path
stringlengths 5
304
| repo_name
stringlengths 6
79
| content
stringlengths 27
1.05M
|
---|---|---|
src/components/NoMatch.js | manar007/react-event-calendar | import React from 'react'
const NoMatch = ({ location }) => {
return <div>
<div className="col-3"></div>
<div className="col-6"> <h1>404</h1> <br/><h3>Not found</h3></div>
<div className="col-3"></div>
</div>
;
};
export default NoMatch |
webpack/ForemanTasks/Components/TasksDashboard/Components/TasksCardsGrid/TasksCardsGrid.js | ares/foreman-tasks | import React from 'react';
import PropTypes from 'prop-types';
import { CardGrid } from 'patternfly-react';
import { noop } from 'foremanReact/common/helpers';
import RunningTasksCard from './Components/RunningTasksCard/RunningTasksCard';
import PausedTasksCard from './Components/PausedTasksCard/PausedTasksCard';
import StoppedTasksCard from './Components/StoppedTasksCard/StoppedTasksCard';
import ScheduledTasksCard from './Components/ScheduledTasksCard/ScheduledTasksCard';
import {
TASKS_DASHBOARD_AVAILABLE_TIMES,
TASKS_DASHBOARD_AVAILABLE_QUERY_STATES,
} from '../../TasksDashboardConstants';
import { timePropType, queryPropType } from '../../TasksDashboardPropTypes';
const TasksCardsGrid = ({ time, query, data, updateQuery }) => (
<CardGrid matchHeight fluid>
<CardGrid.Row>
{[
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.RUNNING, RunningTasksCard],
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.PAUSED, PausedTasksCard],
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.STOPPED, StoppedTasksCard],
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.SCHEDULED, ScheduledTasksCard],
].map(([key, Card]) => (
<CardGrid.Col key={key}>
<Card
matchHeight
data={data[key]}
query={query}
time={time}
updateQuery={updateQuery}
/>
</CardGrid.Col>
))}
</CardGrid.Row>
</CardGrid>
);
TasksCardsGrid.propTypes = {
time: timePropType,
query: queryPropType,
data: PropTypes.shape({
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.RUNNING]:
RunningTasksCard.propTypes.data,
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.PAUSED]:
PausedTasksCard.propTypes.data,
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.STOPPED]:
StoppedTasksCard.propTypes.data,
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.SCHEDULED]:
ScheduledTasksCard.propTypes.data,
}),
updateQuery: PropTypes.func,
};
TasksCardsGrid.defaultProps = {
time: TASKS_DASHBOARD_AVAILABLE_TIMES.H24,
query: {},
data: {
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.RUNNING]:
RunningTasksCard.defaultProps.data,
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.PAUSED]:
PausedTasksCard.defaultProps.data,
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.STOPPED]:
StoppedTasksCard.defaultProps.data,
[TASKS_DASHBOARD_AVAILABLE_QUERY_STATES.SCHEDULED]:
ScheduledTasksCard.defaultProps.data,
},
updateQuery: noop,
};
export default TasksCardsGrid;
|
packages/reactor-kitchensink/src/examples/Msg/Msg.js | markbrocato/extjs-reactor | import React, { Component } from 'react';
import { Container, Button } from '@extjs/ext-react';
Ext.require('Ext.MessageBox');
export default class MsgExample extends Component {
onConfirmResult(buttonId, value, opt) {
Ext.toast(`User clicked ${buttonId} button.`);
}
onPromptResult(buttonId, value) {
Ext.toast(`User clicked ${buttonId} and entered value "${value}".`);
}
render() {
return (
<Container layout="vbox">
<Button
ui="action raised"
margin="0 0 20 0"
handler={() => Ext.Msg.alert('Title', 'The quick brown fox jumped over the lazy dog.')}
text="Alert"
/>
<Button
ui="action raised"
margin="0 0 20 0"
handler={() => Ext.Msg.prompt('Welcome!', "What's your first name?", this.onPromptResult.bind(this))}
text="Prompt"
/>
<Button
ui="action raised"
margin="0 0 20 0"
handler={() => Ext.Msg.confirm("Confirmation", "Are you sure you want to do that?", this.onConfirmResult.bind(this))}
text="Confirm"
/>
</Container>
)
}
} |
jest-setup-wordpress-globals.js | pods-framework/pods | /* global global */
import lodash from 'lodash';
import React from 'react';
import Backbone from 'backbone';
import * as Mn from 'backbone.marionette';
import underscore from 'underscore';
import {
combineReducers,
registerStore,
select,
dispatch,
withSelect,
withDispatch,
} from '@wordpress/data';
global.React = React;
global.lodash = lodash;
global._ = underscore;
global.wp = {
data: {
registerStore,
combineReducers,
select,
dispatch,
withSelect,
withDispatch,
},
};
global.Backbone = Backbone;
global.Backbone.Marionette = Mn;
// @see PodsInit.php
global.PodsMn = Backbone.Marionette.noConflict();
|
src/components/Bottom/Bottom.js | Zoomdata/nhtsa-dashboard | import React from 'react';
import image from '../../images/slot-bottom.png';
const Bottom = () => {
return <img alt="" className="bottom" width="120" height="3.5" src={image} />;
};
export default Bottom;
|
ajax/libs/falcor/0.0.12/falcor.browser.js | honestree/cdnjs | /*!
* Copyright 2014 Netflix, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var falcor = require('./index');
var HttpDataSource = require('falcor-browser');
falcor.HttpDataSource = HttpDataSource;
module.exports = falcor;
},{"./index":2,"falcor-browser":149}],2:[function(require,module,exports){
var falcor = require('./lib/falcor');
var get = require('./lib/get');
var set = require('./lib/set');
var inv = require('./lib/invalidate');
var prototype = falcor.Model.prototype;
prototype._getBoundValue = get.getBoundValue;
prototype._getValueSync = get.getValueSync;
prototype._getPathSetsAsValues = get.getAsValues;
prototype._getPathSetsAsJSON = get.getAsJSON;
prototype._getPathSetsAsPathMap = get.getAsPathMap;
prototype._getPathSetsAsJSONG = get.getAsJSONG;
prototype._getPathMapsAsValues = get.getAsValues;
prototype._getPathMapsAsJSON = get.getAsJSON;
prototype._getPathMapsAsPathMap = get.getAsPathMap;
prototype._getPathMapsAsJSONG = get.getAsJSONG;
prototype._setPathSetsAsJSON = set.setPathSetsAsJSON;
prototype._setPathSetsAsJSONG = set.setPathSetsAsJSONG;
prototype._setPathSetsAsPathMap = set.setPathSetsAsPathMap;
prototype._setPathSetsAsValues = set.setPathSetsAsValues;
prototype._setPathMapsAsJSON = set.setPathMapsAsJSON;
prototype._setPathMapsAsJSONG = set.setPathMapsAsJSONG;
prototype._setPathMapsAsPathMap = set.setPathMapsAsPathMap;
prototype._setPathMapsAsValues = set.setPathMapsAsValues;
prototype._setJSONGsAsJSON = set.setJSONGsAsJSON;
prototype._setJSONGsAsJSONG = set.setJSONGsAsJSONG;
prototype._setJSONGsAsPathMap = set.setJSONGsAsPathMap;
prototype._setJSONGsAsValues = set.setJSONGsAsValues;
prototype._invPathSetsAsJSON = inv.invPathSetsAsJSON;
prototype._invPathSetsAsJSONG = inv.invPathSetsAsJSONG;
prototype._invPathSetsAsPathMap = inv.invPathSetsAsPathMap;
prototype._invPathSetsAsValues = inv.invPathSetsAsValues;
// prototype._setCache = get.setCache;
prototype._setCache = set.setCache;
module.exports = falcor;
},{"./lib/falcor":6,"./lib/get":48,"./lib/invalidate":77,"./lib/set":85}],3:[function(require,module,exports){
if (typeof falcor === 'undefined') {
var falcor = {};
}
var Rx = require('rx');
falcor.__Internals = {};
falcor.Observable = Rx.Observable;
falcor.EXPIRES_NOW = 0;
falcor.EXPIRES_NEVER = 1;
/**
* The current semVer'd data version of falcor.
*/
falcor.dataVersion = '0.1.0';
falcor.now = function now() {
return Date.now();
};
falcor.NOOP = function() {};
module.exports = falcor;
},{"rx":168}],4:[function(require,module,exports){
var falcor = require('./Falcor');
var RequestQueue = require('./request/RequestQueue');
var ImmediateScheduler = require('./scheduler/ImmediateScheduler');
var TimeoutScheduler = require('./scheduler/TimeoutScheduler');
var ERROR = require("../types/error");
var ModelResponse = require('./ModelResponse');
var call = require('./operations/call');
var operations = require('./operations');
var pathSyntax = require('falcor-path-syntax');
var getBoundValue = require('./../get/getBoundValue');
var slice = Array.prototype.slice;
var $ref = require('./../types/path');
var $error = require('./../types/error');
var $sentinel = require('./../types/sentinel');
var Model = module.exports = falcor.Model = function Model(options) {
if (!options) {
options = {};
}
this._materialized = options.materialized || false;
this._boxed = options.boxed || false;
this._treatErrorsAsValues = options.treatErrorsAsValues || false;
this._dataSource = options.source;
this._maxSize = options.maxSize || Math.pow(2, 53) - 1;
this._collectRatio = options.collectRatio || 0.75;
this._scheduler = new ImmediateScheduler();
this._request = new RequestQueue(this, this._scheduler);
this._errorSelector = options.errorSelector || Model.prototype._errorSelector;
this._router = options.router;
this._root = options.root || {
expired: [],
allowSync: 0,
unsafeMode: false
};
if (options.cache && typeof options.cache === "object") {
this.setCache(options.cache);
} else {
this._cache = {};
}
this._path = [];
};
Model.EXPIRES_NOW = falcor.EXPIRES_NOW;
Model.EXPIRES_NEVER = falcor.EXPIRES_NEVER;
Model.ref = function(path) {
if (typeof path === 'string') {
path = pathSyntax(path);
}
return {$type: $ref, value: path};
};
Model.error = function(error) {
return {$type: $error, value: error};
};
Model.atom = function(value) {
return {$type: $sentinel, value: value};
};
Model.prototype = {
_boxed: false,
_progressive: false,
_errorSelector: function(x, y) { return y; },
get: operations("get"),
set: operations("set"),
invalidate: operations("invalidate"),
call: call,
getValue: function(path) {
return this.get(path, function(x) { return x; });
},
setValue: function(path, value) {
path = pathSyntax.fromPath(path);
return this.set(Array.isArray(path) ?
{path: path, value: value} :
path, function(x) { return x; });
},
bind: function(boundPath) {
var model = this, root = model._root,
paths = new Array(arguments.length - 1),
i = -1, n = arguments.length - 1;
boundPath = pathSyntax.fromPath(boundPath);
while(++i < n) {
paths[i] = pathSyntax.fromPath(arguments[i + 1]);
}
if(n === 0) { throw new Error("Model#bind requires at least one value path."); }
return falcor.Observable.create(function(observer) {
var boundModel;
root.allowSync++;
try {
boundModel = model.bindSync(model._path.concat(boundPath));
if (!boundModel) {
throw false;
}
observer.onNext(boundModel);
observer.onCompleted();
} catch (e) {
return model.get.apply(model, paths.map(function(path) {
return boundPath.concat(path);
}).concat(function(){})).subscribe(
function onNext() {},
function onError(err) { observer.onError(err); },
function onCompleted() {
root.allowSync++;
try {
boundModel = model.bindSync(boundPath);
if(boundModel) {
observer.onNext(boundModel);
}
observer.onCompleted();
} catch(e) {
observer.onError(e);
}
// remove the inc
finally {
root.allowSync--;
}
});
}
// remove the inc
finally {
root.allowSync--;
}
});
},
setCache: function(cache) {
return (this._cache = {}) && this._setCache(this, cache);
},
getCache: function() {
var pathmaps = [{}];
var tmpCache = this.boxValues().treatErrorsAsValues().materialize();
tmpCache._getPathMapsAsPathMap(tmpCache, [tmpCache._cache], pathmaps);
return pathmaps[0].json;
},
getValueSync: function(path) {
path = pathSyntax.fromPath(path);
if (Array.isArray(path) === false) {
throw new Error("Model#getValueSync must be called with an Array path.");
}
if (this._path.length) {
path = this._path.concat(path);
}
return this.syncCheck("getValueSync") && this._getValueSync(this, path).value;
},
setValueSync: function(path, value, errorSelector) {
path = pathSyntax.fromPath(path);
if(Array.isArray(path) === false) {
if(typeof errorSelector !== "function") {
errorSelector = value || this._errorSelector;
}
value = path.value;
path = path.path;
}
if(Array.isArray(path) === false) {
throw new Error("Model#setValueSync must be called with an Array path.");
}
if(this.syncCheck("setValueSync")) {
var json = {};
var tEeAV = this._treatErrorsAsValues;
var boxed = this._boxed;
this._treatErrorsAsValues = true;
this._boxed = true;
this._setPathSetsAsJSON(this, [{path: path, value: value}], [json], errorSelector);
this._treatErrorsAsValues = tEeAV;
this._boxed = boxed;
json = json.json;
if(json && json.$type === ERROR && !this._treatErrorsAsValues) {
if(this._boxed) {
throw json;
} else {
throw json.value;
}
} else if(this._boxed) {
return json;
}
return json && json.value;
}
},
bindSync: function(path) {
path = pathSyntax.fromPath(path);
if(Array.isArray(path) === false) {
throw new Error("Model#bindSync must be called with an Array path.");
}
var boundValue = this.syncCheck("bindSync") && getBoundValue(this, this._path.concat(path));
var node = boundValue.value;
path = boundValue.path;
if(boundValue.shorted) {
if(!!node) {
if(node.$type === ERROR) {
if(this._boxed) {
throw node;
}
throw node.value;
// throw new Error("Model#bindSync can\'t bind to or beyond an error: " + boundValue.toString());
}
}
return undefined;
} else if(!!node && node.$type === ERROR) {
if(this._boxed) {
throw node;
}
throw node.value;
}
return this.clone(["_path", boundValue.path]);
},
clone: function() {
var self = this;
var clone = new Model();
var key, keyValue;
var keys = Object.keys(self);
var keysIdx = -1;
var keysLen = keys.length;
while(++keysIdx < keysLen) {
key = keys[keysIdx];
clone[key] = self[key];
}
var argsIdx = -1;
var argsLen = arguments.length;
while(++argsIdx < argsLen) {
keyValue = arguments[argsIdx];
clone[keyValue[0]] = keyValue[1];
}
return clone;
},
batch: function(schedulerOrDelay) {
if(typeof schedulerOrDelay === "number") {
schedulerOrDelay = new TimeoutScheduler(Math.round(Math.abs(schedulerOrDelay)));
} else if(!schedulerOrDelay || !schedulerOrDelay.schedule) {
schedulerOrDelay = new ImmediateScheduler();
}
return this.clone(["_request", new RequestQueue(this, schedulerOrDelay)]);
},
unbatch: function() {
return this.clone(["_request", new RequestQueue(this, new ImmediateScheduler())]);
},
treatErrorsAsValues: function() {
return this.clone(["_treatErrorsAsValues", true]);
},
materialize: function() {
return this.clone(["_materialized", true]);
},
boxValues: function() {
return this.clone(["_boxed", true]);
},
unboxValues: function() {
return this.clone(["_boxed", false]);
},
withoutDataSource: function() {
return this.clone(["_dataSource", null]);
},
syncCheck: function(name) {
if (!!this._dataSource && this._root.allowSync <= 0 && this._root.unsafeMode === false) {
throw new Error("Model#" + name + " may only be called within the context of a request selector.");
}
return true;
}
};
},{"../types/error":135,"./../get/getBoundValue":45,"./../types/error":135,"./../types/path":136,"./../types/sentinel":137,"./Falcor":3,"./ModelResponse":5,"./operations":12,"./operations/call":7,"./request/RequestQueue":37,"./scheduler/ImmediateScheduler":38,"./scheduler/TimeoutScheduler":39,"falcor-path-syntax":152}],5:[function(require,module,exports){
var falcor = require('./Falcor');
var pathSyntax = require('falcor-path-syntax');
if(typeof Promise !== "undefined" && Promise) {
falcor.Promise = Promise;
} else {
falcor.Promise = require("promise");
}
var Observable = falcor.Observable,
valuesMixin = { format: { value: "AsValues" } },
jsonMixin = { format: { value: "AsPathMap" } },
jsongMixin = { format: { value: "AsJSONG" } },
progressiveMixin = { operationIsProgressive: { value: true } };
function ModelResponse(forEach) {
this._subscribe = forEach;
}
ModelResponse.create = function(forEach) {
return new ModelResponse(forEach);
};
ModelResponse.fromOperation = function(model, args, selector, forEach) {
return new ModelResponse(function(observer) {
return forEach(Object.create(observer, {
operationModel: {value: model},
operationArgs: {value: pathSyntax.fromPathsOrPathValues(args)},
operationSelector: {value: selector}
}));
});
};
function noop() {}
function mixin(self) {
var mixins = Array.prototype.slice.call(arguments, 1);
return new ModelResponse(function(other) {
return self.subscribe(mixins.reduce(function(proto, mixin) {
return Object.create(proto, mixin);
}, other));
});
}
ModelResponse.prototype = Observable.create(noop);
ModelResponse.prototype.format = "AsPathMap";
ModelResponse.prototype.toPathValues = function() {
return mixin(this, valuesMixin);
};
ModelResponse.prototype.toJSON = function() {
return mixin(this, jsonMixin);
};
ModelResponse.prototype.progressively = function() {
return mixin(this, progressiveMixin);
};
ModelResponse.prototype.toJSONG = function() {
return mixin(this, jsongMixin);
};
ModelResponse.prototype.then = function(onNext, onError) {
var self = this;
return new falcor.Promise(function(resolve, reject) {
setTimeout(function() {
var value = undefined;
var error = undefined;
self.toArray().subscribe(
function(values) {
if(values.length <= 1) {
value = values[0];
} else {
value = values;
}
},
function(errors) {
if(errors.length <= 1) {
error = errors[0];
} else {
error = errors;
}
resolve = undefined;
},
function() {
if(!!resolve) {
resolve(value);
} else {
reject(error);
}
}
);
}, 0);
}).then(onNext, onError);
};
module.exports = ModelResponse;
},{"./Falcor":3,"falcor-path-syntax":152,"promise":158}],6:[function(require,module,exports){
var falcor = require('./Falcor');
var Model = require('./Model');
falcor.Model = Model;
module.exports = falcor;
},{"./Falcor":3,"./Model":4}],7:[function(require,module,exports){
module.exports = call;
var falcor = require("../../Falcor");
var ModelResponse = require('./../../ModelResponse');
function call(path, args, suffixes, paths, selector) {
var model = this;
args && Array.isArray(args) || (args = []);
suffixes && Array.isArray(suffixes) || (suffixes = []);
paths = Array.prototype.slice.call(arguments, 3);
if (typeof (selector = paths[paths.length - 1]) !== "function") {
selector = undefined;
} else {
paths = paths.slice(0, -1);
}
return ModelResponse.create(function (options) {
var rootModel = model.clone(["_path", []]),
localRoot = rootModel.withoutDataSource(),
dataSource = model._dataSource,
boundPath = model._path,
callPath = boundPath.concat(path),
thisPath = callPath.slice(0, -1);
var disposable = model.
getValue(path).
flatMap(function (localFn) {
if (typeof localFn === "function") {
return falcor.Observable.return(localFn.
apply(rootModel.bindSync(thisPath), args).
map(function (pathValue) {
return {
path: thisPath.concat(pathValue.path),
value: pathValue.value
};
}).
toArray().
flatMap(function (pathValues) {
return localRoot.set.
apply(localRoot, pathValues).
toJSONG();
}).
flatMap(function (envelope) {
return rootModel.get.apply(rootModel,
envelope.paths.reduce(function (paths, path) {
return paths.concat(suffixes.map(function (suffix) {
return path.concat(suffix);
}));
}, []).
concat(paths.reduce(function (paths, path) {
return paths.concat(thisPath.concat(path));
}, []))).
toJSONG();
}));
}
return falcor.Observable.empty();
}).
defaultIfEmpty(dataSource.call(path, args, suffixes, paths)).
mergeAll().
subscribe(function (envelope) {
var invalidated = envelope.invalidated;
if (invalidated && invalidated.length) {
invalidatePaths(rootModel, invalidated, undefined, model._errorSelector);
}
disposable = localRoot.
set(envelope, function () {
return model;
}).
subscribe(function (model) {
var getPaths = envelope.paths.map(function (path) {
return path.slice(boundPath.length);
});
if (selector) {
getPaths[getPaths.length] = function () {
return selector.call(model, getPaths);
};
}
disposable = model.get.apply(model, getPaths).subscribe(options);
});
});
return {
dispose: function () {
disposable && disposable.dispose();
disposable = undefined;
}
};
});
}
},{"../../Falcor":3,"./../../ModelResponse":5}],8:[function(require,module,exports){
var combineOperations = require('./../support/combineOperations');
var setSeedsOrOnNext = require('./../support/setSeedsOrOnNext');
/**
* The initial args that are passed into the async request pipeline.
* @see lib/falcor/operations/request.js for how initialArgs are used
*/
module.exports = function getInitialArgs(options, seeds, onNext) {
var seedRequired = options.format !== 'AsValues';
var isProgressive = options.operationIsProgressive;
var spreadOperations = false;
var operations =
combineOperations(
options.operationArgs, options.format, 'get',
spreadOperations, isProgressive);
setSeedsOrOnNext(
operations, seedRequired, seeds, onNext, options.operationSelector);
var requestOptions;
return [operations];
};
},{"./../support/combineOperations":23,"./../support/setSeedsOrOnNext":36}],9:[function(require,module,exports){
var getSourceObserver = require('./../support/getSourceObserever');
var partitionOperations = require('./../support/partitionOperations');
var mergeBoundPath = require('./../support/mergeBoundPath');
module.exports = getSourceRequest;
function getSourceRequest(
options, onNext, seeds, combinedResults, requestOptions, cb) {
var model = options.operationModel;
var boundPath = model._path;
var missingPaths = combinedResults.requestedMissingPaths;
if (boundPath.length) {
for (var i = 0; i < missingPaths.length; ++i) {
var pathSetIndex = missingPaths[i].pathSetIndex;
var path = missingPaths[i] = boundPath.concat(missingPaths[i]);
path.pathSetIndex = pathSetIndex;
}
}
return model._request.get(
missingPaths,
combinedResults.optimizedMissingPaths,
getSourceObserver(
model,
missingPaths,
function getSourceCallback(err, results) {
if (err) {
cb(err);
return;
}
// partitions the operations by their pathSetIndex
var partitionOperationsAndSeeds = partitionOperations(
results,
seeds,
options.format,
onNext);
// We allow for the rerequesting to happen.
cb(null, partitionOperationsAndSeeds);
}));
}
},{"./../support/getSourceObserever":24,"./../support/mergeBoundPath":28,"./../support/partitionOperations":31}],10:[function(require,module,exports){
var getInitialArgs = require('./getInitialArgs');
var getSourceRequest = require('./getSourceRequest');
var shouldRequest = require('./shouldRequest');
var request = require('./../request');
var processOperations = require('./../support/processOperations');
var get = request(
getInitialArgs,
getSourceRequest,
processOperations,
shouldRequest);
module.exports = get;
},{"./../request":15,"./../support/processOperations":33,"./getInitialArgs":8,"./getSourceRequest":9,"./shouldRequest":11}],11:[function(require,module,exports){
module.exports = function(model, combinedResults) {
return model._dataSource && combinedResults.requestedMissingPaths.length > 0;
};
},{}],12:[function(require,module,exports){
var ModelResponse = require('../ModelResponse');
var get = require('./get');
var set = require('./set');
var invalidate = require('./invalidate');
module.exports = function modelOperation(name) {
return function() {
var model = this, root = model._root,
args = Array.prototype.slice.call(arguments),
selector = args[args.length - 1];
if (typeof selector === 'function') {
args.pop();
} else {
selector = false;
}
var modelResponder;
switch (name) {
case 'get':
modelResponder = get;
break;
case 'set':
modelResponder = set;
break;
case 'invalidate':
modelResponder = invalidate;
break;
}
return ModelResponse.fromOperation(
model,
args,
selector,
modelResponder);
};
};
},{"../ModelResponse":5,"./get":10,"./invalidate":13,"./set":16}],13:[function(require,module,exports){
var invalidateInitialArgs = require('./invalidateInitialArgs');
var request = require('./../request');
var processOperations = require('./../support/processOperations');
var invalidate = request(
invalidateInitialArgs,
null,
processOperations);
module.exports = invalidate;
},{"./../request":15,"./../support/processOperations":33,"./invalidateInitialArgs":14}],14:[function(require,module,exports){
var combineOperations = require('./../support/combineOperations');
var setSeedsOrOnNext = require('./../support/setSeedsOrOnNext');
module.exports = function getInitialArgs(options, seeds, onNext) {
var seedRequired = options.format !== 'AsValues';
var operations = combineOperations(
options.operationArgs, options.format, 'inv');
setSeedsOrOnNext(
operations, seedRequired, seeds,
onNext, options.operationSelector);
return [operations, seeds];
};
},{"./../support/combineOperations":23,"./../support/setSeedsOrOnNext":36}],15:[function(require,module,exports){
var setSeedsOrOnNext = require('./support/setSeedsOrOnNext');
var onNextValues = require('./support/onNextValue');
var onCompletedOrError = require('./support/onCompletedOrError');
var primeSeeds = require('./support/primeSeeds');
var autoFalse = function() { return false; };
module.exports = request;
function request(initialArgs, sourceRequest, processOperations, shouldRequestFn) {
if (!shouldRequestFn) {
shouldRequestFn = autoFalse;
}
return function innerRequest(options) {
var selector = options.operationSelector;
var model = options.operationModel;
var args = options.operationArgs;
var onNext = options.onNext.bind(options);
var onError = options.onError.bind(options);
var onCompleted = options.onCompleted.bind(options);
var isProgressive = options.operationIsProgressive;
var errorSelector = model._errorSelector;
var selectorLength = selector && selector.length || 0;
// State variables
var errors = [];
var format = options.format = selector && 'AsJSON' ||
options.format || 'AsPathMap';
var toJSONG = format === 'AsJSONG';
var toJSON = format === 'AsPathMap';
var toPathValues = format === 'AsValues';
var seedRequired = toJSON || toJSONG || selector;
var boundPath = model._path;
var i, len;
var foundValue = false;
var seeds = primeSeeds(selector, selectorLength);
var loopCount = 0;
function recurse(operations, opts) {
if (loopCount > 50) {
throw 'Loop Kill switch thrown.';
}
var combinedResults = processOperations(
model,
operations,
errorSelector,
opts);
foundValue = foundValue || combinedResults.valuesReceived;
if (combinedResults.errors.length) {
errors = errors.concat(combinedResults.errors);
}
// if in progressiveMode, values are emitted
// each time through the recurse loop. This may have
// to change when the router is considered.
if (isProgressive && !toPathValues) {
onNextValues(model, onNext, seeds, selector);
}
// Performs the recursing via dataSource
if (shouldRequestFn(model, combinedResults, loopCount)) {
sourceRequest(
options,
onNext,
seeds,
combinedResults,
opts,
function onCompleteFromSourceSet(err, results) {
if (err) {
errors = errors.concat(err);
recurse([], seeds);
return;
}
++loopCount;
// We continue to string the opts through
recurse(results, opts);
});
}
// Else we need to onNext values and complete/error.
else {
if (!toPathValues && !isProgressive && foundValue) {
onNextValues(model, onNext, seeds, selector);
}
onCompletedOrError(onCompleted, onError, errors);
}
}
try {
recurse.apply(null,
initialArgs(options, seeds, onNext));
} catch(e) {
errors = [e];
onCompletedOrError(onCompleted, onError, errors);
}
};
}
},{"./support/onCompletedOrError":29,"./support/onNextValue":30,"./support/primeSeeds":32,"./support/setSeedsOrOnNext":36}],16:[function(require,module,exports){
var setInitialArgs = require('./setInitialArgs');
var setSourceRequest = require('./setSourceRequest');
var request = require('./../request');
var setProcessOperations = require('./setProcessOperations');
var shouldRequest = require('./shouldRequest');
var set = request(
setInitialArgs,
setSourceRequest,
setProcessOperations,
shouldRequest);
module.exports = set;
},{"./../request":15,"./setInitialArgs":17,"./setProcessOperations":18,"./setSourceRequest":19,"./shouldRequest":20}],17:[function(require,module,exports){
var combineOperations = require('./../support/combineOperations');
var setSeedsOrOnNext = require('./../support/setSeedsOrOnNext');
var Formats = require('./../support/Formats');
var toPathValues = Formats.toPathValues;
var toJSONG = Formats.toJSONG;
module.exports = function setInitialArgs(options, seeds, onNext) {
var isPathValues = options.format === toPathValues;
var seedRequired = !isPathValues;
var shouldRequest = !!options.operationModel._dataSource;
var format = options.format;
var args = options.operationArgs;
var selector = options.operationSelector;
var isProgressive = options.operationIsProgressive;
var firstSeeds, operations;
var requestOptions = {
removeBoundPath: shouldRequest
};
// If Model is a slave, in shouldRequest mode,
// a single seed is required to accumulate the jsong results.
if (shouldRequest) {
operations =
combineOperations(args, toJSONG, 'set', selector, false);
firstSeeds = [{}];
setSeedsOrOnNext(
operations, true, firstSeeds, false, options.selector);
// we must keep track of the set seeds.
requestOptions.requestSeed = firstSeeds[0];
}
// This model is the master, therefore a regular set can be performed.
else {
firstSeeds = seeds;
operations = combineOperations(args, format, 'set');
setSeedsOrOnNext(
operations, seedRequired, seeds, onNext, options.operationSelector);
}
// We either have to construct the master operations if
// the ModelResponse is isProgressive
// the ModelResponse is toPathValues
// but luckily we can just perform a get for the progressive or
// toPathValues mode.
if (isProgressive || isPathValues) {
var getOps = combineOperations(
args, format, 'get', selector, true);
setSeedsOrOnNext(
getOps, seedRequired, seeds, onNext, options.operationSelector);
operations = operations.concat(getOps);
requestOptions.isProgressive = true;
}
return [operations, requestOptions];
};
},{"./../support/Formats":21,"./../support/combineOperations":23,"./../support/setSeedsOrOnNext":36}],18:[function(require,module,exports){
var processOperations = require('./../support/processOperations');
var combineOperations = require('./../support/combineOperations');
var mergeBoundPath = require('./../support/mergeBoundPath');
var Formats = require('./../support/Formats');
var toPathValues = Formats.toPathValues;
module.exports = setProcessOperations;
function setProcessOperations(model, operations, errorSelector, requestOptions) {
var boundPath = model._path;
var hasBoundPath = boundPath.length > 0;
var removeBoundPath = requestOptions && requestOptions.removeBoundPath;
var isProgressive = requestOptions && requestOptions.isProgressive;
var progressiveOperations;
// if in progressive mode, then the progressive operations
// need to be executed but the bound path must stay intact.
if (isProgressive && removeBoundPath && hasBoundPath) {
progressiveOperations = operations.filter(function(op) {
return op.isProgressive;
});
operations = operations.filter(function(op) {
return !op.isProgressive;
});
}
if (removeBoundPath && hasBoundPath) {
model._path = [];
// For every operations arguments, the bound path must be adjusted.
for (var i = 0, opLen = operations.length; i < opLen; i++) {
var args = operations[i].args;
for (var j = 0, argsLen = args.length; j < argsLen; j++) {
args[j] = mergeBoundPath(args[j], boundPath);
}
}
}
var results = processOperations(model, operations, errorSelector);
// Undo what we have done to the model's bound path.
if (removeBoundPath && hasBoundPath) {
model._path = boundPath;
}
// executes the progressive ops
if (progressiveOperations) {
processOperations(model, progressiveOperations, errorSelector);
}
return results;
}
},{"./../support/Formats":21,"./../support/combineOperations":23,"./../support/mergeBoundPath":28,"./../support/processOperations":33}],19:[function(require,module,exports){
var getSourceObserver = require('./../support/getSourceObserever');
var combineOperations = require('./../support/combineOperations');
var setSeedsOrOnNext = require('./../support/setSeedsOrOnNext');
var toPathValues = require('./../support/Formats').toPathValues;
module.exports = setSourceRequest;
function setSourceRequest(
options, onNext, seeds, combinedResults, requestOptions, cb) {
var model = options.operationModel;
var seedRequired = options.format !== toPathValues;
var requestSeed = requestOptions.requestSeed;
return model._request.set(
requestSeed,
getSourceObserver(
model,
requestSeed.paths,
function setSourceRequestCB(err, results) {
if (err) {
cb(err);
}
// Sets the results into the model.
model._setJSONGsAsJSON(model, [results], []);
// Gets the original paths / maps back out.
var operations = combineOperations(
options.operationArgs, options.format, 'get');
setSeedsOrOnNext(
operations, seedRequired,
seeds, onNext, options.operationSelector);
// unset the removeBoundPath.
requestOptions.removeBoundPath = false;
cb(null, operations);
}));
}
},{"./../support/Formats":21,"./../support/combineOperations":23,"./../support/getSourceObserever":24,"./../support/setSeedsOrOnNext":36}],20:[function(require,module,exports){
// Set differs from get in the sense that the first time through
// the recurse loop a server operation must be performed if it can be.
module.exports = function(model, combinedResults, loopCount) {
return model._dataSource && (
combinedResults.requestedMissingPaths.length > 0 ||
loopCount === 0);
};
},{}],21:[function(require,module,exports){
module.exports = {
toPathValues: 'AsValues',
toJSON: 'AsPathMap',
toJSONG: 'AsJSONG',
selector: 'AsJSON',
};
},{}],22:[function(require,module,exports){
module.exports = function buildJSONGOperation(format, seeds, jsongOp, seedOffset, onNext) {
return {
methodName: '_setJSONGs' + format,
format: format,
isValues: format === 'AsValues',
onNext: onNext,
seeds: seeds,
seedsOffset: seedOffset,
args: [jsongOp]
};
};
},{}],23:[function(require,module,exports){
var isSeedRequired = require('./seedRequired');
var isJSONG = require('./isJSONG');
var isPathOrPathValue = require('./isPathOrPathValue');
var Formats = require('./Formats');
var toSelector = Formats.selector;
module.exports = function combineOperations(args, format, name, spread, isProgressive) {
var seedRequired = isSeedRequired(format);
var isValues = !seedRequired;
var hasSelector = seedRequired && format === toSelector;
var seedsOffset = 0;
return args.
reduce(function(groups, argument) {
var group = groups[groups.length - 1];
var type = isPathOrPathValue(argument) ? "PathSets" :
isJSONG(argument) ? "JSONGs" : "PathMaps";
var groupType = group && group.type;
var methodName = '_' + name + type + format;
if (!groupType || type !== groupType || spread) {
group = {
methodName: methodName,
format: format,
operation: name,
isValues: isValues,
seeds: [],
onNext: null,
seedsOffset: seedsOffset,
isProgressive: isProgressive,
type: type,
args: []
};
groups.push(group);
}
if (hasSelector) {
++seedsOffset;
}
group.args.push(argument);
return groups;
}, []);
};
},{"./Formats":21,"./isJSONG":26,"./isPathOrPathValue":27,"./seedRequired":34}],24:[function(require,module,exports){
var insertErrors = require('./insertErrors.js');
/**
* creates the model source observer
* @param {Model} model
* @param {Array.<Array>} requestedMissingPaths
* @param {Function} cb
*/
function getSourceObserver(model, requestedMissingPaths, cb) {
var incomingValues;
return {
onNext: function(jsongEnvelop) {
incomingValues = {
jsong: jsongEnvelop.jsong,
paths: requestedMissingPaths
};
},
onError: function(err) {
cb(insertErrors(model, requestedMissingPaths, err));
},
onCompleted: function() {
cb(false, incomingValues);
}
};
}
module.exports = getSourceObserver;
},{"./insertErrors.js":25}],25:[function(require,module,exports){
/**
* will insert the error provided for every requestedPath.
* @param {Model} model
* @param {Array.<Array>} requestedPaths
* @param {Object} err
*/
module.exports = function insertErrors(model, requestedPaths, err) {
var out = model._setPathSetsAsJSON.apply(null, [model].concat(
requestedPaths.
reduce(function(acc, r) {
acc[0].push({
path: r,
value: err
});
return acc;
}, [[]]),
[],
model._errorSelector
));
return out.errors;
};
},{}],26:[function(require,module,exports){
module.exports = function isJSONG(x) {
return x.hasOwnProperty("jsong");
};
},{}],27:[function(require,module,exports){
module.exports = function isPathOrPathValue(x) {
return !!(Array.isArray(x)) || (
x.hasOwnProperty("path") && x.hasOwnProperty("value"));
};
},{}],28:[function(require,module,exports){
var isJSONG = require('./isJSONG');
var isPathValue = require('./isPathOrPathValue');
module.exports = mergeBoundPath;
function mergeBoundPath(arg, boundPath) {
return isJSONG(arg) && mergeBoundPathIntoJSONG(arg, boundPath) ||
isPathValue(arg) && mergeBoundPathIntoPathValue(arg, boundPath) ||
mergeBoundPathIntoJSON(arg, boundPath);
}
function mergeBoundPathIntoJSONG(jsongEnv, boundPath) {
var newJSONGEnv = {jsong: jsongEnv.jsong, paths: jsongEnv.paths};
if (boundPath.length) {
var paths = [];
for (i = 0, len = jsongEnv.paths.length; i < len; i++) {
paths[i] = boundPath.concat(jsongEnv.paths[i]);
}
newJSONGEnv.paths = paths;
}
return newJSONGEnv;
}
function mergeBoundPathIntoJSON(arg, boundPath) {
var newArg = arg;
if (boundPath.length) {
newArg = {};
for (var i = 0, len = boundPath.length - 1; i < len; i++) {
newArg[boundPath[i]] = {};
}
newArg[boundPath[i]] = arg;
}
return newArg;
}
function mergeBoundPathIntoPathValue(arg, boundPath) {
return {
path: boundPath.concat(arg.path),
value: arg.value
};
}
},{"./isJSONG":26,"./isPathOrPathValue":27}],29:[function(require,module,exports){
module.exports = function onCompletedOrError(onCompleted, onError, errors) {
if (errors.length) {
onError(errors);
} else {
onCompleted();
}
};
},{}],30:[function(require,module,exports){
/**
* will onNext the observer with the seeds provided.
* @param {Model} model
* @param {Function} onNext
* @param {Array.<Object>} seeds
* @param {Function} [selector]
*/
module.exports = function onNextValues(model, onNext, seeds, selector) {
var root = model._root;
root.allowSync++;
try {
if (selector) {
if (seeds.length) {
// they should be wrapped in json items
onNext(selector.apply(model, seeds.map(function(x, i) {
return x.json;
})));
} else {
onNext(selector.call(model));
}
} else {
// this means there is an onNext function that is not AsValues or progressive,
// therefore there must only be one onNext call, which should only be the 0
// index of the values of the array
onNext(seeds[0]);
}
} catch(e) {
} finally {
root.allowSync--;
}
};
},{}],31:[function(require,module,exports){
var buildJSONGOperation = require('./buildJSONGOperation');
/**
* It performs the opposite of combine operations. It will take a JSONG
* response and partition them into the required amount of operations.
* @param {{jsong: {}, paths:[]}} jsongResponse
*/
module.exports = partitionOperations;
function partitionOperations(
jsongResponse, seeds, format, onNext) {
var partitionedOps = [];
var requestedMissingPaths = jsongResponse.paths;
if (format === 'AsJSON') {
// fast collapse ass the requestedMissingPaths into their
// respective groups
var opsFromRequestedMissingPaths = [];
var op = null;
for (var i = 0, len = requestedMissingPaths.length; i < len; i++) {
var missingPath = requestedMissingPaths[i];
if (!op || op.idx !== missingPath.pathSetIndex) {
op = {
idx: missingPath.pathSetIndex,
paths: []
};
opsFromRequestedMissingPaths.push(op);
}
op.paths.push(missingPath);
}
opsFromRequestedMissingPaths.forEach(function(op, i) {
var seed = [seeds[op.idx]];
var jsong = {
jsong: jsongResponse.jsong,
paths: op.paths
};
partitionedOps.push(buildJSONGOperation(
format,
seed,
jsong,
op.idx,
onNext));
});
} else {
partitionedOps[0] = buildJSONGOperation(format, seeds, jsongResponse, 0, onNext);
}
return partitionedOps;
}
},{"./buildJSONGOperation":22}],32:[function(require,module,exports){
module.exports = function primeSeeds(selector, selectorLength) {
var seeds = [];
if (selector) {
for (i = 0; i < selectorLength; i++) {
seeds.push({});
}
} else {
seeds[0] = {};
}
return seeds;
};
},{}],33:[function(require,module,exports){
module.exports = function processOperations(model, operations, errorSelector, boundPath) {
return operations.reduce(function(memo, operation) {
var jsonGraphOperation = model[operation.methodName];
var seedsOrFunction = operation.isValues ?
operation.onNext : operation.seeds;
var results = jsonGraphOperation(
model,
operation.args,
seedsOrFunction,
operation.onNext,
errorSelector,
boundPath);
var missing = results.requestedMissingPaths;
var offset = operation.seedsOffset;
for (var i = 0, len = missing.length; i < len; i++) {
missing[i].boundPath = boundPath;
missing[i].pathSetIndex += offset;
}
memo.requestedMissingPaths = memo.requestedMissingPaths.concat(missing);
memo.optimizedMissingPaths = memo.optimizedMissingPaths.concat(results.optimizedMissingPaths);
memo.errors = memo.errors.concat(results.errors);
memo.valuesReceived = memo.valuesReceived || results.requestedPaths.length > 0;
return memo;
}, {
errors: [],
requestedMissingPaths: [],
optimizedMissingPaths: [],
valuesReceived: false
});
}
},{}],34:[function(require,module,exports){
module.exports = function isSeedRequired(format) {
return format === 'AsJSON' || format === 'AsJSONG' || format === 'AsPathMap';
};
},{}],35:[function(require,module,exports){
module.exports = function setSeedsOnGroups(groups, seeds, hasSelector) {
var valueIndex = 0;
var seedsLength = seeds.length;
var j, i, len = groups.length, gLen, group;
if (hasSelector) {
for (i = 0; i < len && valueIndex < seedsLength; i++) {
group = groups[i];
gLen = gLen = group.args.length;
for (j = 0; j < gLen && valueIndex < seedsLength; j++, valueIndex++) {
group.seeds.push(seeds[valueIndex]);
}
}
} else {
for (i = 0; i < len && valueIndex < seedsLength; i++) {
groups[i].seeds = seeds;
}
}
}
},{}],36:[function(require,module,exports){
var setSeedsOnGroups = require('./setSeedsOnGroups');
module.exports = function setSeedsOrOnNext(operations, seedRequired, seeds, onNext, selector) {
if (seedRequired) {
setSeedsOnGroups(operations, seeds, selector);
} else {
for (i = 0; i < operations.length; i++) {
operations[i].onNext = onNext;
}
}
};
},{"./setSeedsOnGroups":35}],37:[function(require,module,exports){
var falcor = require('./../Falcor');
var NOOP = falcor.NOOP;
var RequestQueue = function(jsongModel, scheduler) {
this._scheduler = scheduler;
this._jsongModel = jsongModel;
this._scheduled = false;
this._requests = [];
};
RequestQueue.prototype = {
_get: function() {
var i = -1;
var requests = this._requests;
while (++i < requests.length) {
if (!requests[i].pending && requests[i].isGet) {
return requests[i];
}
}
return requests[requests.length] = new GetRequest(this._jsongModel, this);
},
_set: function() {
var i = -1;
var requests = this._requests;
// TODO: Set always sends off a request immediately, so there is no batching.
while (++i < requests.length) {
if (!requests[i].pending && requests[i].isSet) {
return requests[i];
}
}
return requests[requests.length] = new SetRequest(this._jsongModel, this);
},
remove: function(request) {
for (var i = this._requests.length - 1; i > -1; i--) {
if (this._requests[i].id === request.id && this._requests.splice(i, 1)) {
break;
}
}
},
set: function(jsongEnv, observer) {
var self = this;
var disposable = self._set().batch(jsongEnv, observer).flush();
return {
dispose: function() {
disposable.dispose();
}
};
},
get: function(requestedPaths, optimizedPaths, observer) {
var self = this;
var disposable = null;
// TODO: get does not batch across requests.
self._get().batch(requestedPaths, optimizedPaths, observer);
if (!self._scheduled) {
self._scheduled = true;
disposable = self._scheduler.schedule(self._flush.bind(self));
}
return {
dispose: function() {
disposable.dispose();
}
};
},
_flush: function() {
this._scheduled = false;
var requests = this._requests, i = -1;
var disposables = [];
while (++i < requests.length) {
if (!requests[i].pending) {
disposables[disposables.length] = requests[i].flush();
}
}
return {
dispose: function() {
disposables.forEach(function(d) { d.dispose(); });
}
};
}
};
var REQUEST_ID = 0;
var SetRequest = function(model, queue) {
var self = this;
self._jsongModel = model;
self._queue = queue;
self.observers = [];
self.jsongEnvs = [];
self.pending = false;
self.id = ++REQUEST_ID;
self.isSet = true;
};
SetRequest.prototype = {
batch: function(jsongEnv, observer) {
var self = this;
observer.onNext = observer.onNext || NOOP;
observer.onError = observer.onError || NOOP;
observer.onCompleted = observer.onCompleted || NOOP;
if (!observer.__observerId) {
observer.__observerId = ++REQUEST_ID;
}
observer._requestId = self.id;
self.observers[self.observers.length] = observer;
self.jsongEnvs[self.jsongEnvs.length] = jsongEnv;
return self;
},
flush: function() {
var incomingValues, query, op, len;
var self = this;
var jsongs = self.jsongEnvs;
var observers = self.observers;
var model = self._jsongModel;
self.pending = true;
// TODO: Set does not batch.
return model._dataSource.
set(jsongs[0]).
subscribe(function(response) {
incomingValues = response;
}, function(err) {
var i = -1;
var n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onError && obs.onError(err);
}
}, function() {
var i, n, obs;
self._queue.remove(self);
i = -1;
n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onNext && obs.onNext({
jsong: incomingValues.jsong || incomingValues.value,
paths: incomingValues.paths
});
obs.onCompleted && obs.onCompleted();
}
});
}
};
var GetRequest = function(jsongModel, queue) {
var self = this;
self._jsongModel = jsongModel;
self._queue = queue;
self.observers = [];
self.optimizedPaths = [];
self.requestedPaths = [];
self.pending = false;
self.id = ++REQUEST_ID;
self.isGet = true;
};
GetRequest.prototype = {
batch: function(requestedPaths, optimizedPaths, observer) {
// TODO: Do we need to gap fill?
var self = this;
observer.onNext = observer.onNext || NOOP;
observer.onError = observer.onError || NOOP;
observer.onCompleted = observer.onCompleted || NOOP;
if (!observer.__observerId) {
observer.__observerId = ++REQUEST_ID;
}
observer._requestId = self.id;
self.observers[self.observers.length] = observer;
self.optimizedPaths[self.optimizedPaths.length] = optimizedPaths;
self.requestedPaths[self.requestedPaths.length] = requestedPaths;
return self;
},
flush: function() {
var incomingValues, query, op, len;
var self = this;
var requested = self.requestedPaths;
var optimized = self.optimizedPaths;
var observers = self.observers;
var disposables = [];
var results = [];
var model = self._jsongModel;
self._scheduled = false;
self.pending = true;
var optimizedMaps = {};
var requestedMaps = {};
var r, o, i, j, obs, resultIndex;
for (i = 0, len = requested.length; i < len; i++) {
r = requested[i];
o = optimized[i];
obs = observers[i];
for (j = 0; j < r.length; j++) {
pathsToMapWithObservers(r[j], 0, readyNode(requestedMaps, null, obs), obs);
pathsToMapWithObservers(o[j], 0, readyNode(optimizedMaps, null, obs), obs);
}
}
return model._dataSource.
get(collapse(optimizedMaps)).
subscribe(function(response) {
incomingValues = response;
}, function(err) {
var i = -1;
var n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onError && obs.onError(err);
}
}, function() {
var i, n, obs;
self._queue.remove(self);
i = -1;
n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onNext && obs.onNext({
jsong: incomingValues.jsong || incomingValues.value,
paths: incomingValues.paths
});
obs.onCompleted && obs.onCompleted();
}
});
},
// Returns the paths that are contained within this request.
contains: function(requestedPaths, optimizedPaths) {
// TODO:
}
};
function pathsToMapWithObservers(path, idx, branch, observer) {
var curr = path[idx];
// Object / Array
if (typeof curr === 'object') {
if (Array.isArray(curr)) {
curr.forEach(function(v) {
readyNode(branch, v, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[v], observer);
}
});
} else {
var from = curr.from || 0;
var to = curr.to >= 0 ? curr.to : curr.length;
for (var i = from; i <= to; i++) {
readyNode(branch, i, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[i], observer);
}
}
}
} else {
readyNode(branch, curr, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[curr], observer);
}
}
}
/**
* Builds the set of collapsed
* queries by traversing the tree
* once
*/
var charPattern = /\D/i;
function readyNode(branch, key, observer) {
if (key === null) {
branch.__observers = branch.__observers || [];
!containsObserver(branch.__observers, observer) && branch.__observers.push(observer);
return branch;
}
if (!branch[key]) {
branch[key] = {__observers: []};
}
!containsObserver(branch[key].__observers, observer) && branch[key].__observers.push(observer);
return branch;
}
function containsObserver(observers, observer) {
if (!observer) {
return;
}
return observers.reduce(function(acc, x) {
return acc || x.__observerId === observer.__observerId;
}, false);
}
function collapse(pathMap) {
return rangeCollapse(buildQueries(pathMap));
}
/**
* Collapse ranges, e.g. when there is a continuous range
* in an array, turn it into an object instead
*
* [1,2,3,4,5,6] => {"from":1, "to":6}
*
*/
function rangeCollapse(paths) {
paths.forEach(function (path) {
path.forEach(function (elt, index) {
var range;
if (Array.isArray(elt) && elt.every(isNumber) && allUnique(elt)) {
elt.sort(function(a, b) {
return a - b;
});
if (elt[elt.length-1] - elt[0] === elt.length-1) {
// create range
range = {};
range.from = elt[0];
range.to = elt[elt.length-1];
path[index] = range;
}
}
});
});
return paths;
}
/* jshint forin: false */
function buildQueries(root) {
if (root == null || typeof root !== 'object') {
return [ [] ];
}
var children = Object.keys(root).filter(notPathMapInternalKeys),
child, memo, paths, key, childIsNum,
list, head, tail, clone, results,
i = -1, n = children.length,
j, k, x;
if (n === 0 || Array.isArray(root) === true) {
return [ [] ];
}
memo = {};
while(++i < n) {
child = children[i];
paths = buildQueries(root[child]);
key = createKey(paths);
childIsNum = typeof child === 'string' && !charPattern.test(child);
if ((list = memo[key]) && (head = list.head)) {
head[head.length] = childIsNum ? parseInt(child, 10) : child;
} else {
memo[key] = {
head: [childIsNum ? parseInt(child, 10) : child],
tail: paths
};
}
}
results = [];
for(x in memo) {
head = (list = memo[x]).head;
tail = list.tail;
i = -1;
n = tail.length;
while(++i < n) {
list = tail[i];
j = -1;
k = list.length;
if(head[0] === '') {
clone = [];
} else {
clone = [head.length === 1 ? head[0] : head];
while(++j < k) {
clone[j + 1] = list[j];
}
}
results[results.length] = clone;
}
}
return results;
}
function notPathMapInternalKeys(key) {
return (
key !== "__observers" &&
key !== "__pending" &&
key !== "__batchID"
);
}
/**
* Return true if argument is a number
*/
function isNumber(val) {
return typeof val === "number";
}
/**
* allUnique
* return true if every number in an array is unique
*/
function allUnique(arr) {
var hash = {},
index,
len;
for (index = 0, len = arr.length; index < len; index++) {
if (hash[arr[index]]) {
return false;
}
hash[arr[index]] = true;
}
return true;
}
/**
* Sort a list-of-lists
* Used for generating a unique hash
* key for each subtree; used by the
* memoization
*/
function sortLol(lol) {
return lol.reduce(function (result, curr) {
if (curr instanceof Array) {
result.push(sortLol(curr).slice(0).sort());
return result;
}
return result.concat(curr);
}, []).slice(0).sort();
}
/**
* Create a unique hash key for a set
* of paths
*/
function createKey(list) {
return JSON.stringify(sortLol(list));
}
// Note: For testing
falcor.__Internals.buildQueries = buildQueries;
module.exports = RequestQueue;
},{"./../Falcor":3}],38:[function(require,module,exports){
function ImmediateScheduler() {
}
ImmediateScheduler.prototype = {
schedule: function(action) {
action();
}
};
module.exports = ImmediateScheduler;
},{}],39:[function(require,module,exports){
function TimeoutScheduler(delay) {
this.delay = delay;
}
TimeoutScheduler.prototype = {
schedule: function(action) {
setTimeout(action, this.delay);
}
};
module.exports = TimeoutScheduler;
},{}],40:[function(require,module,exports){
var hardLink = require('./util/hardlink');
var createHardlink = hardLink.create;
var onValue = require('./onValue');
var isExpired = require('./util/isExpired');
var $path = require('./../types/path.js');
var __context = require("../internal/context");
function followReference(model, root, node, referenceContainer, reference, seed, outputFormat) {
var depth = 0;
var k, next;
while (true) {
if (depth === 0 && referenceContainer[__context]) {
depth = reference.length;
next = referenceContainer[__context];
} else {
k = reference[depth++];
next = node[k];
}
if (next) {
var type = next.$type;
var value = type && next.value || next;
if (depth < reference.length) {
if (type) {
node = next;
break;
}
node = next;
continue;
}
// We need to report a value or follow another reference.
else {
node = next;
if (type && isExpired(next)) {
break;
}
if (!referenceContainer[__context]) {
createHardlink(referenceContainer, next);
}
// Restart the reference follower.
if (type === $path) {
if (outputFormat === 'JSONG') {
onValue(model, next, seed, null, null, reference, null, outputFormat);
}
depth = 0;
reference = value;
referenceContainer = next;
node = root;
continue;
}
break;
}
} else {
node = undefined;
}
break;
}
if (depth < reference.length && node !== undefined) {
var ref = [];
for (var i = 0; i < depth; i++) {
ref[i] = reference[i];
}
reference = ref;
}
return [node, reference];
}
module.exports = followReference;
},{"../internal/context":62,"./../types/path.js":136,"./onValue":52,"./util/hardlink":54,"./util/isExpired":55}],41:[function(require,module,exports){
var getBoundValue = require('./getBoundValue');
var isPathValue = require('./util/isPathValue');
module.exports = function(walk) {
return function getAsJSON(model, paths, values) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var requestedMissingPaths = results.requestedMissingPaths;
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var missingIdx = 0;
var boundOptimizedPath, optimizedPath;
var i, j, len, bLen;
results.values = values;
if (!values) {
values = [];
}
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (i = 0, len = paths.length; i < len; i++) {
var valueNode = undefined;
var pathSet = paths[i];
if (values[i]) {
valueNode = values[i];
}
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[j] = boundOptimizedPath[j];
}
}
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, 'JSON');
if (missingIdx < requestedMissingPaths.length) {
for (j = missingIdx, length = requestedMissingPaths.length; j < length; j++) {
requestedMissingPaths[j].pathSetIndex = i;
}
missingIdx = length;
}
}
return results;
};
};
},{"./getBoundValue":45,"./util/isPathValue":57}],42:[function(require,module,exports){
var getBoundValue = require('./getBoundValue');
var isPathValue = require('./util/isPathValue');
module.exports = function(walk) {
return function getAsJSONG(model, paths, values) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
results.values = values;
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
if (boundPath.length) {
throw 'It is not legal to use the JSON Graph format from a bound Model. JSON Graph format can only be used from a root model.';
} else {
currentCachePosition = cache;
}
for (var i = 0, len = paths.length; i < len; i++) {
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, values[0], [], results, [], [], inputFormat, 'JSONG');
}
return results;
};
};
},{"./getBoundValue":45,"./util/isPathValue":57}],43:[function(require,module,exports){
var getBoundValue = require('./getBoundValue');
var isPathValue = require('./util/isPathValue');
module.exports = function(walk) {
return function getAsPathMap(model, paths, values) {
var valueNode;
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
valueNode = values[0];
results.values = values;
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[j] = boundOptimizedPath[j];
}
}
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, 'PathMap');
}
return results;
};
};
},{"./getBoundValue":45,"./util/isPathValue":57}],44:[function(require,module,exports){
var getBoundValue = require('./getBoundValue');
var isPathValue = require('./util/isPathValue');
module.exports = function(walk) {
return function getAsValues(model, paths, onNext) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[j] = boundOptimizedPath[j];
}
}
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, onNext, null, results, optimizedPath, [], inputFormat, 'Values');
}
return results;
};
};
},{"./getBoundValue":45,"./util/isPathValue":57}],45:[function(require,module,exports){
var getValueSync = require('./getValueSync');
module.exports = function getBoundValue(model, path) {
var boxed, value, shorted;
boxed = model._boxed;
model._boxed = true;
value = getValueSync(model, path.concat(null));
model._boxed = boxed;
path = value.optimizedPath;
shorted = value.shorted;
value = value.value;
while (path.length && path[path.length - 1] === null) {
path.pop();
}
return {
path: path,
value: value,
shorted: shorted
};
};
},{"./getValueSync":46}],46:[function(require,module,exports){
var followReference = require('./followReference');
var clone = require('./util/clone');
var isExpired = require('./util/isExpired');
var promote = require('./util/lru').promote;
var $path = require('./../types/path.js');
var $sentinel = require('./../types/sentinel.js');
var $error = require('./../types/error.js');
module.exports = function getValueSync(model, simplePath) {
var root = model._cache;
var len = simplePath.length;
var optimizedPath = [];
var shorted = false, shouldShort = false;
var depth = 0;
var key, i, next = root, type, curr = root, out, ref, refNode;
do {
key = simplePath[depth++];
if (key !== null) {
next = curr[key];
optimizedPath.push(key);
}
if (!next) {
out = undefined;
shorted = true;
break;
}
type = next.$type;
// Up to the last key we follow references
if (depth < len) {
if (type === $path) {
ref = followReference(model, root, root, next, next.value);
refNode = ref[0];
if (!refNode) {
out = undefined;
break;
}
type = refNode.$type;
next = refNode;
optimizedPath = ref[1];
}
if (type) {
break;
}
}
// If there is a value, then we have great success, else, report an undefined.
else {
out = next;
}
curr = next;
} while (next && depth < len);
if (depth < len) {
// Unfortunately, if all that follows are nulls, then we have not shorted.
for (i = depth; i < len; ++i) {
if (simplePath[depth] !== null) {
shouldShort = true;
break;
}
}
// if we should short or report value. Values are reported on nulls.
if (shouldShort) {
shorted = true;
out = undefined;
} else {
out = next;
}
for (i = depth; i < len; ++i) {
optimizedPath[optimizedPath.length] = simplePath[i];
}
}
// promotes if not expired
if (out) {
if (isExpired(out)) {
out = undefined;
} else {
promote(model, out);
}
}
if (out && out.$type === $error && !model._treatErrorsAsValues) {
throw {path: simplePath, value: out.value};
} else if (out && model._boxed) {
out = !!type ? clone(out) : out;
} else if (!out && model._materialized) {
out = {$type: $sentinel};
} else if (out) {
out = out.value;
}
return {
value: out,
shorted: shorted,
optimizedPath: optimizedPath
};
};
},{"./../types/error.js":135,"./../types/path.js":136,"./../types/sentinel.js":137,"./followReference":40,"./util/clone":53,"./util/isExpired":55,"./util/lru":58}],47:[function(require,module,exports){
var followReference = require('./followReference');
var onError = require('./onError');
var onMissing = require('./onMissing');
var onValue = require('./onValue');
var lru = require('./util/lru');
var hardLink = require('./util/hardlink');
var isMaterialized = require('./util/isMaterialzed');
var removeHardlink = hardLink.remove;
var splice = lru.splice;
var isExpired = require('./util/isExpired');
var permuteKey = require('./util/permuteKey');
var $path = require('./../types/path');
var $error = require('./../types/error');
var __invalidated = require("../internal/invalidated");
function walk(model, root, curr, pathOrJSON, depth, seedOrFunction, positionalInfo, outerResults, optimizedPath, requestedPath, inputFormat, outputFormat, fromReference) {
if ((!curr || curr && curr.$type) &&
evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfo, outerResults, outputFormat, fromReference)) {
return;
}
// We continue the search to the end of the path/json structure.
else {
// Base case of the searching: Have we hit the end of the road?
// Paths
// 1) depth === path.length
// PathMaps (json input)
// 2) if its an object with no keys
// 3) its a non-object
var jsonQuery = inputFormat === 'JSON';
var atEndOfJSONQuery = false;
var k, i, len;
if (jsonQuery) {
// it has a $type property means we have hit a end.
if (pathOrJSON && pathOrJSON.$type) {
atEndOfJSONQuery = true;
}
// is it an object?
else if (pathOrJSON && typeof pathOrJSON === 'object') {
// A terminating condition
k = Object.keys(pathOrJSON);
if (k.length === 1) {
k = k[0];
}
}
// found a primitive, we hit the end.
else {
atEndOfJSONQuery = true;
}
} else {
k = pathOrJSON[depth];
}
// BaseCase: we have hit the end of our query without finding a 'leaf' node, therefore emit missing.
if (atEndOfJSONQuery || !jsonQuery && depth === pathOrJSON.length) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
return;
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
return;
}
var memo = {done: false};
var permutePosition = positionalInfo;
var permuteRequested = requestedPath;
var permuteOptimized = optimizedPath;
var asJSONG = outputFormat === 'JSONG';
var asJSON = outputFormat === 'JSON';
var isKeySet = false;
var hasChildren = false;
depth++;
var key;
if (k && typeof k === 'object') {
memo.isArray = Array.isArray(k);
memo.arrOffset = 0;
key = permuteKey(k, memo);
isKeySet = true;
// The complex key provided is actual empty
if (memo.done) {
return;
}
} else {
key = k;
memo.done = true;
}
if (asJSON && isKeySet) {
permutePosition = [];
for (i = 0, len = positionalInfo.length; i < len; i++) {
permutePosition[i] = positionalInfo[i];
}
permutePosition.push(depth - 1);
}
do {
fromReference = false;
if (!memo.done) {
permuteOptimized = [];
permuteRequested = [];
for (i = 0, len = requestedPath.length; i < len; i++) {
permuteRequested[i] = requestedPath[i];
}
for (i = 0, len = optimizedPath.length; i < len; i++) {
permuteOptimized[i] = optimizedPath[i];
}
}
var nextPathOrPathMap = jsonQuery ? pathOrJSON[key] : pathOrJSON;
if (jsonQuery && nextPathOrPathMap) {
if (typeof nextPathOrPathMap === 'object') {
if (nextPathOrPathMap.$type) {
hasChildren = false;
} else {
hasChildren = Object.keys(nextPathOrPathMap).length > 0;
}
}
}
var next;
if (key === null || jsonQuery && key === '__null') {
next = curr;
} else {
next = curr[key];
permuteOptimized.push(key);
permuteRequested.push(key);
}
if (next) {
var nType = next.$type;
var value = nType && next.value || next;
if (jsonQuery && hasChildren || !jsonQuery && depth < pathOrJSON.length) {
if (nType && nType === $path && !isExpired(next)) {
if (asJSONG) {
onValue(model, next, seedOrFunction, outerResults, false, permuteOptimized, permutePosition, outputFormat);
}
var ref = followReference(model, root, root, next, value, seedOrFunction, outputFormat);
fromReference = true;
next = ref[0];
var refPath = ref[1];
permuteOptimized = [];
for (i = 0, len = refPath.length; i < len; i++) {
permuteOptimized[i] = refPath[i];
}
}
}
}
walk(model, root, next, nextPathOrPathMap, depth, seedOrFunction, permutePosition, outerResults, permuteOptimized, permuteRequested, inputFormat, outputFormat, fromReference);
if (!memo.done) {
key = permuteKey(k, memo);
}
} while (!memo.done);
}
}
function evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfo, outerResults, outputFormat, fromReference) {
// BaseCase: This position does not exist, emit missing.
if (!curr) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
}
return true;
}
var currType = curr.$type;
positionalInfo = positionalInfo || [];
// The Base Cases. There is a type, therefore we have hit a 'leaf' node.
if (currType === $error) {
if (fromReference) {
requestedPath.push(null);
}
if (outputFormat === 'JSONG' || model._treatErrorsAsValues) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onError(model, curr, requestedPath, optimizedPath, outerResults);
}
}
// Else we have found a value, emit the current position information.
else {
if (isExpired(curr)) {
if (!curr[__invalidated]) {
splice(model, curr);
removeHardlink(curr);
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
} else {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
}
}
return true;
}
module.exports = walk;
},{"../internal/invalidated":65,"./../types/error":135,"./../types/path":136,"./followReference":40,"./onError":50,"./onMissing":51,"./onValue":52,"./util/hardlink":54,"./util/isExpired":55,"./util/isMaterialzed":56,"./util/lru":58,"./util/permuteKey":59}],48:[function(require,module,exports){
var walk = require('./getWalk');
module.exports = {
getAsJSON: require('./getAsJSON')(walk),
getAsJSONG: require('./getAsJSONG')(walk),
getAsValues: require('./getAsValues')(walk),
getAsPathMap: require('./getAsPathMap')(walk),
getValueSync: require('./getValueSync'),
getBoundValue: require('./getBoundValue'),
setCache: require('./legacy_setCache')
};
},{"./getAsJSON":41,"./getAsJSONG":42,"./getAsPathMap":43,"./getAsValues":44,"./getBoundValue":45,"./getValueSync":46,"./getWalk":47,"./legacy_setCache":49}],49:[function(require,module,exports){
/* istanbul ignore next */
var NOOP = function NOOP() {},
__GENERATION_GUID = 0,
__GENERATION_VERSION = 0,
__CONTAINER = "__reference_container",
__CONTEXT = "__context",
__GENERATION = "__generation",
__GENERATION_UPDATED = "__generation_updated",
__INVALIDATED = "__invalidated",
__KEY = "__key",
__KEYS = "__keys",
__IS_KEY_SET = "__is_key_set",
__NULL = "__null",
__SELF = "./",
__PARENT = "../",
__REF = "__ref",
__REF_INDEX = "__ref_index",
__REFS_LENGTH = "__refs_length",
__ROOT = "/",
__OFFSET = "__offset",
__FALKOR_EMPTY_OBJECT = '__FALKOR_EMPTY_OBJECT',
__INTERNAL_KEYS = [
__CONTAINER, __CONTEXT, __GENERATION, __GENERATION_UPDATED,
__INVALIDATED, __KEY, __KEYS, __IS_KEY_SET, __NULL, __SELF,
__PARENT, __REF, __REF_INDEX, __REFS_LENGTH, __OFFSET, __ROOT
],
$TYPE = "$type",
$SIZE = "$size",
$EXPIRES = "$expires",
$TIMESTAMP = "$timestamp",
SENTINEL = "sentinel",
PATH = "ref",
ERROR = "error",
VALUE = "value",
EXPIRED = "expired",
LEAF = "leaf";
/* istanbul ignore next */
module.exports = function setCache(model, map) {
var root = model._root, expired = root.expired, depth = 0, height = 0, mapStack = [], nodes = [], nodeRoot = model._cache, nodeParent = nodeRoot, node = nodeParent, nodeType, nodeValue, nodeSize, nodeTimestamp, nodeExpires;
mapStack[0] = map;
nodes[-1] = nodeParent;
while (depth > -1) {
/* Walk Path Map */
var isTerminus = false, offset = 0, keys = void 0, index = void 0, key = void 0, isKeySet = false;
node = nodeParent = nodes[depth - 1];
depth = depth;
follow_path_map_9177:
do {
height = depth;
nodeType = node && node[$TYPE] || void 0;
nodeValue = nodeType === SENTINEL ? node[VALUE] : node;
if ((isTerminus = !((map = mapStack[offset = depth * 4]) != null && typeof map === 'object') || map[$TYPE] !== void 0 || Array.isArray(map) || !((keys = mapStack[offset + 1] || (mapStack[offset + 1] = Object.keys(map))) && ((index = mapStack[offset + 2] || (mapStack[offset + 2] = 0)) || true) && ((isKeySet = keys.length > 1) || keys.length > 0))) || (node == null || nodeType !== void 0 || typeof node !== 'object' || Array.isArray(nodeValue))) {
if ((nodeExpires = (node && node[$EXPIRES]) != null) && (nodeExpires !== 1 && (nodeExpires === 0 || nodeExpires < now())) || node != null && node[__INVALIDATED] === true) {
nodeType = void 0;
nodeValue = void 0;
node = (expired[expired.length] = node) && (node[__INVALIDATED] = true) && void 0;
}
if (!isTerminus && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue))) {
if (node == null || nodeType !== void 0 || typeof node !== 'object' || Array.isArray(nodeValue)) {
key = null;
node = node;
depth = depth;
continue follow_path_map_9177;
}
} else {
if (key != null) {
var newNode, sizeOffset, edgeSize = node && node[$SIZE] || 0;
nodeType = map && map[$TYPE] || void 0;
nV2 = nodeType ? map[VALUE] : void 0;
nodeValue = nodeType === SENTINEL ? map[VALUE] : map;
newNode = map;
if ((!nodeType || nodeType === SENTINEL || nodeType === PATH) && Array.isArray(nodeValue)) {
delete nodeValue[$SIZE];
// console.log(1);
if (nodeType) {
nodeSize = 50 + (nodeValue.length || 1);
} else {
nodeSize = nodeValue.length || 1;
}
newNode[$SIZE] = nodeSize;
nodeValue[__CONTAINER] = newNode;
} else if (nodeType === SENTINEL || nodeType === PATH) {
newNode[$SIZE] = nodeSize = 50 + (nV2 && typeof nV2.length === 'number' ? nV2.length : 1);
} else if (nodeType === ERROR) {
newNode[$SIZE] = nodeSize = map && map[$SIZE] || 0 || 50 + 1;
} else if (!(map != null && typeof map === 'object')) {
nodeSize = 50 + (typeof nodeValue === 'string' && nodeValue.length || 1);
nodeType = 'sentinel';
newNode = {};
newNode[VALUE] = nodeValue;
newNode[$TYPE] = nodeType;
newNode[$SIZE] = nodeSize;
} else {
nodeType = newNode[$TYPE] = nodeType || GROUP;
newNode[$SIZE] = nodeSize = map && map[$SIZE] || 0 || 50 + 1;
}
;
if (node !== newNode && (node != null && typeof node === 'object')) {
var nodeRefsLength = node[__REFS_LENGTH] || 0, destRefsLength = newNode[__REFS_LENGTH] || 0, i = -1, ref;
while (++i < nodeRefsLength) {
if ((ref = node[__REF + i]) !== void 0) {
ref[__CONTEXT] = newNode;
newNode[__REF + (destRefsLength + i)] = ref;
node[__REF + i] = void 0;
}
}
newNode[__REFS_LENGTH] = nodeRefsLength + destRefsLength;
node[__REFS_LENGTH] = ref = void 0;
var invParent = nodeParent, invChild = node, invKey = key, keys$2, index$2, offset$2, childType, childValue, isBranch, stack = [
nodeParent,
invKey,
node
], depth$2 = 0;
while (depth$2 > -1) {
nodeParent = stack[offset$2 = depth$2 * 8];
invKey = stack[offset$2 + 1];
node = stack[offset$2 + 2];
if ((childType = stack[offset$2 + 3]) === void 0 || (childType = void 0)) {
childType = stack[offset$2 + 3] = node && node[$TYPE] || void 0 || null;
}
childValue = stack[offset$2 + 4] || (stack[offset$2 + 4] = childType === SENTINEL ? node[VALUE] : node);
if ((isBranch = stack[offset$2 + 5]) === void 0) {
isBranch = stack[offset$2 + 5] = !childType && (node != null && typeof node === 'object') && !Array.isArray(childValue);
}
if (isBranch === true) {
if ((keys$2 = stack[offset$2 + 6]) === void 0) {
keys$2 = stack[offset$2 + 6] = [];
index$2 = -1;
for (var childKey in node) {
!(!(childKey[0] !== '_' || childKey[1] !== '_') || (childKey === __SELF || childKey === __PARENT || childKey === __ROOT) || childKey[0] === '$') && (keys$2[++index$2] = childKey);
}
}
index$2 = stack[offset$2 + 7] || (stack[offset$2 + 7] = 0);
if (index$2 < keys$2.length) {
stack[offset$2 + 7] = index$2 + 1;
stack[offset$2 = ++depth$2 * 8] = node;
stack[offset$2 + 1] = invKey = keys$2[index$2];
stack[offset$2 + 2] = node[invKey];
continue;
}
}
var ref$2 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination;
if (ref$2 && Array.isArray(ref$2)) {
destination = ref$2[__CONTEXT];
if (destination) {
var i$2 = (ref$2[__REF_INDEX] || 0) - 1, n = (destination[__REFS_LENGTH] || 0) - 1;
while (++i$2 <= n) {
destination[__REF + i$2] = destination[__REF + (i$2 + 1)];
}
destination[__REFS_LENGTH] = n;
ref$2[__REF_INDEX] = ref$2[__CONTEXT] = destination = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$3, i$3 = -1, n$2 = node[__REFS_LENGTH] || 0;
while (++i$3 < n$2) {
if ((ref$3 = node[__REF + i$3]) !== void 0) {
ref$3[__CONTEXT] = node[__REF + i$3] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$2 = root, head = root$2.__head, tail = root$2.__tail, next = node.__next, prev = node.__prev;
next != null && typeof next === 'object' && (next.__prev = prev);
prev != null && typeof prev === 'object' && (prev.__next = next);
node === head && (root$2.__head = root$2.__next = next);
node === tail && (root$2.__tail = root$2.__prev = prev);
node.__next = node.__prev = void 0;
head = tail = next = prev = void 0;
;
nodeParent[invKey] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
;
delete stack[offset$2 + 0];
delete stack[offset$2 + 1];
delete stack[offset$2 + 2];
delete stack[offset$2 + 3];
delete stack[offset$2 + 4];
delete stack[offset$2 + 5];
delete stack[offset$2 + 6];
delete stack[offset$2 + 7];
--depth$2;
}
nodeParent = invParent;
node = invChild;
}
nodeParent[key] = node = newNode;
nodeType = node && node[$TYPE] || void 0;
node = !node[__SELF] && ((node[__SELF] = node) || true) && ((node[__KEY] = key) || true) && ((node[__PARENT] = nodeParent) || true) && ((node[__ROOT] = nodeRoot) || true) && (node[__GENERATION] || (node[__GENERATION] = ++__GENERATION_GUID) && node) && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue) && (nodeValue[__CONTAINER] = node)) || node;
sizeOffset = edgeSize - nodeSize;
var self = nodeParent, child = node;
while (node = nodeParent) {
nodeParent = node[__PARENT];
if ((node[$SIZE] = (node[$SIZE] || 0) - sizeOffset) <= 0 && nodeParent) {
var ref$4 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination$2;
if (ref$4 && Array.isArray(ref$4)) {
destination$2 = ref$4[__CONTEXT];
if (destination$2) {
var i$4 = (ref$4[__REF_INDEX] || 0) - 1, n$3 = (destination$2[__REFS_LENGTH] || 0) - 1;
while (++i$4 <= n$3) {
destination$2[__REF + i$4] = destination$2[__REF + (i$4 + 1)];
}
destination$2[__REFS_LENGTH] = n$3;
ref$4[__REF_INDEX] = ref$4[__CONTEXT] = destination$2 = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$5, i$5 = -1, n$4 = node[__REFS_LENGTH] || 0;
while (++i$5 < n$4) {
if ((ref$5 = node[__REF + i$5]) !== void 0) {
ref$5[__CONTEXT] = node[__REF + i$5] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$3 = root, head$2 = root$3.__head, tail$2 = root$3.__tail, next$2 = node.__next, prev$2 = node.__prev;
next$2 != null && typeof next$2 === 'object' && (next$2.__prev = prev$2);
prev$2 != null && typeof prev$2 === 'object' && (prev$2.__next = next$2);
node === head$2 && (root$3.__head = root$3.__next = next$2);
node === tail$2 && (root$3.__tail = root$3.__prev = prev$2);
node.__next = node.__prev = void 0;
head$2 = tail$2 = next$2 = prev$2 = void 0;
;
nodeParent[node[__KEY]] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
} else if (node[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
var self$2 = node, stack$2 = [], depth$3 = 0, linkPaths, ref$6, i$6, k, n$5;
while (depth$3 > -1) {
if ((linkPaths = stack$2[depth$3]) === void 0) {
i$6 = k = -1;
n$5 = node[__REFS_LENGTH] || 0;
node[__GENERATION_UPDATED] = __GENERATION_VERSION;
node[__GENERATION] = ++__GENERATION_GUID;
if ((ref$6 = node[__PARENT]) !== void 0 && ref$6[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
stack$2[depth$3] = linkPaths = new Array(n$5 + 1);
linkPaths[++k] = ref$6;
} else if (n$5 > 0) {
stack$2[depth$3] = linkPaths = new Array(n$5);
}
while (++i$6 < n$5) {
if ((ref$6 = node[__REF + i$6]) !== void 0 && ref$6[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
linkPaths[++k] = ref$6;
}
}
}
if ((node = linkPaths && linkPaths.pop()) !== void 0) {
++depth$3;
} else {
stack$2[depth$3--] = void 0;
}
}
node = self$2;
}
}
nodeParent = self;
node = child;
}
;
node = node;
break follow_path_map_9177;
}
}
if ((key = keys[index]) == null) {
node = node;
break follow_path_map_9177;
} else if (key === __NULL && ((key = null) || true) || !(!(key[0] !== '_' || key[1] !== '_') || (key === __SELF || key === __PARENT || key === __ROOT) || key[0] === '$') && ((mapStack[(depth + 1) * 4] = map[key]) || true)) {
mapStack[(depth + 1) * 4 + 3] = key;
} else {
mapStack[offset + 2] = index + 1;
node = node;
depth = depth;
continue follow_path_map_9177;
}
nodes[depth - 1] = nodeParent = node;
if (key != null) {
node = nodeParent && nodeParent[key];
if (typeof map === 'object') {
for (var key$2 in map) {
key$2[0] === '$' && key$2 !== $SIZE && (nodeParent && (nodeParent[key$2] = map[key$2]) || true);
}
map = map[key];
}
var mapType = map && map[$TYPE] || void 0;
var mapValue = mapType === SENTINEL ? map[VALUE] : map;
if ((node == null || typeof node !== 'object' || !!nodeType && nodeType !== SENTINEL && !Array.isArray(nodeValue)) && (!mapType && (map != null && typeof map === 'object') && !Array.isArray(mapValue))) {
nodeType = void 0;
nodeValue = {};
nodeSize = node && node[$SIZE] || 0;
if (node !== nodeValue && (node != null && typeof node === 'object')) {
var nodeRefsLength$2 = node[__REFS_LENGTH] || 0, destRefsLength$2 = nodeValue[__REFS_LENGTH] || 0, i$7 = -1, ref$7;
while (++i$7 < nodeRefsLength$2) {
if ((ref$7 = node[__REF + i$7]) !== void 0) {
ref$7[__CONTEXT] = nodeValue;
nodeValue[__REF + (destRefsLength$2 + i$7)] = ref$7;
node[__REF + i$7] = void 0;
}
}
nodeValue[__REFS_LENGTH] = nodeRefsLength$2 + destRefsLength$2;
node[__REFS_LENGTH] = ref$7 = void 0;
var invParent$2 = nodeParent, invChild$2 = node, invKey$2 = key, keys$3, index$3, offset$3, childType$2, childValue$2, isBranch$2, stack$3 = [
nodeParent,
invKey$2,
node
], depth$4 = 0;
while (depth$4 > -1) {
nodeParent = stack$3[offset$3 = depth$4 * 8];
invKey$2 = stack$3[offset$3 + 1];
node = stack$3[offset$3 + 2];
if ((childType$2 = stack$3[offset$3 + 3]) === void 0 || (childType$2 = void 0)) {
childType$2 = stack$3[offset$3 + 3] = node && node[$TYPE] || void 0 || null;
}
childValue$2 = stack$3[offset$3 + 4] || (stack$3[offset$3 + 4] = childType$2 === SENTINEL ? node[VALUE] : node);
if ((isBranch$2 = stack$3[offset$3 + 5]) === void 0) {
isBranch$2 = stack$3[offset$3 + 5] = !childType$2 && (node != null && typeof node === 'object') && !Array.isArray(childValue$2);
}
if (isBranch$2 === true) {
if ((keys$3 = stack$3[offset$3 + 6]) === void 0) {
keys$3 = stack$3[offset$3 + 6] = [];
index$3 = -1;
for (var childKey$2 in node) {
!(!(childKey$2[0] !== '_' || childKey$2[1] !== '_') || (childKey$2 === __SELF || childKey$2 === __PARENT || childKey$2 === __ROOT) || childKey$2[0] === '$') && (keys$3[++index$3] = childKey$2);
}
}
index$3 = stack$3[offset$3 + 7] || (stack$3[offset$3 + 7] = 0);
if (index$3 < keys$3.length) {
stack$3[offset$3 + 7] = index$3 + 1;
stack$3[offset$3 = ++depth$4 * 8] = node;
stack$3[offset$3 + 1] = invKey$2 = keys$3[index$3];
stack$3[offset$3 + 2] = node[invKey$2];
continue;
}
}
var ref$8 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination$3;
if (ref$8 && Array.isArray(ref$8)) {
destination$3 = ref$8[__CONTEXT];
if (destination$3) {
var i$8 = (ref$8[__REF_INDEX] || 0) - 1, n$6 = (destination$3[__REFS_LENGTH] || 0) - 1;
while (++i$8 <= n$6) {
destination$3[__REF + i$8] = destination$3[__REF + (i$8 + 1)];
}
destination$3[__REFS_LENGTH] = n$6;
ref$8[__REF_INDEX] = ref$8[__CONTEXT] = destination$3 = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$9, i$9 = -1, n$7 = node[__REFS_LENGTH] || 0;
while (++i$9 < n$7) {
if ((ref$9 = node[__REF + i$9]) !== void 0) {
ref$9[__CONTEXT] = node[__REF + i$9] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$4 = root, head$3 = root$4.__head, tail$3 = root$4.__tail, next$3 = node.__next, prev$3 = node.__prev;
next$3 != null && typeof next$3 === 'object' && (next$3.__prev = prev$3);
prev$3 != null && typeof prev$3 === 'object' && (prev$3.__next = next$3);
node === head$3 && (root$4.__head = root$4.__next = next$3);
node === tail$3 && (root$4.__tail = root$4.__prev = prev$3);
node.__next = node.__prev = void 0;
head$3 = tail$3 = next$3 = prev$3 = void 0;
;
nodeParent[invKey$2] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
;
delete stack$3[offset$3 + 0];
delete stack$3[offset$3 + 1];
delete stack$3[offset$3 + 2];
delete stack$3[offset$3 + 3];
delete stack$3[offset$3 + 4];
delete stack$3[offset$3 + 5];
delete stack$3[offset$3 + 6];
delete stack$3[offset$3 + 7];
--depth$4;
}
nodeParent = invParent$2;
node = invChild$2;
}
nodeParent[key] = node = nodeValue;
node = !node[__SELF] && ((node[__SELF] = node) || true) && ((node[__KEY] = key) || true) && ((node[__PARENT] = nodeParent) || true) && ((node[__ROOT] = nodeRoot) || true) && (node[__GENERATION] || (node[__GENERATION] = ++__GENERATION_GUID) && node) && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue) && (nodeValue[__CONTAINER] = node)) || node;
var self$3 = node, node$2;
while (node$2 = node) {
if (node[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
var self$4 = node, stack$4 = [], depth$5 = 0, linkPaths$2, ref$10, i$10, k$2, n$8;
while (depth$5 > -1) {
if ((linkPaths$2 = stack$4[depth$5]) === void 0) {
i$10 = k$2 = -1;
n$8 = node[__REFS_LENGTH] || 0;
node[__GENERATION_UPDATED] = __GENERATION_VERSION;
node[__GENERATION] = ++__GENERATION_GUID;
if ((ref$10 = node[__PARENT]) !== void 0 && ref$10[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
stack$4[depth$5] = linkPaths$2 = new Array(n$8 + 1);
linkPaths$2[++k$2] = ref$10;
} else if (n$8 > 0) {
stack$4[depth$5] = linkPaths$2 = new Array(n$8);
}
while (++i$10 < n$8) {
if ((ref$10 = node[__REF + i$10]) !== void 0 && ref$10[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
linkPaths$2[++k$2] = ref$10;
}
}
}
if ((node = linkPaths$2 && linkPaths$2.pop()) !== void 0) {
++depth$5;
} else {
stack$4[depth$5--] = void 0;
}
}
node = self$4;
}
node = node$2[__PARENT];
}
node = self$3;
}
}
node = node;
depth = depth + 1;
continue follow_path_map_9177;
} while (true);
node = node;
var offset$4 = depth * 4, keys$4, index$4;
do {
delete mapStack[offset$4 + 0];
delete mapStack[offset$4 + 1];
delete mapStack[offset$4 + 2];
delete mapStack[offset$4 + 3];
} while ((keys$4 = mapStack[(offset$4 = 4 * --depth) + 1]) && ((index$4 = mapStack[offset$4 + 2]) || true) && (mapStack[offset$4 + 2] = ++index$4) >= keys$4.length);
}
return nodeRoot;
}
},{}],50:[function(require,module,exports){
var lru = require('./util/lru');
var clone = require('./util/clone');
var promote = lru.promote;
module.exports = function onError(model, node, permuteRequested, permuteOptimized, outerResults) {
outerResults.errors.push({path: permuteRequested, value: node.value});
promote(model, node);
if (permuteOptimized) {
outerResults.requestedPaths.push(permuteRequested);
outerResults.optimizedPaths.push(permuteOptimized);
}
};
},{"./util/clone":53,"./util/lru":58}],51:[function(require,module,exports){
var support = require('./util/support');
var fastCat = support.fastCat,
fastCatSkipNulls = support.fastCatSkipNulls,
fastCopy = support.fastCopy;
var isExpired = require('./util/isExpired');
var spreadJSON = require('./util/spreadJSON');
var clone = require('./util/clone');
module.exports = function onMissing(model, node, path, depth, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat) {
var pathSlice;
if (Array.isArray(path)) {
if (depth < path.length) {
pathSlice = fastCopy(path, depth);
} else {
pathSlice = [];
}
concatAndInsertMissing(pathSlice, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat);
} else {
pathSlice = [];
spreadJSON(path, pathSlice);
for (var i = 0, len = pathSlice.length; i < len; i++) {
concatAndInsertMissing(pathSlice[i], outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, true);
}
}
};
function concatAndInsertMissing(remainingPath, results, permuteRequested, permuteOptimized, permutePosition, outputFormat, __null) {
var i = 0, len;
if (__null) {
for (i = 0, len = remainingPath.length; i < len; i++) {
if (remainingPath[i] === '__null') {
remainingPath[i] = null;
}
}
}
if (outputFormat === 'JSON') {
permuteRequested = fastCat(permuteRequested, remainingPath);
for (i = 0, len = permutePosition.length; i < len; i++) {
var idx = permutePosition[i];
var r = permuteRequested[idx];
permuteRequested[idx] = [r];
}
results.requestedMissingPaths.push(permuteRequested);
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
} else {
results.requestedMissingPaths.push(fastCat(permuteRequested, remainingPath));
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
}
}
},{"./util/clone":53,"./util/isExpired":55,"./util/spreadJSON":60,"./util/support":61}],52:[function(require,module,exports){
var lru = require('./util/lru');
var clone = require('./util/clone');
var promote = lru.promote;
var $path = require('./../types/path');
var $sentinel = require('./../types/sentinel');
var $error = require('./../types/error');
module.exports = function onValue(model, node, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, fromReference) {
var i, len, k, key, curr, prev, prevK;
var materialized = false, valueNode;
if (node) {
promote(model, node);
}
if (!node || node.value === undefined) {
materialized = model._materialized;
}
// materialized
if (materialized) {
valueNode = {$type: $sentinel};
}
// Boxed Mode & Reference Node & Error node (only happens when model is in treat errors as values).
else if (model._boxed) {
valueNode = clone(node);
}
else if (node.$type === $path || node.$type === $error) {
if (outputFormat === 'JSONG') {
valueNode = clone(node);
} else {
valueNode = node.value;
}
}
else {
if (outputFormat === 'JSONG') {
if (typeof node.value === 'object') {
valueNode = clone(node);
} else {
valueNode = node.value;
}
} else {
valueNode = node.value;
}
}
if (permuteRequested) {
if (fromReference && permuteRequested[permuteRequested.length - 1] !== null) {
permuteRequested.push(null);
}
outerResults.requestedPaths.push(permuteRequested);
outerResults.optimizedPaths.push(permuteOptimized);
}
switch (outputFormat) {
case 'Values':
// in any subscription situation, onNexts are always provided, even as a noOp.
seedOrFunction({path: permuteRequested, value: valueNode});
break;
case 'PathMap':
len = permuteRequested.length - 1;
if (len === -1) {
seedOrFunction.json = valueNode;
} else {
curr = seedOrFunction.json;
if (!curr) {
curr = seedOrFunction.json = {};
}
for (i = 0; i < len; i++) {
k = permuteRequested[i];
if (!curr[k]) {
curr[k] = {};
}
prev = curr;
prevK = k;
curr = curr[k];
}
k = permuteRequested[i];
if (k !== null) {
curr[k] = valueNode;
} else {
prev[prevK] = valueNode;
}
}
break;
case 'JSON':
if (seedOrFunction) {
if (permutePosition.length) {
if (!seedOrFunction.json) {
seedOrFunction.json = {};
}
curr = seedOrFunction.json;
for (i = 0, len = permutePosition.length - 1; i < len; i++) {
k = permutePosition[i];
key = permuteRequested[k];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
k = permutePosition[i];
key = permuteRequested[k];
curr[key] = valueNode;
} else {
seedOrFunction.json = valueNode;
}
}
break;
case 'JSONG':
curr = seedOrFunction.jsong;
if (!curr) {
curr = seedOrFunction.jsong = {};
seedOrFunction.paths = [];
}
for (i = 0, len = permuteOptimized.length - 1; i < len; i++) {
key = permuteOptimized[i];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
key = permuteOptimized[i];
// TODO: Special case? do string comparisons make big difference?
curr[key] = materialized ? {$type: $sentinel} : valueNode;
if (permuteRequested) {
seedOrFunction.paths.push(permuteRequested);
}
break;
}
};
},{"./../types/error":135,"./../types/path":136,"./../types/sentinel":137,"./util/clone":53,"./util/lru":58}],53:[function(require,module,exports){
// Copies the node
var prefix = require("../../internal/prefix");
module.exports = function clone(node) {
var outValue, i, len;
var keys = Object.keys(node);
outValue = {};
for (i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
if (k[0] === prefix) {
continue;
}
outValue[k] = node[k];
}
return outValue;
};
},{"../../internal/prefix":70}],54:[function(require,module,exports){
var __ref = require("../../internal/ref");
var __context = require("../../internal/context");
var __ref_index = require("../../internal/ref-index");
var __refs_length = require("../../internal/refs-length");
function createHardlink(from, to) {
// create a back reference
var backRefs = to[__refs_length] || 0;
to[__ref + backRefs] = from;
to[__refs_length] = backRefs + 1;
// create a hard reference
from[__ref_index] = backRefs;
from[__context] = to;
}
function removeHardlink(cacheObject) {
var context = cacheObject[__context];
if (context) {
var idx = cacheObject[__ref_index];
var len = context[__refs_length];
while (idx < len) {
context[__ref + idx] = context[__REF + idx + 1];
++idx;
}
context[__refs_length] = len - 1;
cacheObject[__context] = undefined;
cacheObject[__ref_index] = undefined;
}
}
module.exports = {
create: createHardlink,
remove: removeHardlink
};
},{"../../internal/context":62,"../../internal/ref":73,"../../internal/ref-index":72,"../../internal/refs-length":74}],55:[function(require,module,exports){
var now = require('../../support/now');
module.exports = function isExpired(node) {
var $expires = node.$expires === undefined && -1 || node.$expires;
return $expires !== -1 && $expires !== 1 && ($expires === 0 || $expires < now());
};
},{"../../support/now":122}],56:[function(require,module,exports){
module.exports = function isMaterialized(model) {
return model._materialized && !(model._router || model._dataSource);
};
},{}],57:[function(require,module,exports){
module.exports = function(x) {
return x.path && x.value;
};
},{}],58:[function(require,module,exports){
var __head = require("../../internal/head");
var __tail = require("../../internal/tail");
var __next = require("../../internal/next");
var __prev = require("../../internal/prev");
var __invalidated = require("../../internal/invalidated");
// [H] -> Next -> ... -> [T]
// [T] -> Prev -> ... -> [H]
function lruPromote(model, object) {
var root = model._root;
var head = root[__head];
if (head === object) {
return;
}
// First insert
if (!head) {
root[__head] = object;
return;
}
// The head and the tail need to separate
if (!root[__tail]) {
root[__head] = object;
root[__tail] = head;
object[__next] = head;
// Now tail
head[__prev] = object;
return;
}
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = undefined;
// Insert into head position
root[__head] = object;
object[__next] = head;
head[__prev] = object;
}
function lruSplice(model, object) {
var root = model._root;
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = undefined;
if (object === root[__head]) {
root[__head] = undefined;
}
if (object === root[__tail]) {
root[__tail] = undefined;
}
object[__invalidated] = true;
root.expired.push(object);
}
module.exports = {
promote: lruPromote,
splice: lruSplice
};
},{"../../internal/head":64,"../../internal/invalidated":65,"../../internal/next":67,"../../internal/prev":71,"../../internal/tail":75}],59:[function(require,module,exports){
var prefix = require("../../internal/prefix");
module.exports = function permuteKey(key, memo) {
if (memo.isArray) {
if (memo.loaded && memo.rangeOffset > memo.to) {
memo.arrOffset++;
memo.loaded = false;
}
var idx = memo.arrOffset, length = key.length;
if (idx === length) {
memo.done = true;
return '';
}
var el = key[memo.arrOffset];
var type = typeof el;
if (type === 'object') {
if (!memo.loaded) {
memo.from = el.from || 0;
memo.to = el.to ||
typeof el.length === 'number' && memo.from + el.length - 1 || 0;
memo.rangeOffset = memo.from;
memo.loaded = true;
}
return memo.rangeOffset++;
} else {
do {
// if (type !== 'string') {
// break;
// }
if (el[0] !== prefix && el[0] !== '$') {
break;
}
el = key[++idx];
} while (el !== undefined || idx < length);
if (el === undefined || idx === length) {
memo.done = true;
return '';
}
memo.arrOffset = idx + 1;
return el;
}
} else {
if (!memo.loaded) {
memo.from = key.from || 0;
memo.to = key.to ||
typeof key.length === 'number' && memo.from + key.length - 1 || 0;
memo.rangeOffset = memo.from;
memo.loaded = true;
}
if (memo.rangeOffset > memo.to) {
memo.done = true;
return '';
}
return memo.rangeOffset++;
}
};
},{"../../internal/prefix":70}],60:[function(require,module,exports){
var fastCopy = require('./support').fastCopy;
module.exports = function spreadJSON(root, bins, bin) {
bin = bin || [];
if (!bins.length) {
bins.push(bin);
}
if (!root || typeof root !== 'object' || root.$type) {
return [];
}
var keys = Object.keys(root);
if (keys.length === 1) {
bin.push(keys[0]);
spreadJSON(root[keys[0]], bins, bin);
} else {
for (var i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
var nextBin = fastCopy(bin);
nextBin.push(k);
bins.push(nextBin);
spreadJSON(root[k], bins, nextBin);
}
}
};
},{"./support":61}],61:[function(require,module,exports){
function fastCopy(arr, i) {
var a = [], len, j;
for (j = 0, i = i || 0, len = arr.length; i < len; j++, i++) {
a[j] = arr[i];
}
return a;
}
function fastCatSkipNulls(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
if (arr2[j] !== null) {
a[i++] = arr2[j];
}
}
return a;
}
function fastCat(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
a[i++] = arr2[j];
}
return a;
}
module.exports = {
fastCat: fastCat,
fastCatSkipNulls: fastCatSkipNulls,
fastCopy: fastCopy
};
},{}],62:[function(require,module,exports){
module.exports = require("./prefix") + "context";
},{"./prefix":70}],63:[function(require,module,exports){
module.exports = require("./prefix") + "generation";
},{"./prefix":70}],64:[function(require,module,exports){
module.exports = require("./prefix") + "head";
},{"./prefix":70}],65:[function(require,module,exports){
module.exports = require("./prefix") + "invalidated";
},{"./prefix":70}],66:[function(require,module,exports){
module.exports = require("./prefix") + "key";
},{"./prefix":70}],67:[function(require,module,exports){
module.exports = require("./prefix") + "next";
},{"./prefix":70}],68:[function(require,module,exports){
module.exports = require("./prefix") + "offset";
},{"./prefix":70}],69:[function(require,module,exports){
module.exports = require("./prefix") + "parent";
},{"./prefix":70}],70:[function(require,module,exports){
// This may look like an empty string, but it's actually a single zero-width-space character.
module.exports = "";
},{}],71:[function(require,module,exports){
module.exports = require("./prefix") + "prev";
},{"./prefix":70}],72:[function(require,module,exports){
module.exports = require("./prefix") + "ref-index";
},{"./prefix":70}],73:[function(require,module,exports){
module.exports = require("./prefix") + "ref";
},{"./prefix":70}],74:[function(require,module,exports){
module.exports = require("./prefix") + "refs-length";
},{"./prefix":70}],75:[function(require,module,exports){
module.exports = require("./prefix") + "tail";
},{"./prefix":70}],76:[function(require,module,exports){
module.exports = require("./prefix") + "version";
},{"./prefix":70}],77:[function(require,module,exports){
module.exports = {
invPathSetsAsJSON: require("./invalidate-path-sets-as-json-dense"),
invPathSetsAsJSONG: require("./invalidate-path-sets-as-json-graph"),
invPathSetsAsPathMap: require("./invalidate-path-sets-as-json-sparse"),
invPathSetsAsValues: require("./invalidate-path-sets-as-json-values")
};
},{"./invalidate-path-sets-as-json-dense":78,"./invalidate-path-sets-as-json-graph":79,"./invalidate-path-sets-as-json-sparse":80,"./invalidate-path-sets-as-json-values":81}],78:[function(require,module,exports){
module.exports = invalidate_path_sets_as_json_dense;
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var array_slice = require("../support/array-slice");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var update_graph = require("../support/update-graph");
var invalidate_node = require("../support/invalidate-node");
var collect = require("../lru/collect");
function invalidate_path_sets_as_json_dense(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots[3] = parents[3] = nodes[3] = undefined;
}
var pathset = pathsets[index];
roots.index = index;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
if (is_keyset && !!(parents[3] = json)) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
nodes[0] = node;
if (!!json) {
var type = is_object(node) && node.$type || undefined;
var jsonkey = keyset;
if (jsonkey == null) {
json = roots;
jsonkey = 3;
}
json[jsonkey] = clone(roots, node, type, node && node.value);
}
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
roots.json = roots[3];
roots.hasValue = true;
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/array-slice":101,"../support/clone-dense-json":102,"../support/get-valid-key":112,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/update-graph":133,"../walk/walk-path-set":143}],79:[function(require,module,exports){
module.exports = invalidate_path_sets_as_json_graph;
var $path = require("../types/path");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var update_graph = require("../support/update-graph");
var invalidate_node = require("../support/invalidate-node");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function invalidate_path_sets_as_json_graph(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var type = is_object(node) && node.$type || undefined;
if (is_branch) {
parents[0] = nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
clone_success(roots, requested, optimized);
roots.json = roots[1];
roots.hasValue = true;
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/update-graph":133,"../types/path":136,"../walk/walk-path-set-soft-link":142}],80:[function(require,module,exports){
module.exports = invalidate_path_sets_as_json_sparse;
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var array_slice = require("../support/array-slice");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var update_graph = require("../support/update-graph");
var invalidate_node = require("../support/invalidate-node");
var collect = require("../lru/collect");
function invalidate_path_sets_as_json_sparse(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
parents[3] = json;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
nodes[0] = node;
var type = is_object(node) && node.$type || undefined;
json[jsonkey] = clone(roots, node, type, node && node.value);
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
roots.json = roots[3];
roots.hasValue = true;
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/array-slice":101,"../support/clone-dense-json":102,"../support/get-valid-key":112,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/update-graph":133,"../walk/walk-path-set":143}],81:[function(require,module,exports){
module.exports = invalidate_path_sets_as_json_values;
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var array_slice = require("../support/array-slice");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var update_graph = require("../support/update-graph");
var invalidate_node = require("../support/invalidate-node");
var collect = require("../lru/collect");
function invalidate_path_sets_as_json_values(model, pathsets, onNext) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
return;
}
nodes[0] = node;
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || undefined;
var onNext = roots.onNext;
if (!!type && onNext) {
onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/array-slice":101,"../support/clone-dense-json":102,"../support/get-valid-key":112,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/update-graph":133,"../walk/walk-path-set":143}],82:[function(require,module,exports){
var __head = require("../internal/head");
var __tail = require("../internal/tail");
var __next = require("../internal/next");
var __prev = require("../internal/prev");
var update_graph = require("../support/update-graph");
module.exports = function(lru, expired, version, total, max, ratio) {
var targetSize = max * ratio;
var node, size;
while(!!(node = expired.pop())) {
size = node.$size || 0;
total -= size;
update_graph(node, size, version, lru);
}
if(total >= max) {
var prev = lru[__tail];
while((total >= targetSize) && !!(node = prev)) {
prev = prev[__prev];
size = node.$size || 0;
total -= size;
update_graph(node, size, version, lru);
}
if((lru[__tail] = lru[__prev] = prev) == null) {
lru[__head] = lru[__next] = undefined;
} else {
prev[__next] = undefined;
}
}
};
},{"../internal/head":64,"../internal/next":67,"../internal/prev":71,"../internal/tail":75,"../support/update-graph":133}],83:[function(require,module,exports){
var $expires_never = require("../values/expires-never");
var __head = require("../internal/head");
var __tail = require("../internal/tail");
var __next = require("../internal/next");
var __prev = require("../internal/prev");
var is_object = require("../support/is-object");
module.exports = function(root, node) {
if(is_object(node) && (node.$expires !== $expires_never)) {
var head = root[__head], tail = root[__tail],
next = node[__next], prev = node[__prev];
if (node !== head) {
(next != null && typeof next === "object") && (next[__prev] = prev);
(prev != null && typeof prev === "object") && (prev[__next] = next);
(next = head) && (head != null && typeof head === "object") && (head[__prev] = node);
(root[__head] = root[__next] = head = node);
(head[__next] = next);
(head[__prev] = undefined);
}
if (tail == null || node === tail) {
root[__tail] = root[__prev] = tail = prev || node;
}
}
return node;
};
},{"../internal/head":64,"../internal/next":67,"../internal/prev":71,"../internal/tail":75,"../support/is-object":118,"../values/expires-never":138}],84:[function(require,module,exports){
var __head = require("../internal/head");
var __tail = require("../internal/tail");
var __next = require("../internal/next");
var __prev = require("../internal/prev");
module.exports = function(root, node) {
var head = root[__head], tail = root[__tail],
next = node[__next], prev = node[__prev];
(next != null && typeof next === "object") && (next[__prev] = prev);
(prev != null && typeof prev === "object") && (prev[__next] = next);
(node === head) && (root[__head] = root[__next] = next);
(node === tail) && (root[__tail] = root[__prev] = prev);
node[__next] = node[__prev] = undefined;
head = tail = next = prev = undefined;
};
},{"../internal/head":64,"../internal/next":67,"../internal/prev":71,"../internal/tail":75}],85:[function(require,module,exports){
module.exports = {
setPathSetsAsJSON: require('./set-json-values-as-json-dense'),
setPathSetsAsJSONG: require('./set-json-values-as-json-graph'),
setPathSetsAsPathMap: require('./set-json-values-as-json-sparse'),
setPathSetsAsValues: require('./set-json-values-as-json-values'),
setPathMapsAsJSON: require('./set-json-sparse-as-json-dense'),
setPathMapsAsJSONG: require('./set-json-sparse-as-json-graph'),
setPathMapsAsPathMap: require('./set-json-sparse-as-json-sparse'),
setPathMapsAsValues: require('./set-json-sparse-as-json-values'),
setJSONGsAsJSON: require('./set-json-graph-as-json-dense'),
setJSONGsAsJSONG: require('./set-json-graph-as-json-graph'),
setJSONGsAsPathMap: require('./set-json-graph-as-json-sparse'),
setJSONGsAsValues: require('./set-json-graph-as-json-values'),
setCache: require('./set-cache')
};
},{"./set-cache":86,"./set-json-graph-as-json-dense":87,"./set-json-graph-as-json-graph":88,"./set-json-graph-as-json-sparse":89,"./set-json-graph-as-json-values":90,"./set-json-sparse-as-json-dense":91,"./set-json-sparse-as-json-graph":92,"./set-json-sparse-as-json-sparse":93,"./set-json-sparse-as-json-values":94,"./set-json-values-as-json-dense":95,"./set-json-values-as-json-graph":96,"./set-json-values-as-json-sparse":97,"./set-json-values-as-json-values":98}],86:[function(require,module,exports){
module.exports = set_cache;
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var collect = require("../lru/collect");
function set_cache(model, pathmap, error_selector) {
var roots = options([], model, error_selector);
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
roots[0] = roots.root;
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return model;
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key],
type;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/sentinel":137,"../walk/walk-path-map":141}],87:[function(require,module,exports){
module.exports = set_json_graph_as_json_dense;
var $path = require("../types/path");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var merge_node = require("../support/merge-node");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_graph_as_json_dense(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var index2 = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index3 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index3 < count2) {
json = values && values[++index2];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pathset = pathsets[index3];
roots.index = index3;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
messageParent = parents[2];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
var length = requested.length;
var offset = roots.offset;
parents[3] = json;
if (is_branch) {
parents[0] = node;
parents[2] = message;
if ((length > offset) && is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/is-object":118,"../support/merge-node":121,"../support/options":123,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../types/path":136,"../walk/walk-path-set-soft-link":142}],88:[function(require,module,exports){
module.exports = set_json_graph_as_json_graph;
var $path = require("../types/path");
var clone = require("../support/clone-graph-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var merge_node = require("../support/merge-node");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var promote = require("../lru/promote");
var collect = require("../lru/collect");
function set_json_graph_as_json_graph(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = 0;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
messageParent = parents[2];
} else {
json = nodes[1];
parent = nodes[0];
messageParent = nodes[2];
}
var jsonkey = key;
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
parents[1] = json;
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var type = is_object(node) && node.$type || undefined;
if (is_branch) {
parents[0] = node;
parents[2] = message;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":82,"../lru/promote":83,"../support/array-clone":100,"../support/clone-graph-json":103,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/is-object":118,"../support/merge-node":121,"../support/options":123,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../types/path":136,"../walk/walk-path-set-soft-link":142}],89:[function(require,module,exports){
module.exports = set_json_graph_as_json_sparse;
var $path = require("../types/path");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var merge_node = require("../support/merge-node");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_graph_as_json_sparse(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
messageParent = parents[2];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
parents[3] = json;
if (is_branch) {
var length = requested.length;
var offset = roots.offset;
var type = is_object(node) && node.$type || undefined;
parents[0] = node;
parents[2] = message;
if ((length > offset) && (!type || type == $path)) {
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/is-object":118,"../support/merge-node":121,"../support/options":123,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../types/path":136,"../walk/walk-path-set-soft-link":142}],90:[function(require,module,exports){
module.exports = set_json_graph_as_json_values;
var $path = require("../types/path");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var array_slice = require("../support/array-slice");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var merge_node = require("../support/merge-node");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_graph_as_json_values(model, envelopes, onNext, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset) {
var parent, messageParent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
messageParent = parents[2];
} else {
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
if (is_branch) {
parents[0] = node;
parents[2] = message;
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_slice(requested, roots.offset),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/array-slice":101,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/get-valid-key":112,"../support/is-object":118,"../support/merge-node":121,"../support/options":123,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../types/path":136,"../walk/walk-path-set-soft-link":142}],91:[function(require,module,exports){
module.exports = set_json_sparse_as_json_dense;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-map");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_sparse_as_json_dense(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pathmap = pathmaps[index];
roots.index = index;
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
if (is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-map":129,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-map":141}],92:[function(require,module,exports){
module.exports = set_json_sparse_as_json_graph;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-graph-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-map");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var promote = require("../lru/promote");
var collect = require("../lru/collect");
function set_json_sparse_as_json_graph(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
type = node.$type;
parents[0] = nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":82,"../lru/promote":83,"../support/array-clone":100,"../support/clone-graph-json":103,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-map":129,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-map-soft-link":140}],93:[function(require,module,exports){
module.exports = set_json_sparse_as_json_sparse;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-map");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_sparse_as_json_sparse(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-map":129,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-map":141}],94:[function(require,module,exports){
module.exports = set_path_map_as_json_values;
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_map = require("../walk/walk-path-map");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-map");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_path_map_as_json_values(model, pathmaps, onNext, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-map":129,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/sentinel":137,"../walk/walk-path-map":141}],95:[function(require,module,exports){
module.exports = set_json_values_as_json_dense;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var invalidate_node = require("../support/invalidate-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_values_as_json_dense(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
roots.index = index;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
if (is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-set":143}],96:[function(require,module,exports){
module.exports = set_json_values_as_json_graph;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-graph-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set-soft-link");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var invalidate_node = require("../support/invalidate-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var promote = require("../lru/promote");
var collect = require("../lru/collect");
function set_json_values_as_json_graph(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
type = node.$type;
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":82,"../lru/promote":83,"../support/array-clone":100,"../support/clone-graph-json":103,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-set-soft-link":142}],97:[function(require,module,exports){
module.exports = set_json_values_as_json_sparse;
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var invalidate_node = require("../support/invalidate-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_values_as_json_sparse(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/path":136,"../types/sentinel":137,"../walk/walk-path-set":143}],98:[function(require,module,exports){
module.exports = set_json_values_as_json_values;
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var clone = require("../support/clone-dense-json");
var array_clone = require("../support/array-clone");
var options = require("../support/options");
var walk_path_set = require("../walk/walk-path-set");
var is_object = require("../support/is-object");
var get_valid_key = require("../support/get-valid-key");
var create_branch = require("../support/create-branch");
var wrap_node = require("../support/wrap-node");
var invalidate_node = require("../support/invalidate-node");
var replace_node = require("../support/replace-node");
var graph_node = require("../support/graph-node");
var update_back_refs = require("../support/update-back-refs");
var update_graph = require("../support/update-graph");
var inc_generation = require("../support/inc-generation");
var node_as_miss = require("../support/treat-node-as-missing-path-set");
var node_as_error = require("../support/treat-node-as-error");
var clone_success = require("../support/clone-success-paths");
var collect = require("../lru/collect");
function set_json_values_as_json_values(model, pathvalues, onNext, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized, nodes)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key], type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":82,"../support/array-clone":100,"../support/clone-dense-json":102,"../support/clone-success-paths":108,"../support/create-branch":110,"../support/get-valid-key":112,"../support/graph-node":113,"../support/inc-generation":114,"../support/invalidate-node":116,"../support/is-object":118,"../support/options":123,"../support/replace-node":126,"../support/treat-node-as-error":128,"../support/treat-node-as-missing-path-set":130,"../support/update-back-refs":132,"../support/update-graph":133,"../support/wrap-node":134,"../types/error":135,"../types/sentinel":137,"../walk/walk-path-set":143}],99:[function(require,module,exports){
module.exports = function(array, value) {
var i = -1;
var n = array.length;
var array2 = new Array(n + 1);
while(++i < n) { array2[i] = array[i]; }
array2[i] = value;
return array2;
};
},{}],100:[function(require,module,exports){
module.exports = function(array) {
var i = -1;
var n = array.length;
var array2 = new Array(n);
while(++i < n) { array2[i] = array[i]; }
return array2;
};
},{}],101:[function(require,module,exports){
module.exports = function(array, index) {
var i = -1;
var n = array.length - index;
var array2 = new Array(n);
while(++i < n) { array2[i] = array[i + index]; }
return array2;
};
},{}],102:[function(require,module,exports){
var $sentinel = require("../types/sentinel");
var clone = require("./clone");
module.exports = function(roots, node, type, value) {
if(node == null || value === undefined) {
return { $type: $sentinel };
}
if(roots.boxed == true) {
return !!type && clone(node) || node;
}
return value;
}
},{"../types/sentinel":137,"./clone":109}],103:[function(require,module,exports){
var $sentinel = require("../types/sentinel");
var clone = require("./clone");
var is_primitive = require("./is-primitive");
module.exports = function(roots, node, type, value) {
if(node == null || value === undefined) {
return { $type: $sentinel };
}
if(roots.boxed == true) {
return !!type && clone(node) || node;
}
if(!type || (type === $sentinel && is_primitive(value))) {
return value;
}
return clone(node);
}
},{"../types/sentinel":137,"./clone":109,"./is-primitive":119}],104:[function(require,module,exports){
var clone_requested = require("./clone-requested-path");
var clone_optimized = require("./clone-optimized-path");
var walk_path_map = require("../walk/walk-path-map-soft-link");
var is_object = require("./is-object");
var empty = [];
module.exports = function(roots, pathmap, keys_stack, depth, requested, optimized) {
var patset_keys = explode_keys(pathmap, keys_stack.concat(), depth);
var pathset = patset_keys.map(function(keys) {
keys = keys.filter(function(key) { return key != "null"; });
switch(keys.length) {
case 0:
return null;
case 1:
return keys[0];
default:
return keys;
}
});
roots.requestedMissingPaths.push(clone_requested(roots.bound, requested, pathset, depth, roots.index));
roots.optimizedMissingPaths.push(clone_optimized(optimized, pathset, depth));
}
function explode_keys(pathmap, keys_stack, depth) {
if(is_object(pathmap)) {
var keys = Object.keys(pathmap);
var keys2 = keys_stack[depth] || (keys_stack[depth] = []);
keys2.push.apply(keys2, keys);
keys.forEach(function(key) {
explode_keys(pathmap[key], keys_stack, depth + 1);
});
}
return keys_stack;
}
},{"../walk/walk-path-map-soft-link":140,"./clone-optimized-path":106,"./clone-requested-path":107,"./is-object":118}],105:[function(require,module,exports){
var clone_requested_path = require("./clone-requested-path");
var clone_optimized_path = require("./clone-optimized-path");
module.exports = function(roots, pathset, depth, requested, optimized) {
roots.requestedMissingPaths.push(clone_requested_path(roots.bound, requested, pathset, depth, roots.index));
roots.optimizedMissingPaths.push(clone_optimized_path(optimized, pathset, depth));
}
},{"./clone-optimized-path":106,"./clone-requested-path":107}],106:[function(require,module,exports){
module.exports = function(optimized, pathset, depth) {
var x;
var i = -1;
var j = depth - 1;
var n = optimized.length;
var m = pathset.length;
var array2 = [];
while(++i < n) {
array2[i] = optimized[i];
}
while(++j < m) {
if((x = pathset[j]) != null) {
array2[i++] = x;
}
}
return array2;
}
},{}],107:[function(require,module,exports){
var is_object = require("./is-object");
module.exports = function(bound, requested, pathset, depth, index) {
var x;
var i = -1;
var j = -1;
var l = 0;
var m = requested.length;
var n = bound.length;
var array2 = [];
while(++i < n) {
array2[i] = bound[i];
}
while(++j < m) {
if((x = requested[j]) != null) {
if(is_object(pathset[l++])) {
array2[i++] = [x];
} else {
array2[i++] = x;
}
}
}
m = n + l + pathset.length - depth;
while(i < m) {
array2[i++] = pathset[l++];
}
if(index != null) {
array2.pathSetIndex = index;
}
return array2;
}
},{"./is-object":118}],108:[function(require,module,exports){
var array_slice = require("./array-slice");
var array_clone = require("./array-clone");
module.exports = function(roots, requested, optimized) {
roots.requestedPaths.push(array_slice(requested, roots.offset));
roots.optimizedPaths.push(array_clone(optimized));
}
},{"./array-clone":100,"./array-slice":101}],109:[function(require,module,exports){
var is_object = require("./is-object");
var prefix = require("../internal/prefix");
module.exports = function(value) {
var dest = value, src = dest, i = -1, n, keys, key;
if(is_object(dest)) {
dest = {};
keys = Object.keys(src);
n = keys.length;
while(++i < n) {
key = keys[i];
if(key[0] !== prefix) {
dest[key] = src[key];
}
}
}
return dest;
}
},{"../internal/prefix":70,"./is-object":118}],110:[function(require,module,exports){
var $path = require("../types/path");
var $expired = "expired";
var replace_node = require("./replace-node");
var graph_node = require("./graph-node");
var update_back_refs = require("./update-back-refs");
var is_primitive = require("./is-primitive");
var is_expired = require("./is-expired");
module.exports = function(roots, parent, node, type, key) {
if(!!type && is_expired(roots, node)) {
type = $expired;
}
if((!!type && type != $path) || is_primitive(node)) {
node = replace_node(parent, node, {}, key, roots.lru);
node = graph_node(roots[0], parent, node, key, 0);
node = update_back_refs(node, roots.version);
}
return node;
}
},{"../types/path":136,"./graph-node":113,"./is-expired":117,"./is-primitive":119,"./replace-node":126,"./update-back-refs":132}],111:[function(require,module,exports){
var __ref = require("../internal/ref");
var __context = require("../internal/context");
var __ref_index = require("../internal/ref-index");
var __refs_length = require("../internal/refs-length");
module.exports = function(node) {
var ref, i = -1, n = node[__refs_length] || 0;
while(++i < n) {
if((ref = node[__ref + i]) !== undefined) {
ref[__context] = ref[__ref_index] = node[__ref + i] = undefined;
}
}
node[__refs_length] = undefined
}
},{"../internal/context":62,"../internal/ref":73,"../internal/ref-index":72,"../internal/refs-length":74}],112:[function(require,module,exports){
module.exports = function(path) {
var key, index = path.length - 1;
do {
if((key = path[index]) != null) {
return key;
}
} while(--index > -1);
return null;
}
},{}],113:[function(require,module,exports){
var __parent = require("../internal/parent");
var __key = require("../internal/key");
var __generation = require("../internal/generation");
module.exports = function(root, parent, node, key, generation) {
node[__parent] = parent;
node[__key] = key;
node[__generation] = generation;
return node;
}
},{"../internal/generation":63,"../internal/key":66,"../internal/parent":69}],114:[function(require,module,exports){
var generation = 0;
module.exports = function() { return generation++; }
},{}],115:[function(require,module,exports){
var version = 0;
module.exports = function() { return version++; }
},{}],116:[function(require,module,exports){
module.exports = invalidate;
var is_object = require("./is-object");
var remove_node = require("./remove-node");
var prefix = require("../internal/prefix");
function invalidate(parent, node, key, lru) {
if(remove_node(parent, node, key, lru)) {
var type = is_object(node) && node.$type || undefined;
if(type == null) {
var keys = Object.keys(node);
for(var i = -1, n = keys.length; ++i < n;) {
var key = keys[i];
if(key[0] !== prefix && key[0] !== "$") {
invalidate(node, node[key], key, lru);
}
}
}
return true;
}
return false;
}
},{"../internal/prefix":70,"./is-object":118,"./remove-node":125}],117:[function(require,module,exports){
var $expires_now = require("../values/expires-now");
var $expires_never = require("../values/expires-never");
var __invalidated = require("../internal/invalidated");
var now = require("./now");
var splice = require("../lru/splice");
module.exports = function(roots, node) {
var expires = node.$expires;
if((expires != null ) && (
expires != $expires_never ) && (
expires == $expires_now || expires < now())) {
if(!node[__invalidated]) {
node[__invalidated] = true;
roots.expired.push(node);
splice(roots.lru, node);
}
return true;
}
return false;
}
},{"../internal/invalidated":65,"../lru/splice":84,"../values/expires-never":138,"../values/expires-now":139,"./now":122}],118:[function(require,module,exports){
var obj_typeof = "object";
module.exports = function(value) {
return value != null && typeof value == obj_typeof;
}
},{}],119:[function(require,module,exports){
var obj_typeof = "object";
module.exports = function(value) {
return value == null || typeof value != obj_typeof;
}
},{}],120:[function(require,module,exports){
module.exports = key_to_keyset;
var __offset = require("../internal/offset");
var is_array = Array.isArray;
var is_object = require("./is-object");
function key_to_keyset(key, iskeyset) {
if(iskeyset) {
if(is_array(key)) {
key = key[key[__offset]];
return key_to_keyset(key, is_object(key));
} else {
return key[__offset];
}
}
return key;
}
},{"../internal/offset":68,"./is-object":118}],121:[function(require,module,exports){
var $self = "./";
var $path = require("../types/path");
var $sentinel = require("../types/sentinel");
var $expires_now = require("../values/expires-now");
var is_object = require("./is-object");
var is_primitive = require("./is-primitive");
var is_expired = require("./is-expired");
var promote = require("../lru/promote");
var wrap_node = require("./wrap-node");
var graph_node = require("./graph-node");
var replace_node = require("../support/replace-node");
var update_graph = require("../support/update-graph");
var inc_generation = require("./inc-generation");
var invalidate_node = require("./invalidate-node");
module.exports = function(roots, parent, node, messageParent, message, key) {
var type, messageType, node_is_object, message_is_object;
// If the cache and message are the same, we can probably return early:
// - If they're both null, return null.
// - If they're both branches, return the branch.
// - If they're both edges, continue below.
if(node == message) {
if(node == null) {
return null;
} else if(node_is_object = is_object(node)) {
type = node.$type;
if(type == null) {
if(node[$self] == null) {
return graph_node(roots[0], parent, node, key, 0);
}
return node;
}
}
} else if(node_is_object = is_object(node)) {
type = node.$type;
}
var value, messageValue;
if(type == $path) {
if(message == null) {
// If the cache is an expired reference, but the message
// is empty, remove the cache value and return undefined
// so we build a missing path.
if(is_expired(roots, node)) {
invalidate_node(parent, node, key, roots.lru);
return undefined;
}
// If the cache has a reference and the message is empty,
// leave the cache alone and follow the reference.
return node;
} else if(message_is_object = is_object(message)) {
messageType = message.$type;
// If the cache and the message are both references,
// check if we need to replace the cache reference.
if(messageType == $path) {
if(node === message) {
// If the cache and message are the same reference,
// we performed a whole-branch merge of one of the
// grandparents. If we've previously graphed this
// reference, break early.
if(node[$self] != null) {
return node;
}
}
// If the message doesn't expire immediately and is newer than the
// cache (or either cache or message don't have timestamps), attempt
// to use the message value.
// Note: Number and `undefined` compared LT/GT to `undefined` is `false`.
else if((
is_expired(roots, message) === false) && ((
message.$timestamp < node.$timestamp) === false)) {
// Compare the cache and message references.
// - If they're the same, break early so we don't insert.
// - If they're different, replace the cache reference.
value = node.value;
messageValue = message.value;
var count = value.length;
// If the reference lengths are equal, check their keys for equality.
if(count === messageValue.length) {
while(--count > -1) {
// If any of their keys are different, replace the reference
// in the cache with the reference in the message.
if(value[count] !== messageValue[count]) {
break;
}
}
// If all their keys are equal, leave the cache value alone.
if(count === -1) {
return node;
}
}
}
}
}
} else {
if(message_is_object = is_object(message)) {
messageType = message.$type;
}
if(node_is_object && !type) {
// Otherwise if the cache is a branch and the message is either
// null or also a branch, continue with the cache branch.
if(message == null || (message_is_object && !messageType)) {
return node;
}
}
}
// If the message is an expired edge, report it back out so we don't build a missing path, but
// don't insert it into the cache. If a value exists in the cache that didn't come from a
// whole-branch grandparent merge, remove the cache value.
if(!!messageType && !!message[$self] && is_expired(roots, message)) {
if(node_is_object && node != message) {
invalidate_node(parent, node, key, roots.lru);
}
return message;
}
// If the cache is a value, but the message is a branch, merge the branch over the value.
else if(!!type && message_is_object && !messageType) {
node = replace_node(parent, node, message, key, roots.lru);
return graph_node(roots[0], parent, node, key, 0);
}
// If the message is a value, insert it into the cache.
else if(!message_is_object || !!messageType) {
var offset = 0;
// If we've arrived at this message value, but didn't perform a whole-branch merge
// on one of its ancestors, replace the cache node with the message value.
if(node != message) {
messageValue || (messageValue = !!messageType ? message.value : message);
message = wrap_node(message, messageType, messageValue);
var size = node_is_object && node.$size || 0;
var messageSize = message.$size;
offset = size - messageSize;
node = replace_node(parent, node, message, key, roots.lru);
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// If the cache and the message are the same value, we branch-merged one of its
// ancestors. Give the message a $size and $type, attach its graph pointers, and
// update the cache sizes and generations.
else if(node_is_object && node[$self] == null) {
node = parent[key] = wrap_node(node, type, node.value);
offset = -node.$size;
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// Otherwise, cache and message are the same primitive value. Wrap in a sentinel and insert.
else {
node = parent[key] = wrap_node(node, type, node);
offset = -node.$size;
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// If the node is already expired, return undefined to build a missing path.
// if(is_expired(roots, node)) {
// return undefined;
// }
// Promote the message edge in the LRU.
promote(roots.lru, node);
}
// If we get here, the cache is empty and the message is a branch.
// Merge the whole branch over.
else if(node == null) {
node = parent[key] = graph_node(roots[0], parent, message, key, 0);
}
return node;
}
},{"../lru/promote":83,"../support/replace-node":126,"../support/update-graph":133,"../types/path":136,"../types/sentinel":137,"../values/expires-now":139,"./graph-node":113,"./inc-generation":114,"./invalidate-node":116,"./is-expired":117,"./is-object":118,"./is-primitive":119,"./wrap-node":134}],122:[function(require,module,exports){
module.exports = Date.now;
},{}],123:[function(require,module,exports){
var inc_version = require("../support/inc-version");
var getBoundValue = require('../get/getBoundValue');
module.exports = function(options, model, error_selector) {
var bound = options.bound || (options.bound = model._path || []);
var root = options.root || (options.root = model._cache);
var nodes = options.nodes || (options.nodes = []);
var lru = options.lru || (options.lru = model._root);
options.expired || (options.expired = lru.expired);
options.errors || (options.errors = []);
options.requestedPaths || (options.requestedPaths = []);
options.optimizedPaths || (options.optimizedPaths = []);
options.requestedMissingPaths || (options.requestedMissingPaths = []);
options.optimizedMissingPaths || (options.optimizedMissingPaths = []);
options.boxed = model._boxed || false;
options.materialized = model._materialized;
options.errorsAsValues = model._treatErrorsAsValues || false;
options.headless = model._dataSource == null;
options.version = inc_version();
options.offset || (options.offset = 0);
options.error_selector = error_selector || model._errorSelector;
if(bound.length) {
nodes[0] = getBoundValue(model, bound).value;
} else {
nodes[0] = root;
}
return options;
};
},{"../get/getBoundValue":45,"../support/inc-version":115}],124:[function(require,module,exports){
module.exports = permute_keyset;
var __offset = require("../internal/offset");
var is_array = Array.isArray;
var is_object = require("./is-object");
function permute_keyset(key) {
if(is_array(key)) {
if(key[__offset] === undefined) {
key[__offset] = -1;
if(key.length == 0) {
return false;
}
}
if(++key[__offset] >= key.length) {
return permute_keyset(key[key[__offset] = -1]);
} else {
return true;
}
} else if(is_object(key)) {
if(key[__offset] === undefined) {
key[__offset] = (key.from || (key.from = 0)) - 1;
if(key.to === undefined) {
if(key.length === undefined) {
throw new Error("Range keysets must specify at least one index to retrieve.");
} else if(key.length === 0) {
return false;
}
key.to = key.from + (key.length || 1) - 1;
}
}
if(++key[__offset] > key.to) {
key[__offset] = key.from - 1;
return false;
}
return true;
}
return false;
}
},{"../internal/offset":68,"./is-object":118}],125:[function(require,module,exports){
var $path = require("../types/path");
var __parent = require("../internal/parent");
var unlink = require("./unlink");
var delete_back_refs = require("./delete-back-refs");
var splice = require("../lru/splice");
var is_object = require("./is-object");
module.exports = function(parent, node, key, lru) {
if(is_object(node)) {
var type = node.$type;
if(!!type) {
if(type == $path) { unlink(node); }
splice(lru, node);
}
delete_back_refs(node);
parent[key] = node[__parent] = undefined;
return true;
}
return false;
}
},{"../internal/parent":69,"../lru/splice":84,"../types/path":136,"./delete-back-refs":111,"./is-object":118,"./unlink":131}],126:[function(require,module,exports){
var transfer_back_refs = require("./transfer-back-refs");
var invalidate_node = require("./invalidate-node");
module.exports = function(parent, node, replacement, key, lru) {
if(node != null && node !== replacement && typeof node == "object") {
transfer_back_refs(node, replacement);
invalidate_node(parent, node, key, lru);
}
return parent[key] = replacement;
}
},{"./invalidate-node":116,"./transfer-back-refs":127}],127:[function(require,module,exports){
var __ref = require("../internal/ref");
var __context = require("../internal/context");
var __refs_length = require("../internal/refs-length");
module.exports = function(node, dest) {
var nodeRefsLength = node[__refs_length] || 0,
destRefsLength = dest[__refs_length] || 0,
i = -1, ref;
while(++i < nodeRefsLength) {
ref = node[__ref + i];
if(ref !== undefined) {
ref[__context] = dest;
dest[__ref + (destRefsLength + i)] = ref;
node[__ref + i] = undefined;
}
}
dest[__refs_length] = nodeRefsLength + destRefsLength;
node[__refs_length] = ref = undefined;
}
},{"../internal/context":62,"../internal/ref":73,"../internal/refs-length":74}],128:[function(require,module,exports){
var $error = require("../types/error");
var promote = require("../lru/promote");
var array_clone = require("./array-clone");
module.exports = function(roots, node, type, path) {
if(node == null) {
return false;
}
promote(roots.lru, node);
if(type != $error || roots.errorsAsValues) {
return false;
}
roots.errors.push({ path: array_clone(path), value: node.value });
return true;
};
},{"../lru/promote":83,"../types/error":135,"./array-clone":100}],129:[function(require,module,exports){
var $sentinel = require("../types/sentinel");
var clone_misses = require("./clone-missing-path-maps");
var is_expired = require("./is-expired");
module.exports = function(roots, node, type, pathmap, keys_stack, depth, requested, optimized) {
var dematerialized = !roots.materialized;
if(node == null && dematerialized) {
clone_misses(roots, pathmap, keys_stack, depth, requested, optimized);
return true;
} else if(!!type) {
if(type == $sentinel && node.value === undefined && dematerialized && !roots.boxed) {
return true;
} else if(is_expired(roots, node)) {
clone_misses(roots, pathmap, keys_stack, depth, requested, optimized);
return true;
}
}
return false;
};
},{"../types/sentinel":137,"./clone-missing-path-maps":104,"./is-expired":117}],130:[function(require,module,exports){
var $sentinel = require("../types/sentinel");
var clone_misses = require("./clone-missing-path-sets");
var is_expired = require("./is-expired");
module.exports = function(roots, node, type, pathset, depth, requested, optimized) {
var dematerialized = !roots.materialized;
if(node == null && dematerialized) {
clone_misses(roots, pathset, depth, requested, optimized);
return true;
} else if(!!type) {
if(type == $sentinel && node.value === undefined && dematerialized && !roots.boxed) {
return true;
} else if(is_expired(roots, node)) {
clone_misses(roots, pathset, depth, requested, optimized);
return true;
}
}
return false;
};
},{"../types/sentinel":137,"./clone-missing-path-sets":105,"./is-expired":117}],131:[function(require,module,exports){
var __ref = require("../internal/ref");
var __context = require("../internal/context");
var __ref_index = require("../internal/ref-index");
var __refs_length = require("../internal/refs-length");
module.exports = function(ref) {
var destination = ref[__context];
if(destination) {
var i = (ref[__ref_index] || 0) - 1,
n = (destination[__refs_length] || 0) - 1;
while(++i <= n) {
destination[__ref + i] = destination[__ref + (i + 1)];
}
destination[__refs_length] = n;
ref[__ref_index] = ref[__context] = destination = undefined;
}
}
},{"../internal/context":62,"../internal/ref":73,"../internal/ref-index":72,"../internal/refs-length":74}],132:[function(require,module,exports){
module.exports = update_back_refs;
var __ref = require("../internal/ref");
var __parent = require("../internal/parent");
var __version = require("../internal/version");
var __generation = require("../internal/generation");
var __refs_length = require("../internal/refs-length");
var generation = require("./inc-generation");
function update_back_refs(node, version) {
if(node && node[__version] !== version) {
node[__version] = version;
node[__generation] = generation();
update_back_refs(node[__parent], version);
var i = -1, n = node[__refs_length] || 0;
while(++i < n) {
update_back_refs(node[__ref + i], version);
}
}
return node;
}
},{"../internal/generation":63,"../internal/parent":69,"../internal/ref":73,"../internal/refs-length":74,"../internal/version":76,"./inc-generation":114}],133:[function(require,module,exports){
var __key = require("../internal/key");
var __version = require("../internal/version");
var __parent = require("../internal/parent");
var remove_node = require("./remove-node");
var update_back_refs = require("./update-back-refs");
module.exports = function(node, offset, version, lru) {
var child;
while(child = node) {
node = child[__parent];
if((child.$size = (child.$size || 0) - offset) <= 0 && node != null) {
remove_node(node, child, child[__key], lru);
} else if(child[__version] !== version) {
update_back_refs(child, version);
}
}
}
},{"../internal/key":66,"../internal/parent":69,"../internal/version":76,"./remove-node":125,"./update-back-refs":132}],134:[function(require,module,exports){
var $path = require("../types/path");
var $error = require("../types/error");
var $sentinel = require("../types/sentinel");
var now = require("./now");
var clone = require("./clone");
var is_array = Array.isArray;
var is_object = require("./is-object");
module.exports = function(node, type, value) {
var dest = node, size = 0;
if(!!type) {
dest = clone(node);
size = dest.$size;
// }
// if(type == $path) {
// dest = clone(node);
// size = 50 + (value.length || 1);
// } else if(is_object(node) && (type || (type = node.$type))) {
// dest = clone(node);
// size = dest.$size;
} else {
dest = { value: value };
type = $sentinel;
}
if(size <= 0 || size == null) {
switch(typeof value) {
case "number":
case "boolean":
case "function":
case "undefined":
size = 51;
break;
case "object":
size = is_array(value) && (50 + value.length) || 51;
break;
case "string":
size = 50 + value.length;
break;
}
}
var expires = is_object(node) && node.$expires || undefined;
if(typeof expires === "number" && expires < 0) {
dest.$expires = now() + (expires * -1);
}
dest.$type = type;
dest.$size = size;
return dest;
}
},{"../types/error":135,"../types/path":136,"../types/sentinel":137,"./clone":109,"./is-object":118,"./now":122}],135:[function(require,module,exports){
module.exports = "error";
},{}],136:[function(require,module,exports){
module.exports = "ref";
},{}],137:[function(require,module,exports){
module.exports = "sentinel";
},{}],138:[function(require,module,exports){
module.exports = 1;
},{}],139:[function(require,module,exports){
module.exports = 0;
},{}],140:[function(require,module,exports){
module.exports = walk_path_map;
var prefix = require("../internal/prefix");
var $path = require("../types/path");
var walk_reference = require("./walk-reference");
var array_slice = require("../support/array-slice");
var array_clone = require("../support/array-clone");
var array_append = require("../support/array-append");
var is_expired = require("../support/is-expired");
var is_primitive = require("../support/is-primitive");
var is_object = require("../support/is-object");
var is_array = Array.isArray;
var promote = require("../lru/promote");
function walk_path_map(onNode, onEdge, pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(is_primitive(pathmap) || is_primitive(node)) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[0] = parents[0] = roots[0];
nodes[1] = parents[1] = roots[1];
nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
optimized = array_clone(reference);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, true, null, keyset, false);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
if(type != null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keys_stack[depth] = Object.keys(pathmap);
if(keys.length == 0) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var is_outer_keyset = keys.length > 1;
for(var i = -1, n = keys.length; ++i < n;) {
var inner_key = keys[i];
if((inner_key[0] === prefix) || (inner_key[0] === "$")) {
continue;
}
var inner_keyset = is_outer_keyset ? inner_key : keyset;
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var pathmap2 = pathmap[inner_key];
var requested2, optimized2, is_branch;
var has_child_key = false;
var is_branch = is_object(pathmap2) && !pathmap2.$type;// && !is_array(pathmap2);
if(is_branch) {
for(child_key in pathmap2) {
if((child_key[0] === prefix) || (child_key[0] === "$")) {
continue;
}
child_key = pathmap2.hasOwnProperty(child_key);
break;
}
is_branch = child_key === true;
}
if(inner_key == "null") {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
inner_key = key;
inner_keyset = keyset;
pathmap2 = pathmap;
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
if(is_branch) {
walk_path_map(onNode, onEdge,
pathmap2, keys_stack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
} else {
onEdge(pathmap2, keys_stack, depth, roots, parents2, nodes2, requested2, optimized2, inner_key, inner_keyset);
}
}
}
},{"../internal/prefix":70,"../lru/promote":83,"../support/array-append":99,"../support/array-clone":100,"../support/array-slice":101,"../support/is-expired":117,"../support/is-object":118,"../support/is-primitive":119,"../types/path":136,"./walk-reference":144}],141:[function(require,module,exports){
module.exports = walk_path_map;
var prefix = require("../internal/prefix");
var __context = require("../internal/context");
var $path = require("../types/path");
var walk_reference = require("./walk-reference");
var array_slice = require("../support/array-slice");
var array_clone = require("../support/array-clone");
var array_append = require("../support/array-append");
var is_expired = require("../support/is-expired");
var is_primitive = require("../support/is-primitive");
var is_object = require("../support/is-object");
var is_array = Array.isArray;
var promote = require("../lru/promote");
function walk_path_map(onNode, onEdge, pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(is_primitive(pathmap) || is_primitive(node)) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if(node != null) {
type = node.$type;
optimized = array_clone(reference);
nodes[0] = node;
} else {
nodes[0] = parents[0] = roots[0];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
optimized = array_clone(reference);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, true, null, keyset, false);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
}
if(type != null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keys_stack[depth] = Object.keys(pathmap);
if(keys.length == 0) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var is_outer_keyset = keys.length > 1;
for(var i = -1, n = keys.length; ++i < n;) {
var inner_key = keys[i];
if((inner_key[0] === prefix) || (inner_key[0] === "$")) {
continue;
}
var inner_keyset = is_outer_keyset ? inner_key : keyset;
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var pathmap2 = pathmap[inner_key];
var requested2, optimized2, is_branch;
var child_key = false;
var is_branch = is_object(pathmap2) && !pathmap2.$type;// && !is_array(pathmap2);
if(is_branch) {
for(child_key in pathmap2) {
if((child_key[0] === prefix) || (child_key[0] === "$")) {
continue;
}
child_key = pathmap2.hasOwnProperty(child_key);
break;
}
is_branch = child_key === true;
}
if(inner_key == "null") {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
inner_key = key;
inner_keyset = keyset;
pathmap2 = pathmap;
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
if(is_branch) {
walk_path_map(onNode, onEdge,
pathmap2, keys_stack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
} else {
onEdge(pathmap2, keys_stack, depth, roots, parents2, nodes2, requested2, optimized2, inner_key, inner_keyset);
}
}
}
},{"../internal/context":62,"../internal/prefix":70,"../lru/promote":83,"../support/array-append":99,"../support/array-clone":100,"../support/array-slice":101,"../support/is-expired":117,"../support/is-object":118,"../support/is-primitive":119,"../types/path":136,"./walk-reference":144}],142:[function(require,module,exports){
module.exports = walk_path_set;
var $path = require("../types/path");
var empty_array = new Array(0);
var walk_reference = require("./walk-reference");
var array_slice = require("../support/array-slice");
var array_clone = require("../support/array-clone");
var array_append = require("../support/array-append");
var is_expired = require("../support/is-expired");
var is_primitive = require("../support/is-primitive");
var is_object = require("../support/is-object");
var keyset_to_key = require("../support/keyset-to-key");
var permute_keyset = require("../support/permute-keyset");
var promote = require("../lru/promote");
function walk_path_set(onNode, onEdge, pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(depth >= pathset.length || is_primitive(node)) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[0] = parents[0] = roots[0];
nodes[1] = parents[1] = roots[1];
nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
optimized = array_clone(reference);
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathset, roots, parents, nodes, requested, optimized, true, false, null, keyset, false);
return onEdge(pathset, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
if(type != null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outer_key = pathset[depth];
var is_outer_keyset = is_object(outer_key);
var is_branch = depth < pathset.length - 1;
var run_once = false;
while(is_outer_keyset && permute_keyset(outer_key) && (run_once = true) || (run_once = !run_once)) {
var inner_key, inner_keyset;
if(is_outer_keyset === true) {
inner_key = keyset_to_key(outer_key, true);
inner_keyset = inner_key;
} else {
inner_key = outer_key;
inner_keyset = keyset;
}
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var requested2, optimized2;
if(inner_key == null) {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
// optimized2 = optimized;
inner_key = key;
inner_keyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
walk_path_set(onNode, onEdge,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
}
}
},{"../lru/promote":83,"../support/array-append":99,"../support/array-clone":100,"../support/array-slice":101,"../support/is-expired":117,"../support/is-object":118,"../support/is-primitive":119,"../support/keyset-to-key":120,"../support/permute-keyset":124,"../types/path":136,"./walk-reference":144}],143:[function(require,module,exports){
module.exports = walk_path_set;
var prefix = require("../internal/prefix");
var __context = require("../internal/context");
var $path = require("../types/path");
var empty_array = new Array(0);
var walk_reference = require("./walk-reference");
var array_slice = require("../support/array-slice");
var array_clone = require("../support/array-clone");
var array_append = require("../support/array-append");
var is_expired = require("../support/is-expired");
var is_primitive = require("../support/is-primitive");
var is_object = require("../support/is-object");
var keyset_to_key = require("../support/keyset-to-key");
var permute_keyset = require("../support/permute-keyset");
var promote = require("../lru/promote");
function walk_path_set(onNode, onEdge, pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(depth >= pathset.length || is_primitive(node)) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if(node != null) {
type = node.$type;
optimized = array_clone(reference);
nodes[0] = node;
} else {
nodes[0] = parents[0] = roots[0];
// nodes[1] = parents[1] = roots[1];
// nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
optimized = array_clone(reference);
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathset, roots, parents, nodes, requested, optimized, true, false, null, keyset, false);
return onEdge(pathset, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
}
if(type != null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outer_key = pathset[depth];
var is_outer_keyset = is_object(outer_key);
var is_branch = depth < pathset.length - 1;
var run_once = false;
while(is_outer_keyset && permute_keyset(outer_key) && (run_once = true) || (run_once = !run_once)) {
var inner_key, inner_keyset;
if(is_outer_keyset === true) {
inner_key = keyset_to_key(outer_key, true);
inner_keyset = inner_key;
} else {
inner_key = outer_key;
inner_keyset = keyset;
}
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var requested2, optimized2;
if(inner_key == null) {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
// optimized2 = optimized;
inner_key = key;
inner_keyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
walk_path_set(onNode, onEdge,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
}
}
},{"../internal/context":62,"../internal/prefix":70,"../lru/promote":83,"../support/array-append":99,"../support/array-clone":100,"../support/array-slice":101,"../support/is-expired":117,"../support/is-object":118,"../support/is-primitive":119,"../support/keyset-to-key":120,"../support/permute-keyset":124,"../types/path":136,"./walk-reference":144}],144:[function(require,module,exports){
module.exports = walk_reference;
var prefix = require("../internal/prefix");
var __ref = require("../internal/ref");
var __context = require("../internal/context");
var __ref_index = require("../internal/ref-index");
var __refs_length = require("../internal/refs-length");
var is_object = require("../support/is-object");
var is_primitive = require("../support/is-primitive");
var array_slice = require("../support/array-slice");
var array_append = require("../support/array-append");
function walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized) {
optimized.length = 0;
var index = -1;
var count = reference.length;
var node, key, keyset;
while(++index < count) {
node = nodes[0];
if(node == null) {
return nodes;
} else if(is_primitive(node) || node.$type) {
onNode(reference, roots, parents, nodes, requested, optimized, false, false, keyset, null, false);
return nodes;
}
do {
key = reference[index];
if(key != null) {
keyset = key;
optimized.push(key);
onNode(reference, roots, parents, nodes, requested, optimized, false, index < count - 1, key, null, false);
break;
}
} while(++index < count);
}
node = nodes[0];
if(is_object(node) && container[__context] !== node) {
var backrefs = node[__refs_length] || 0;
node[__refs_length] = backrefs + 1;
node[__ref + backrefs] = container;
container[__context] = node;
container[__ref_index] = backrefs;
}
return nodes;
}
},{"../internal/context":62,"../internal/prefix":70,"../internal/ref":73,"../internal/ref-index":72,"../internal/refs-length":74,"../support/array-append":99,"../support/array-slice":101,"../support/is-object":118,"../support/is-primitive":119}],145:[function(require,module,exports){
/*global define:false require:false */
module.exports = (function(){
// Import Events
var events = require('events')
// Export Domain
var domain = {}
domain.createDomain = domain.create = function(){
var d = new events.EventEmitter()
function emitError(e) {
d.emit('error', e)
}
d.add = function(emitter){
emitter.on('error', emitError)
}
d.remove = function(emitter){
emitter.removeListener('error', emitError)
}
d.bind = function(fn){
return function(){
var args = Array.prototype.slice.call(arguments)
try {
fn.apply(null, args)
}
catch (err){
emitError(err)
}
}
}
d.intercept = function(fn){
return function(err){
if ( err ) {
emitError(err)
}
else {
var args = Array.prototype.slice.call(arguments, 1)
try {
fn.apply(null, args)
}
catch (err){
emitError(err)
}
}
}
}
d.run = function(fn){
try {
fn()
}
catch (err) {
emitError(err)
}
return this
};
d.dispose = function(){
this.removeAllListeners()
return this
};
d.enter = d.exit = function(){
return this
}
return d
};
return domain
}).call(this)
},{"events":146}],146:[function(require,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:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
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) {
var m;
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 {
// 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.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
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;
}
},{}],147:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
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');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],148:[function(require,module,exports){
(function (global){
/*!
* Copyright 2014 Netflix, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.falcor=e()}}(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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){
module.exports = _dereq_('./operations');
},{"./operations":149}],2:[function(_dereq_,module,exports){
if (typeof falcor === 'undefined') {
var falcor = {};
}
var Rx = _dereq_('./rx.ultralite');
falcor.__Internals = {};
falcor.Observable = Rx.Observable;
falcor.EXPIRES_NOW = 0;
falcor.EXPIRES_NEVER = 1;
/**
* The current semVer'd data version of falcor.
*/
falcor.dataVersion = '0.1.0';
falcor.now = function now() {
return Date.now();
};
falcor.NOOP = function() {};
module.exports = falcor;
},{"./rx.ultralite":41}],3:[function(_dereq_,module,exports){
var falcor = _dereq_('./Falcor');
var RequestQueue = _dereq_('./request/RequestQueue');
var ImmediateScheduler = _dereq_('./scheduler/ImmediateScheduler');
var TimeoutScheduler = _dereq_('./scheduler/TimeoutScheduler');
var ERROR = _dereq_("../types/error");
var ModelResponse = _dereq_('./ModelResponse');
var call = _dereq_('./operations/call');
var operations = _dereq_('./operations');
var dotSyntaxParser = _dereq_('./operations/parser/parser');
var getBoundValue = _dereq_('./../get/getBoundValue');
var slice = Array.prototype.slice;
var $ref = _dereq_('./../types/path');
var $error = _dereq_('./../types/error');
var $sentinel = _dereq_('./../types/sentinel');
var Model = module.exports = falcor.Model = function Model(options) {
if (!options) {
options = {};
}
this._materialized = options.materialized || false;
this._boxed = options.boxed || false;
this._treatErrorsAsValues = options.treatErrorsAsValues || false;
this._dataSource = options.source;
this._maxSize = options.maxSize || Math.pow(2, 53) - 1;
this._collectRatio = options.collectRatio || 0.75;
this._scheduler = new ImmediateScheduler();
this._request = new RequestQueue(this, this._scheduler);
this._errorSelector = options.errorSelector || Model.prototype._errorSelector;
this._router = options.router;
this._root = options.root || {
expired: [],
allowSync: false,
unsafeMode: true
};
if (options.cache && typeof options.cache === "object") {
this.setCache(options.cache);
} else {
this._cache = {};
}
this._path = [];
};
Model.EXPIRES_NOW = falcor.EXPIRES_NOW;
Model.EXPIRES_NEVER = falcor.EXPIRES_NEVER;
Model.ref = function(path) {
if (typeof path === 'string') {
path = dotSyntaxParser(path);
}
return {$type: $ref, value: path};
};
Model.error = function(error) {
return {$type: $error, value: error};
};
Model.atom = function(value) {
return {$type: $sentinel, value: value};
};
Model.prototype = {
_boxed: false,
_progressive: false,
_errorSelector: function(x, y) { return y; },
get: operations('get'),
set: operations("set"),
invalidate: operations("invalidate"),
call: call,
getValue: function(path) {
return this.get(path, function(x) { return x });
},
setValue: function(path, value) {
return this.set(Array.isArray(path) ?
{path: path, value: value} :
path, function(x) { return x; });
},
bind: function(boundPath) {
var model = this, root = model._root,
paths = new Array(arguments.length - 1),
i = -1, n = arguments.length - 1;
while(++i < n) {
paths[i] = arguments[i + 1];
}
if(n === 0) { throw new Error("Model#bind requires at least one value path."); }
return falcor.Observable.create(function(observer) {
var boundModel;
try {
root.allowSync = true;
if(!(boundModel = model.bindSync(model._path.concat(boundPath)))) {
throw false;
}
root.allowSync = false;
observer.onNext(boundModel);
observer.onCompleted();
} catch (e) {
root.allowSync = false;
return model.get.apply(model, paths.map(function(path) {
return boundPath.concat(path);
}).concat(function(){})).subscribe(
function onNext() {},
function onError(err) { observer.onError(err); },
function onCompleted() {
try {
if(boundModel = model.bindSync(boundPath)) {
observer.onNext(boundModel);
}
observer.onCompleted();
} catch(e) {
observer.onError(e);
}
});
}
});
},
setCache: function(cache) {
return (this._cache = {}) && this._setCache(this, cache);
},
getValueSync: function(path) {
if (Array.isArray(path) === false) {
throw new Error("Model#getValueSync must be called with an Array path.");
}
if (this._path.length) {
path = this._path.concat(path);
}
return this.syncCheck("getValueSync") && this._getValueSync(this, path).value;
},
setValueSync: function(path, value, errorSelector) {
if(Array.isArray(path) === false) {
if(typeof errorSelector !== "function") {
errorSelector = value || this._errorSelector;
}
value = path.value;
path = path.path;
}
if(Array.isArray(path) === false) {
throw new Error("Model#setValueSync must be called with an Array path.");
}
if(this.syncCheck("setValueSync")) {
var json = {};
var tEeAV = this._treatErrorsAsValues;
var boxed = this._boxed;
this._treatErrorsAsValues = true;
this._boxed = true;
this._setPathSetsAsJSON(this, [{path: path, value: value}], [json], errorSelector);
this._treatErrorsAsValues = tEeAV;
this._boxed = boxed;
json = json.json;
if(json && json.$type === ERROR && !this._treatErrorsAsValues) {
if(this._boxed) {
throw json;
} else {
throw json.value;
}
} else if(this._boxed) {
return json;
}
return json && json.value;
}
},
bindSync: function(path) {
if(Array.isArray(path) === false) {
throw new Error("Model#bindSync must be called with an Array path.");
}
var boundValue = this.syncCheck("bindSync") && getBoundValue(this, this._path.concat(path));
var node = boundValue.value;
path = boundValue.path;
if(boundValue.shorted) {
if(!!node) {
if(node.$type === ERROR) {
if(this._boxed) {
throw node;
}
throw node.value;
// throw new Error("Model#bindSync can\'t bind to or beyond an error: " + boundValue.toString());
}
}
return undefined;
} else if(!!node && node.$type === ERROR) {
if(this._boxed) {
throw node;
}
throw node.value;
}
return this.clone(["_path", boundValue.path]);
},
// TODO: This seems like a great place for optimizations
clone: function() {
var self = this;
var clone = new Model();
Object.keys(self).forEach(function(key) {
clone[key] = self[key];
});
slice.call(arguments).forEach(function(tuple) {
clone[tuple[0]] = tuple[1];
});
return clone;
},
batch: function(schedulerOrDelay) {
if(typeof schedulerOrDelay === "number") {
schedulerOrDelay = new TimeoutScheduler(Math.round(Math.abs(schedulerOrDelay)));
} else if(!schedulerOrDelay || !schedulerOrDelay.schedule) {
schedulerOrDelay = new ImmediateScheduler();
}
return this.clone(["_request", new RequestQueue(this, schedulerOrDelay)]);
},
unbatch: function() {
return this.clone(["_request", new RequestQueue(this, new ImmediateScheduler())]);
},
treatErrorsAsValues: function() {
return this.clone(["_treatErrorsAsValues", true]);
},
materialize: function() {
return this.clone(["_materialized", true]);
},
boxValues: function() {
return this.clone(["_boxed", true]);
},
unboxValues: function() {
return this.clone(["_boxed", false]);
},
withoutDataSource: function() {
return this.clone(["_dataSource", null]);
},
syncCheck: function(name) {
if (!!this._dataSource && this._root.allowSync === false && this._root.unsafeMode === false) {
throw new Error("Model#" + name + " may only be called within the context of a request selector.");
}
return true;
}
};
},{"../types/error":139,"./../get/getBoundValue":49,"./../types/error":139,"./../types/path":140,"./../types/sentinel":141,"./Falcor":2,"./ModelResponse":4,"./operations":11,"./operations/call":6,"./operations/parser/parser":16,"./request/RequestQueue":40,"./scheduler/ImmediateScheduler":42,"./scheduler/TimeoutScheduler":43}],4:[function(_dereq_,module,exports){
var falcor = _dereq_('./Falcor');
var Observable = falcor.Observable,
valuesMixin = { format: { value: "AsValues" } },
jsonMixin = { format: { value: "AsPathMap" } },
jsongMixin = { format: { value: "AsJSONG" } },
progressiveMixin = { operationIsProgressive: { value: true } };
function ModelResponse(forEach) {
this._subscribe = forEach;
}
ModelResponse.create = function(forEach) {
return new ModelResponse(forEach);
};
ModelResponse.fromOperation = function(model, args, selector, forEach) {
return new ModelResponse(function(observer) {
return forEach(Object.create(observer, {
operationModel: {value: model},
operationArgs: {value: args},
operationSelector: {value: selector}
}));
});
};
function noop() {}
function mixin(self) {
var mixins = Array.prototype.slice.call(arguments, 1);
return new ModelResponse(function(other) {
return self.subscribe(mixins.reduce(function(proto, mixin) {
return Object.create(proto, mixin);
}, other));
});
}
ModelResponse.prototype = Observable.create(noop);
ModelResponse.prototype.format = "AsPathMap";
ModelResponse.prototype.toPathValues = function() {
return mixin(this, valuesMixin);
};
ModelResponse.prototype.toJSON = function() {
return mixin(this, jsonMixin);
};
ModelResponse.prototype.progressively = function() {
return mixin(this, progressiveMixin);
};
ModelResponse.prototype.toJSONG = function() {
return mixin(this, jsongMixin);
};
module.exports = ModelResponse;
},{"./Falcor":2}],5:[function(_dereq_,module,exports){
var falcor = _dereq_('./Falcor');
var Model = _dereq_('./Model');
falcor.Model = Model;
module.exports = falcor;
},{"./Falcor":2,"./Model":3}],6:[function(_dereq_,module,exports){
module.exports = call;
var falcor = _dereq_("../../Falcor");
var ModelResponse = _dereq_('./../../ModelResponse');
function call(path, args, suffixes, paths, selector) {
var model = this;
args && Array.isArray(args) || (args = []);
suffixes && Array.isArray(suffixes) || (suffixes = []);
paths = Array.prototype.slice.call(arguments, 3);
if (typeof (selector = paths[paths.length - 1]) !== "function") {
selector = undefined;
} else {
paths = paths.slice(0, -1);
}
return ModelResponse.create(function (options) {
var rootModel = model.clone(["_path", []]),
localRoot = rootModel.withoutDataSource(),
dataSource = model._dataSource,
boundPath = model._path,
callPath = boundPath.concat(path),
thisPath = callPath.slice(0, -1);
var disposable = model.
getValue(path).
flatMap(function (localFn) {
if (typeof localFn === "function") {
return falcor.Observable.return(localFn.
apply(rootModel.bindSync(thisPath), args).
map(function (pathValue) {
return {
path: thisPath.concat(pathValue.path),
value: pathValue.value
};
}).
toArray().
flatMap(function (pathValues) {
return localRoot.set.
apply(localRoot, pathValues).
toJSONG();
}).
flatMap(function (envelope) {
return rootModel.get.apply(rootModel,
envelope.paths.reduce(function (paths, path) {
return paths.concat(suffixes.map(function (suffix) {
return path.concat(suffix);
}));
}, []).
concat(paths.reduce(function (paths, path) {
return paths.concat(thisPath.concat(path));
}, []))).
toJSONG();
}));
}
return falcor.Observable.empty();
}).
defaultIfEmpty(dataSource.call(path, args, suffixes, paths)).
mergeAll().
subscribe(function (envelope) {
var invalidated = envelope.invalidated;
if (invalidated && invalidated.length) {
invalidatePaths(rootModel, invalidated, undefined, model._errorSelector);
}
disposable = localRoot.
set(envelope, function () {
return model;
}).
subscribe(function (model) {
var getPaths = envelope.paths.map(function (path) {
return path.slice(boundPath.length);
});
if (selector) {
getPaths[getPaths.length] = function () {
return selector.call(model, getPaths);
};
}
disposable = model.get.apply(model, getPaths).subscribe(options);
});
});
return {
dispose: function () {
disposable && disposable.dispose();
disposable = undefined;
}
};
});
}
},{"../../Falcor":2,"./../../ModelResponse":4}],7:[function(_dereq_,module,exports){
var combineOperations = _dereq_('./../support/combineOperations');
var setSeedsOrOnNext = _dereq_('./../support/setSeedsOrOnNext');
/**
* The initial args that are passed into the async request pipeline.
* @see lib/falcor/operations/request.js for how initialArgs are used
*/
module.exports = function getInitialArgs(options, seeds, onNext) {
var seedRequired = options.format !== 'AsValues';
var isProgressive = options.operationIsProgressive;
var spreadOperations = false;
var operations =
combineOperations(
options.operationArgs, options.format, 'get',
spreadOperations, isProgressive);
setSeedsOrOnNext(
operations, seedRequired, seeds, onNext, options.operationSelector);
var requestOptions;
return [operations];
};
},{"./../support/combineOperations":26,"./../support/setSeedsOrOnNext":39}],8:[function(_dereq_,module,exports){
var getSourceObserver = _dereq_('./../support/getSourceObserever');
var partitionOperations = _dereq_('./../support/partitionOperations');
var mergeBoundPath = _dereq_('./../support/mergeBoundPath');
module.exports = getSourceRequest;
function getSourceRequest(
options, onNext, seeds, combinedResults, requestOptions, cb) {
var model = options.operationModel;
var boundPath = model._path;
var missingPaths = combinedResults.requestedMissingPaths;
if (boundPath.length) {
for (var i = 0; i < missingPaths.length; ++i) {
var pathSetIndex = missingPaths[i].pathSetIndex;
var path = missingPaths[i] = boundPath.concat(missingPaths[i]);
path.pathSetIndex = pathSetIndex;
}
}
return model._request.get(
missingPaths,
combinedResults.optimizedMissingPaths,
getSourceObserver(
model,
missingPaths,
function getSourceCallback(err, results) {
if (err) {
cb(err);
return;
}
// partitions the operations by their pathSetIndex
var partitionOperationsAndSeeds = partitionOperations(
results,
seeds,
options.format,
onNext);
// We allow for the rerequesting to happen.
cb(null, partitionOperationsAndSeeds);
}));
}
},{"./../support/getSourceObserever":27,"./../support/mergeBoundPath":31,"./../support/partitionOperations":34}],9:[function(_dereq_,module,exports){
var getInitialArgs = _dereq_('./getInitialArgs');
var getSourceRequest = _dereq_('./getSourceRequest');
var shouldRequest = _dereq_('./shouldRequest');
var request = _dereq_('./../request');
var processOperations = _dereq_('./../support/processOperations');
var get = request(
getInitialArgs,
getSourceRequest,
processOperations,
shouldRequest);
module.exports = get;
},{"./../request":18,"./../support/processOperations":36,"./getInitialArgs":7,"./getSourceRequest":8,"./shouldRequest":10}],10:[function(_dereq_,module,exports){
module.exports = function(model, combinedResults) {
return model._dataSource && combinedResults.requestedMissingPaths.length > 0;
};
},{}],11:[function(_dereq_,module,exports){
var ModelResponse = _dereq_('../ModelResponse');
var get = _dereq_('./get');
var set = _dereq_('./set');
var invalidate = _dereq_('./invalidate');
module.exports = function modelOperation(name) {
return function() {
var model = this, root = model._root,
args = Array.prototype.slice.call(arguments),
selector = args[args.length - 1];
if (typeof selector === 'function') {
args.pop();
} else {
selector = false;
}
var modelResponder;
switch (name) {
case 'get':
modelResponder = get;
break;
case 'set':
modelResponder = set;
break;
case 'invalidate':
modelResponder = invalidate;
break;
}
return ModelResponse.fromOperation(
model,
args,
selector,
modelResponder);
};
};
},{"../ModelResponse":4,"./get":9,"./invalidate":12,"./set":19}],12:[function(_dereq_,module,exports){
var invalidateInitialArgs = _dereq_('./invalidateInitialArgs');
var request = _dereq_('./../request');
var processOperations = _dereq_('./../support/processOperations');
var invalidate = request(
invalidateInitialArgs,
null,
processOperations);
module.exports = invalidate;
},{"./../request":18,"./../support/processOperations":36,"./invalidateInitialArgs":13}],13:[function(_dereq_,module,exports){
var combineOperations = _dereq_('./../support/combineOperations');
var setSeedsOrOnNext = _dereq_('./../support/setSeedsOrOnNext');
module.exports = function getInitialArgs(options, seeds, onNext) {
var seedRequired = options.format !== 'AsValues';
var operations = combineOperations(
options.operationArgs, options.format, 'inv');
setSeedsOrOnNext(
operations, seedRequired, seeds,
onNext, options.operationSelector);
return [operations, seeds];
};
},{"./../support/combineOperations":26,"./../support/setSeedsOrOnNext":39}],14:[function(_dereq_,module,exports){
module.exports = {
token: 'token',
dotSeparator: '.',
commaSeparator: ',',
openingBracket: '[',
closingBracket: ']',
space: 'space',
quote: 'quote',
unknown: 'unknown'
};
},{}],15:[function(_dereq_,module,exports){
module.exports = {
nestedIndexers: 'Indexers cannot be nested',
closingWithoutOpeningIndexer: 'A closing indexer, "]", was provided without an opening indexer.',
leadingDotInIndexer: 'The dot operator in an indexer cannot be used this way.',
twoDot: 'Cannot have two dot separators outside of an indexer range.',
dotComma: 'Cannot have a comma preceded by a dot separator.',
commasOutsideOfIndexers: 'Commas cannot be used outside of indexers.',
trailingComma: 'Cannot have trailing commas in indexers.',
leadingComma: 'Leading commas in ranges are not allowed.',
emptyQuotes: 'Cannot have empty quotes',
emptyIndexer: 'Cannot have empty indexer.',
quotesOutsideIndexer: 'Cannot have quotes outside indexer.',
nonTerminatingQuotes: 'The quotes within the indexer were not closed.',
tokensMustBeNumeric: 'Tokens without quotes must be numeric.',
indexerTokensMustBeCommaDelimited: 'Indexer tokens must be comma delimited.',
numericRange: 'Only numeric keys can be used in ranges.'
};
},{}],16:[function(_dereq_,module,exports){
var tokenizer = _dereq_('./tokenizer');
var TokenTypes = _dereq_('./TokenTypes');
var Expections = _dereq_('./expections');
/**
* not only is this the parser, it is also the
* semantic analyzer for brevity sake / we never need
* this to change overall types of output.
*/
module.exports = function parser(string) {
var out = [];
var tokenized = tokenizer(string);
var state = {};
var token = tokenized();
while (!token.done) {
switch (token.type) {
case TokenTypes.token:
insertToken(token.token, state, out);
break;
case TokenTypes.dotSeparator:
dotSeparator(token.token, state, out);
break;
case TokenTypes.space:
space(token.token, state, out);
break;
case TokenTypes.commaSeparator:
commaSeparator(token.token, state, out);
break;
case TokenTypes.openingBracket:
openIndexer(token.token, state, out);
break;
case TokenTypes.closingBracket:
closeIndexer(token.token, state, out);
break;
case TokenTypes.quote:
quote(token.token, state, out);
break;
}
token = tokenized();
}
return out;
};
function space(token, state, out) {
// The space character only matters when inIndexer
// and in quote mode.
if (state.inIndexer && state.quote) {
state.indexerToken += token;
}
}
function insertToken(token, state, out) {
state.hasDot = false;
// if within indexer then there are several edge cases.
if (state.inIndexer) {
tokenInIndexer(token, state, out);
return;
}
// if not in indexer just insert into end position.
out[out.length] = token;
}
function dotSeparator(token, state, out) {
// If in indexer then dotOperators have different meanings.
if (state.inIndexer) {
indexerDotOperator(token, state, out);
}
// throws an expection if a range operator is outside of a range.
else if (state.hasDot) {
throw Expections.twoDot;
}
state.hasDot = true;
}
function commaSeparator(token, state, out) {
if (state.hasDot) {
throw Expections.dotComma;
}
// If in indexer then dotOperators have different meanings.
if (state.inIndexer) {
indexerCommaOperator(token, state, out);
}
}
// Accumulates dotSeparators inside indexers
function indexerDotOperator(token, state, out) {
// must be preceded by token.
if (state.indexerToken === undefined) {
throw Expections.leadingDotInIndexer;
}
// if in quote mode, add the dot indexer to quote.
if (state.quote) {
state.indexerToken += token;
return;
}
if (!state.rangeCount) {
state.range = true;
state.rangeCount = 0;
}
++state.rangeCount;
if (state.rangeCount === 2) {
state.inclusiveRange = true;
}
else if (state.rangeCount === 3) {
state.exclusiveRange = true;
state.inclusiveRange = false;
}
}
function indexerCommaOperator(token, state, out) {
// are we a range indexer?
if (state.range) {
closeRangedIndexer(token, state, out);
}
// push previous token and clear state.
else if (state.inIndexer) {
pushTokenIntoIndexer(token, state, out);
}
// If a comma is used outside of an indexer throw
else {
throw Expections.commasOutsideOfIndexers;
}
}
function pushTokenIntoIndexer(token, state, out) {
// no token to push, throw error.
if (state.indexerToken === undefined) {
throw Expections.leadingComma;
}
// push the current token onto the stack then clear state.
state.indexer[state.indexer.length] = state.indexerToken;
cleanIndexerTokenState(state);
}
function openIndexer(token, state, out) {
if (state.inIndexer) {
throw Expections.nestedIndexers;
}
state.inIndexer = true;
state.indexer = [];
}
function closeIndexer(token, state, out) {
// must be within an indexer to close.
if (!state.inIndexer) {
throw Expections.closingWithoutOpeningIndexer;
}
// The quotes could be non terminating
if (state.quote) {
throw Expections.nonTerminatingQuotes;
}
// are we a range indexer?
if (state.range) {
closeRangedIndexer(token, state, out);
}
// are we have a token?
else if (state.indexerToken !== undefined) {
pushTokenIntoIndexer(token, state, out);
}
// empty indexer. Must be after the potential addition
// statements.
if (state.indexer && state.indexer.length === 0) {
throw Expections.emptyIndexer;
}
// flatten to avoid odd JSON output.
if (state.indexer && state.indexer.length === 1) {
state.indexer = state.indexer[0];
}
out[out.length] = state.indexer;
// removes all indexer state
cleanIndexerRangeState(state);
cleanIndexerTokenState(state);
state.indexer =
state.inIndexer = undefined;
}
function closeRangedIndexer(token, state, out) {
state.indexer[state.indexer.length] = {
from: state.indexerToken,
to: state.rangeCloseToken - (state.exclusiveRange && 1 || 0)
};
cleanIndexerRangeState(state);
}
function cleanIndexerRangeState(state) {
state.inclusiveRange =
state.exclusiveRange =
state.range =
state.rangeCloseToken =
state.rangeCount = undefined;
}
// removes state associated with indexerTokenState.
function cleanIndexerTokenState(state) {
state.indexerToken =
state.indexerTokenQuoted = undefined;
}
function tokenInRange(token, state, out) {
token = +token;
if (isNaN(token)) {
throw Expections.numericRange;
}
state.rangeCloseToken = token;
}
function tokenInIndexer(token, state, out) {
// finish the range token.
if (state.range) {
tokenInRange(token, state, out);
}
// quote mode, accumulate tokens.
else if (state.quote) {
if (state.indexerToken === undefined) {
state.indexerToken = '';
}
state.indexerToken += token;
}
// We are in range mode.
else {
token = +token;
if (isNaN(token)) {
throw Expections.tokensMustBeNumeric;
}
state.indexerToken = token;
}
}
// this function just ensures that quotes only happen in indexers,
// outside of ranges, and with 1 or more length tokens.
function quote(token, state, out) {
if (state.indexerTokenQuoted) {
throw Expections.indexerTokensMustBeCommaDelimited;
}
if (!state.inIndexer) {
throw Expections.quotesOutsideIndexer;
}
var was = state.quote;
var toBe = !was;
state.quote = toBe;
// so deep
if (was && !toBe) {
if (state.indexerToken === undefined) {
throw Expections.emptyQuotes;
}
state.indexerTokenQuoted = true;
}
}
},{"./TokenTypes":14,"./expections":15,"./tokenizer":17}],17:[function(_dereq_,module,exports){
var TokenTypes = _dereq_('./TokenTypes');
var DOT_SEPARATOR = '.';
var COMMA_SEPARATOR = ',';
var OPENING_BRACKET = '[';
var CLOSING_BRACKET = ']';
var DOUBLE_OUOTES = '"';
var SINGE_OUOTES = "'";
var SPACE = " ";
var SPECIAL_CHARACTERS = '\'"[]., ';
var TokenTypes = _dereq_('./TokenTypes');
module.exports = function tokenizer(string) {
var idx = -1;
return function() {
var token = '';
var done;
do {
done = idx === string.length;
if (done) {
return {done: true};
}
// we have to peek at the next token
var character = string[idx + 1];
// if its not a special character we need to accumulate it.
var isQuote = character === SINGE_OUOTES ||
character === DOUBLE_OUOTES;
if (character !== undefined &&
SPECIAL_CHARACTERS.indexOf(character) === -1) {
token += character;
++idx;
continue;
}
if (token.length) {
return toOutput(token, TokenTypes.token, done);
}
++idx;
var type;
switch (character) {
case DOT_SEPARATOR:
type = TokenTypes.dotSeparator;
break;
case COMMA_SEPARATOR:
type = TokenTypes.commaSeparator;
break;
case OPENING_BRACKET:
type = TokenTypes.openingBracket;
break;
case CLOSING_BRACKET:
type = TokenTypes.closingBracket;
break;
case SPACE:
type = TokenTypes.space;
break;
case DOUBLE_OUOTES:
case SINGE_OUOTES:
type = TokenTypes.quote;
break;
}
if (type) {
return toOutput(token, type, done);
}
} while (!done);
if (token.length) {
return toOutput(token, TokenTypes.token, false);
}
return {done: true};
};
};
function toOutput(token, type, done) {
return {
token: token,
done: done,
type: type
};
}
},{"./TokenTypes":14}],18:[function(_dereq_,module,exports){
var setSeedsOrOnNext = _dereq_('./support/setSeedsOrOnNext');
var onNextValues = _dereq_('./support/onNextValue');
var onCompletedOrError = _dereq_('./support/onCompletedOrError');
var dotSyntaxParser = _dereq_('./parser/parser');
var primeSeeds = _dereq_('./support/primeSeeds');
var autoFalse = function() { return false; };
module.exports = request;
function request(initialArgs, sourceRequest, processOperations, shouldRequestFn) {
if (!shouldRequestFn) {
shouldRequestFn = autoFalse;
}
return function innerRequest(options) {
var selector = options.operationSelector;
var model = options.operationModel;
var args = options.operationArgs;
var onNext = options.onNext.bind(options);
var onError = options.onError.bind(options);
var onCompleted = options.onCompleted.bind(options);
var isProgressive = options.operationIsProgressive;
var errorSelector = model._errorSelector;
var selectorLength = selector && selector.length || 0;
// State variables
var errors = [];
var format = options.format = selector && 'AsJSON' ||
options.format || 'AsPathMap';
var toJSONG = format === 'AsJSONG';
var toJSON = format === 'AsPathMap';
var toPathValues = format === 'AsValues';
var seedRequired = toJSON || toJSONG || selector;
var boundPath = model._path;
var i, len;
var foundValue = false;
var seeds = primeSeeds(selector, selectorLength);
var loopCount = 0;
// parse any dotSyntax
for (i = 0, len = args.length; i < len; i++) {
// it is a dotSyntax string.
if (typeof args[i] === 'string') {
args[i] = dotSyntaxParser(args[i]);
}
// it is a pathValue with dotSyntax.
else if (typeof args[i].path === 'string') {
args[i].path = dotSyntaxParser(args[i].path);
}
}
function recurse(operations, opts) {
if (loopCount > 50) {
throw 'Loop Kill switch thrown.';
}
var combinedResults = processOperations(
model,
operations,
errorSelector,
opts);
foundValue = foundValue || combinedResults.valuesReceived;
if (combinedResults.errors.length) {
errors = errors.concat(combinedResults.errors);
}
// if in progressiveMode, values are emitted
// each time through the recurse loop. This may have
// to change when the router is considered.
if (isProgressive && !toPathValues) {
onNextValues(model, onNext, seeds, selector);
}
// Performs the recursing via dataSource
if (shouldRequestFn(model, combinedResults, loopCount)) {
sourceRequest(
options,
onNext,
seeds,
combinedResults,
opts,
function onCompleteFromSourceSet(err, results) {
if (err) {
errors = errors.concat(err);
recurse([], seeds);
return;
}
++loopCount;
// We continue to string the opts through
recurse(results, opts);
});
}
// Else we need to onNext values and complete/error.
else {
if (!toPathValues && !isProgressive && foundValue) {
onNextValues(model, onNext, seeds, selector);
}
onCompletedOrError(onCompleted, onError, errors);
}
}
try {
recurse.apply(null,
initialArgs(options, seeds, onNext));
} catch(e) {
errors = [e];
onCompletedOrError(onCompleted, onError, errors);
}
};
}
},{"./parser/parser":16,"./support/onCompletedOrError":32,"./support/onNextValue":33,"./support/primeSeeds":35,"./support/setSeedsOrOnNext":39}],19:[function(_dereq_,module,exports){
var setInitialArgs = _dereq_('./setInitialArgs');
var setSourceRequest = _dereq_('./setSourceRequest');
var request = _dereq_('./../request');
var setProcessOperations = _dereq_('./setProcessOperations');
var shouldRequest = _dereq_('./shouldRequest');
var set = request(
setInitialArgs,
setSourceRequest,
setProcessOperations,
shouldRequest);
module.exports = set;
},{"./../request":18,"./setInitialArgs":20,"./setProcessOperations":21,"./setSourceRequest":22,"./shouldRequest":23}],20:[function(_dereq_,module,exports){
var combineOperations = _dereq_('./../support/combineOperations');
var setSeedsOrOnNext = _dereq_('./../support/setSeedsOrOnNext');
var Formats = _dereq_('./../support/Formats');
var toPathValues = Formats.toPathValues;
var toJSONG = Formats.toJSONG;
module.exports = function setInitialArgs(options, seeds, onNext) {
var isPathValues = options.format === toPathValues;
var seedRequired = !isPathValues;
var shouldRequest = !!options.operationModel._dataSource;
var format = options.format;
var args = options.operationArgs;
var selector = options.operationSelector;
var isProgressive = options.operationIsProgressive;
var firstSeeds, operations;
var requestOptions = {
removeBoundPath: shouldRequest
};
// If Model is a slave, in shouldRequest mode,
// a single seed is required to accumulate the jsong results.
if (shouldRequest) {
operations =
combineOperations(args, toJSONG, 'set', selector, false);
firstSeeds = [{}];
setSeedsOrOnNext(
operations, true, firstSeeds, false, options.selector);
// we must keep track of the set seeds.
requestOptions.requestSeed = firstSeeds[0];
}
// This model is the master, therefore a regular set can be performed.
else {
firstSeeds = seeds;
operations = combineOperations(args, format, 'set');
setSeedsOrOnNext(
operations, seedRequired, seeds, onNext, options.operationSelector);
}
// We either have to construct the master operations if
// the ModelResponse is isProgressive
// the ModelResponse is toPathValues
// but luckily we can just perform a get for the progressive or
// toPathValues mode.
if (isProgressive || isPathValues) {
var getOps = combineOperations(
args, format, 'get', selector, true);
setSeedsOrOnNext(
getOps, seedRequired, seeds, onNext, options.operationSelector);
operations = operations.concat(getOps);
requestOptions.isProgressive = true;
}
return [operations, requestOptions];
};
},{"./../support/Formats":24,"./../support/combineOperations":26,"./../support/setSeedsOrOnNext":39}],21:[function(_dereq_,module,exports){
var processOperations = _dereq_('./../support/processOperations');
var combineOperations = _dereq_('./../support/combineOperations');
var mergeBoundPath = _dereq_('./../support/mergeBoundPath');
var Formats = _dereq_('./../support/Formats');
var toPathValues = Formats.toPathValues;
module.exports = setProcessOperations;
function setProcessOperations(model, operations, errorSelector, requestOptions) {
var boundPath = model._path;
var hasBoundPath = boundPath.length > 0;
var removeBoundPath = requestOptions && requestOptions.removeBoundPath;
var isProgressive = requestOptions && requestOptions.isProgressive;
var progressiveOperations;
// if in progressive mode, then the progressive operations
// need to be executed but the bound path must stay intact.
if (isProgressive && removeBoundPath && hasBoundPath) {
progressiveOperations = operations.filter(function(op) {
return op.isProgressive;
});
operations = operations.filter(function(op) {
return !op.isProgressive;
});
}
if (removeBoundPath && hasBoundPath) {
model._path = [];
// For every operations arguments, the bound path must be adjusted.
for (var i = 0, opLen = operations.length; i < opLen; i++) {
var args = operations[i].args;
for (var j = 0, argsLen = args.length; j < argsLen; j++) {
args[j] = mergeBoundPath(args[j], boundPath);
}
}
}
var results = processOperations(model, operations, errorSelector);
// Undo what we have done to the model's bound path.
if (removeBoundPath && hasBoundPath) {
model._path = boundPath;
}
// executes the progressive ops
if (progressiveOperations) {
processOperations(model, progressiveOperations, errorSelector);
}
return results;
}
},{"./../support/Formats":24,"./../support/combineOperations":26,"./../support/mergeBoundPath":31,"./../support/processOperations":36}],22:[function(_dereq_,module,exports){
var getSourceObserver = _dereq_('./../support/getSourceObserever');
var combineOperations = _dereq_('./../support/combineOperations');
var setSeedsOrOnNext = _dereq_('./../support/setSeedsOrOnNext');
var toPathValues = _dereq_('./../support/Formats').toPathValues;
module.exports = setSourceRequest;
function setSourceRequest(
options, onNext, seeds, combinedResults, requestOptions, cb) {
var model = options.operationModel;
var seedRequired = options.format !== toPathValues;
var requestSeed = requestOptions.requestSeed;
return model._request.set(
requestSeed,
getSourceObserver(
model,
requestSeed.paths,
function setSourceRequestCB(err, results) {
if (err) {
cb(err);
}
// Sets the results into the model.
model._setJSONGsAsJSON(model, [results], []);
// Gets the original paths / maps back out.
var operations = combineOperations(
options.operationArgs, options.format, 'get');
setSeedsOrOnNext(
operations, seedRequired,
seeds, onNext, options.operationSelector);
// unset the removeBoundPath.
requestOptions.removeBoundPath = false;
cb(null, operations);
}));
}
},{"./../support/Formats":24,"./../support/combineOperations":26,"./../support/getSourceObserever":27,"./../support/setSeedsOrOnNext":39}],23:[function(_dereq_,module,exports){
// Set differs from get in the sense that the first time through
// the recurse loop a server operation must be performed if it can be.
module.exports = function(model, combinedResults, loopCount) {
return model._dataSource && (
combinedResults.requestedMissingPaths.length > 0 ||
loopCount === 0);
};
},{}],24:[function(_dereq_,module,exports){
module.exports = {
toPathValues: 'AsValues',
toJSON: 'AsPathMap',
toJSONG: 'AsJSONG',
selector: 'AsJSON',
};
},{}],25:[function(_dereq_,module,exports){
module.exports = function buildJSONGOperation(format, seeds, jsongOp, seedOffset, onNext) {
return {
methodName: '_setJSONGs' + format,
format: format,
isValues: format === 'AsValues',
onNext: onNext,
seeds: seeds,
seedsOffset: seedOffset,
args: [jsongOp]
};
};
},{}],26:[function(_dereq_,module,exports){
var isSeedRequired = _dereq_('./seedRequired');
var isJSONG = _dereq_('./isJSONG');
var isPathOrPathValue = _dereq_('./isPathOrPathValue');
var Formats = _dereq_('./Formats');
var toSelector = Formats.selector;
module.exports = function combineOperations(args, format, name, spread, isProgressive) {
var seedRequired = isSeedRequired(format);
var isValues = !seedRequired;
var hasSelector = seedRequired && format === toSelector;
var seedsOffset = 0;
return args.
reduce(function(groups, argument) {
var group = groups[groups.length - 1];
var type = isPathOrPathValue(argument) ? "PathSets" :
isJSONG(argument) ? "JSONGs" : "PathMaps";
var groupType = group && group.type;
var methodName = '_' + name + type + format;
if (!groupType || type !== groupType || spread) {
group = {
methodName: methodName,
format: format,
operation: name,
isValues: isValues,
seeds: [],
onNext: null,
seedsOffset: seedsOffset,
isProgressive: isProgressive,
type: type,
args: []
};
groups.push(group);
}
if (hasSelector) {
++seedsOffset;
}
group.args.push(argument);
return groups;
}, []);
};
},{"./Formats":24,"./isJSONG":29,"./isPathOrPathValue":30,"./seedRequired":37}],27:[function(_dereq_,module,exports){
var insertErrors = _dereq_('./insertErrors.js');
/**
* creates the model source observer
* @param {Model} model
* @param {Array.<Array>} requestedMissingPaths
* @param {Function} cb
*/
function getSourceObserver(model, requestedMissingPaths, cb) {
var incomingValues;
return {
onNext: function(jsongEnvelop) {
incomingValues = {
jsong: jsongEnvelop.jsong,
paths: requestedMissingPaths
};
},
onError: function(err) {
cb(insertErrors(model, requestedMissingPaths, err));
},
onCompleted: function() {
cb(false, incomingValues);
}
};
}
module.exports = getSourceObserver;
},{"./insertErrors.js":28}],28:[function(_dereq_,module,exports){
/**
* will insert the error provided for every requestedPath.
* @param {Model} model
* @param {Array.<Array>} requestedPaths
* @param {Object} err
*/
module.exports = function insertErrors(model, requestedPaths, err) {
var out = model._setPathSetsAsJSON.apply(null, [model].concat(
requestedPaths.
reduce(function(acc, r) {
acc[0].push({
path: r,
value: err
});
return acc;
}, [[]]),
[],
model._errorSelector
));
return out.errors;
};
},{}],29:[function(_dereq_,module,exports){
module.exports = function isJSONG(x) {
return x.hasOwnProperty("jsong");
};
},{}],30:[function(_dereq_,module,exports){
module.exports = function isPathOrPathValue(x) {
return !!(Array.isArray(x)) || (
x.hasOwnProperty("path") && x.hasOwnProperty("value"));
};
},{}],31:[function(_dereq_,module,exports){
var isJSONG = _dereq_('./isJSONG');
var isPathValue = _dereq_('./isPathOrPathValue');
module.exports = mergeBoundPath;
function mergeBoundPath(arg, boundPath) {
return isJSONG(arg) && mergeBoundPathIntoJSONG(arg, boundPath) ||
isPathValue(arg) && mergeBoundPathIntoPathValue(arg, boundPath) ||
mergeBoundPathIntoJSON(arg, boundPath);
}
function mergeBoundPathIntoJSONG(jsongEnv, boundPath) {
var newJSONGEnv = {jsong: jsongEnv.jsong, paths: jsongEnv.paths};
if (boundPath.length) {
var paths = [];
for (i = 0, len = jsongEnv.paths.length; i < len; i++) {
paths[i] = boundPath.concat(jsongEnv.paths[i]);
}
newJSONGEnv.paths = paths;
}
return newJSONGEnv;
}
function mergeBoundPathIntoJSON(arg, boundPath) {
var newArg = arg;
if (boundPath.length) {
newArg = {};
for (var i = 0, len = boundPath.length - 1; i < len; i++) {
newArg[boundPath[i]] = {};
}
newArg[boundPath[i]] = arg;
}
return newArg;
}
function mergeBoundPathIntoPathValue(arg, boundPath) {
return {
path: boundPath.concat(arg.path),
value: arg.value
};
}
},{"./isJSONG":29,"./isPathOrPathValue":30}],32:[function(_dereq_,module,exports){
module.exports = function onCompletedOrError(onCompleted, onError, errors) {
if (errors.length) {
onError(errors);
} else {
onCompleted();
}
};
},{}],33:[function(_dereq_,module,exports){
/**
* will onNext the observer with the seeds provided.
* @param {Model} model
* @param {Function} onNext
* @param {Array.<Object>} seeds
* @param {Function} [selector]
*/
module.exports = function onNextValues(model, onNext, seeds, selector) {
var root = model._root;
root.allowSync = true;
if (selector) {
if (seeds.length) {
// they should be wrapped in json items
onNext(selector.apply(model, seeds.map(function(x, i) {
return x.json;
})));
} else {
onNext(selector.call(model));
}
} else {
// this means there is an onNext function that is not AsValues or progressive,
// therefore there must only be one onNext call, which should only be the 0
// index of the values of the array
onNext(seeds[0]);
}
root.allowSync = false;
};
},{}],34:[function(_dereq_,module,exports){
var buildJSONGOperation = _dereq_('./buildJSONGOperation');
/**
* It performs the opposite of combine operations. It will take a JSONG
* response and partition them into the required amount of operations.
* @param {{jsong: {}, paths:[]}} jsongResponse
*/
module.exports = partitionOperations;
function partitionOperations(
jsongResponse, seeds, format, onNext) {
var partitionedOps = [];
var requestedMissingPaths = jsongResponse.paths;
if (format === 'AsJSON') {
// fast collapse ass the requestedMissingPaths into their
// respective groups
var opsFromRequestedMissingPaths = [];
var op = null;
for (var i = 0, len = requestedMissingPaths.length; i < len; i++) {
var missingPath = requestedMissingPaths[i];
if (!op || op.idx !== missingPath.pathSetIndex) {
op = {
idx: missingPath.pathSetIndex,
paths: []
};
opsFromRequestedMissingPaths.push(op);
}
op.paths.push(missingPath);
}
opsFromRequestedMissingPaths.forEach(function(op, i) {
var seed = [seeds[op.idx]];
var jsong = {
jsong: jsongResponse.jsong,
paths: op.paths
};
partitionedOps.push(buildJSONGOperation(
format,
seed,
jsong,
op.idx,
onNext));
});
} else {
partitionedOps[0] = buildJSONGOperation(format, seeds, jsongResponse, 0, onNext);
}
return partitionedOps;
}
},{"./buildJSONGOperation":25}],35:[function(_dereq_,module,exports){
module.exports = function primeSeeds(selector, selectorLength) {
var seeds = [];
if (selector) {
for (i = 0; i < selectorLength; i++) {
seeds.push({});
}
} else {
seeds[0] = {};
}
return seeds;
};
},{}],36:[function(_dereq_,module,exports){
module.exports = function processOperations(model, operations, errorSelector, boundPath) {
return operations.reduce(function(memo, operation) {
var jsonGraphOperation = model[operation.methodName];
var seedsOrFunction = operation.isValues ?
operation.onNext : operation.seeds;
var results = jsonGraphOperation(
model,
operation.args,
seedsOrFunction,
operation.onNext,
errorSelector,
boundPath);
var missing = results.requestedMissingPaths;
var offset = operation.seedsOffset;
for (var i = 0, len = missing.length; i < len; i++) {
missing[i].boundPath = boundPath;
missing[i].pathSetIndex += offset;
}
memo.requestedMissingPaths = memo.requestedMissingPaths.concat(missing);
memo.optimizedMissingPaths = memo.optimizedMissingPaths.concat(results.optimizedMissingPaths);
memo.errors = memo.errors.concat(results.errors);
memo.valuesReceived = memo.valuesReceived || results.requestedPaths.length > 0;
return memo;
}, {
errors: [],
requestedMissingPaths: [],
optimizedMissingPaths: [],
valuesReceived: false
});
}
},{}],37:[function(_dereq_,module,exports){
module.exports = function isSeedRequired(format) {
return format === 'AsJSON' || format === 'AsJSONG' || format === 'AsPathMap';
};
},{}],38:[function(_dereq_,module,exports){
module.exports = function setSeedsOnGroups(groups, seeds, hasSelector) {
var valueIndex = 0;
var seedsLength = seeds.length;
var j, i, len = groups.length, gLen, group;
if (hasSelector) {
for (i = 0; i < len && valueIndex < seedsLength; i++) {
group = groups[i];
gLen = gLen = group.args.length;
for (j = 0; j < gLen && valueIndex < seedsLength; j++, valueIndex++) {
group.seeds.push(seeds[valueIndex]);
}
}
} else {
for (i = 0; i < len && valueIndex < seedsLength; i++) {
groups[i].seeds = seeds;
}
}
}
},{}],39:[function(_dereq_,module,exports){
var setSeedsOnGroups = _dereq_('./setSeedsOnGroups');
module.exports = function setSeedsOrOnNext(operations, seedRequired, seeds, onNext, selector) {
if (seedRequired) {
setSeedsOnGroups(operations, seeds, selector);
} else {
for (i = 0; i < operations.length; i++) {
operations[i].onNext = onNext;
}
}
};
},{"./setSeedsOnGroups":38}],40:[function(_dereq_,module,exports){
var falcor = _dereq_('./../Falcor');
var NOOP = falcor.NOOP;
var RequestQueue = function(jsongModel, scheduler) {
this._scheduler = scheduler;
this._jsongModel = jsongModel;
this._scheduled = false;
this._requests = [];
};
RequestQueue.prototype = {
_get: function() {
var i = -1;
var requests = this._requests;
while (++i < requests.length) {
if (!requests[i].pending && requests[i].isGet) {
return requests[i];
}
}
return requests[requests.length] = new GetRequest(this._jsongModel, this);
},
_set: function() {
var i = -1;
var requests = this._requests;
// TODO: Set always sends off a request immediately, so there is no batching.
while (++i < requests.length) {
if (!requests[i].pending && requests[i].isSet) {
return requests[i];
}
}
return requests[requests.length] = new SetRequest(this._jsongModel, this);
},
remove: function(request) {
for (var i = this._requests.length - 1; i > -1; i--) {
if (this._requests[i].id === request.id && this._requests.splice(i, 1)) {
break;
}
}
},
set: function(jsongEnv, observer) {
var self = this;
var disposable = self._set().batch(jsongEnv, observer).flush();
return {
dispose: function() {
disposable.dispose();
}
};
},
get: function(requestedPaths, optimizedPaths, observer) {
var self = this;
var disposable = null;
// TODO: get does not batch across requests.
self._get().batch(requestedPaths, optimizedPaths, observer);
if (!self._scheduled) {
self._scheduled = true;
disposable = self._scheduler.schedule(self._flush.bind(self));
}
return {
dispose: function() {
disposable.dispose();
}
};
},
_flush: function() {
this._scheduled = false;
var requests = this._requests, i = -1;
var disposables = [];
while (++i < requests.length) {
if (!requests[i].pending) {
disposables[disposables.length] = requests[i].flush();
}
}
return {
dispose: function() {
disposables.forEach(function(d) { d.dispose(); });
}
};
}
};
var REQUEST_ID = 0;
var SetRequest = function(model, queue) {
var self = this;
self._jsongModel = model;
self._queue = queue;
self.observers = [];
self.jsongEnvs = [];
self.pending = false;
self.id = ++REQUEST_ID;
self.isSet = true;
};
SetRequest.prototype = {
batch: function(jsongEnv, observer) {
var self = this;
observer.onNext = observer.onNext || NOOP;
observer.onError = observer.onError || NOOP;
observer.onCompleted = observer.onCompleted || NOOP;
if (!observer.__observerId) {
observer.__observerId = ++REQUEST_ID;
}
observer._requestId = self.id;
self.observers[self.observers.length] = observer;
self.jsongEnvs[self.jsongEnvs.length] = jsongEnv;
return self;
},
flush: function() {
var incomingValues, query, op, len;
var self = this;
var jsongs = self.jsongEnvs;
var observers = self.observers;
var model = self._jsongModel;
self.pending = true;
// TODO: Set does not batch.
return model._dataSource.
set(jsongs[0]).
subscribe(function(response) {
incomingValues = response;
}, function(err) {
var i = -1;
var n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onError && obs.onError(err);
}
}, function() {
var i, n, obs;
self._queue.remove(self);
i = -1;
n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onNext && obs.onNext({
jsong: incomingValues.jsong || incomingValues.value,
paths: incomingValues.paths
});
obs.onCompleted && obs.onCompleted();
}
});
}
};
var GetRequest = function(jsongModel, queue) {
var self = this;
self._jsongModel = jsongModel;
self._queue = queue;
self.observers = [];
self.optimizedPaths = [];
self.requestedPaths = [];
self.pending = false;
self.id = ++REQUEST_ID;
self.isGet = true;
};
GetRequest.prototype = {
batch: function(requestedPaths, optimizedPaths, observer) {
// TODO: Do we need to gap fill?
var self = this;
observer.onNext = observer.onNext || NOOP;
observer.onError = observer.onError || NOOP;
observer.onCompleted = observer.onCompleted || NOOP;
if (!observer.__observerId) {
observer.__observerId = ++REQUEST_ID;
}
observer._requestId = self.id;
self.observers[self.observers.length] = observer;
self.optimizedPaths[self.optimizedPaths.length] = optimizedPaths;
self.requestedPaths[self.requestedPaths.length] = requestedPaths;
return self;
},
flush: function() {
var incomingValues, query, op, len;
var self = this;
var requested = self.requestedPaths;
var optimized = self.optimizedPaths;
var observers = self.observers;
var disposables = [];
var results = [];
var model = self._jsongModel;
self._scheduled = false;
self.pending = true;
var optimizedMaps = {};
var requestedMaps = {};
var r, o, i, j, obs, resultIndex;
for (i = 0, len = requested.length; i < len; i++) {
r = requested[i];
o = optimized[i];
obs = observers[i];
for (j = 0; j < r.length; j++) {
pathsToMapWithObservers(r[j], 0, readyNode(requestedMaps, null, obs), obs);
pathsToMapWithObservers(o[j], 0, readyNode(optimizedMaps, null, obs), obs);
}
}
return model._dataSource.
get(collapse(optimizedMaps)).
subscribe(function(response) {
incomingValues = response;
}, function(err) {
var i = -1;
var n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onError && obs.onError(err);
}
}, function() {
var i, n, obs;
self._queue.remove(self);
i = -1;
n = observers.length;
while (++i < n) {
obs = observers[i];
obs.onNext && obs.onNext({
jsong: incomingValues.jsong || incomingValues.value,
paths: incomingValues.paths
});
obs.onCompleted && obs.onCompleted();
}
});
},
// Returns the paths that are contained within this request.
contains: function(requestedPaths, optimizedPaths) {
// TODO:
}
};
function pathsToMapWithObservers(path, idx, branch, observer) {
var curr = path[idx];
// Object / Array
if (typeof curr === 'object') {
if (Array.isArray(curr)) {
curr.forEach(function(v) {
readyNode(branch, v, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[v], observer);
}
});
} else {
var from = curr.from || 0;
var to = curr.to >= 0 ? curr.to : curr.length;
for (var i = from; i <= to; i++) {
readyNode(branch, i, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[i], observer);
}
}
}
} else {
readyNode(branch, curr, observer);
if (path.length > idx + 1) {
pathsToMapWithObservers(path, idx + 1, branch[curr], observer);
}
}
}
/**
* Builds the set of collapsed
* queries by traversing the tree
* once
*/
var charPattern = /\D/i;
function readyNode(branch, key, observer) {
if (key === null) {
branch.__observers = branch.__observers || [];
!containsObserver(branch.__observers, observer) && branch.__observers.push(observer);
return branch;
}
if (!branch[key]) {
branch[key] = {__observers: []};
}
!containsObserver(branch[key].__observers, observer) && branch[key].__observers.push(observer);
return branch;
}
function containsObserver(observers, observer) {
if (!observer) {
return;
}
return observers.reduce(function(acc, x) {
return acc || x.__observerId === observer.__observerId;
}, false);
}
function collapse(pathMap) {
return rangeCollapse(buildQueries(pathMap));
}
/**
* Collapse ranges, e.g. when there is a continuous range
* in an array, turn it into an object instead
*
* [1,2,3,4,5,6] => {"from":1, "to":6}
*
*/
function rangeCollapse(paths) {
paths.forEach(function (path) {
path.forEach(function (elt, index) {
var range;
if (Array.isArray(elt) && elt.every(isNumber) && allUnique(elt)) {
elt.sort(function(a, b) {
return a - b;
});
if (elt[elt.length-1] - elt[0] === elt.length-1) {
// create range
range = {};
range.from = elt[0];
range.to = elt[elt.length-1];
path[index] = range;
}
}
});
});
return paths;
}
/* jshint forin: false */
function buildQueries(root) {
if (root == null || typeof root !== 'object') {
return [ [] ];
}
var children = Object.keys(root).filter(notPathMapInternalKeys),
child, memo, paths, key, childIsNum,
list, head, tail, clone, results,
i = -1, n = children.length,
j, k, x;
if (n === 0 || Array.isArray(root) === true) {
return [ [] ];
}
memo = {};
while(++i < n) {
child = children[i];
paths = buildQueries(root[child]);
key = createKey(paths);
childIsNum = typeof child === 'string' && !charPattern.test(child);
if ((list = memo[key]) && (head = list.head)) {
head[head.length] = childIsNum ? parseInt(child, 10) : child;
} else {
memo[key] = {
head: [childIsNum ? parseInt(child, 10) : child],
tail: paths
};
}
}
results = [];
for(x in memo) {
head = (list = memo[x]).head;
tail = list.tail;
i = -1;
n = tail.length;
while(++i < n) {
list = tail[i];
j = -1;
k = list.length;
if(head[0] === '') {
clone = [];
} else {
clone = [head.length === 1 ? head[0] : head];
while(++j < k) {
clone[j + 1] = list[j];
}
}
results[results.length] = clone;
}
}
return results;
}
function notPathMapInternalKeys(key) {
return (
key !== "__observers" &&
key !== "__pending" &&
key !== "__batchID"
);
}
/**
* Return true if argument is a number
*/
function isNumber(val) {
return typeof val === "number";
}
/**
* allUnique
* return true if every number in an array is unique
*/
function allUnique(arr) {
var hash = {},
index,
len;
for (index = 0, len = arr.length; index < len; index++) {
if (hash[arr[index]]) {
return false;
}
hash[arr[index]] = true;
}
return true;
}
/**
* Sort a list-of-lists
* Used for generating a unique hash
* key for each subtree; used by the
* memoization
*/
function sortLol(lol) {
return lol.reduce(function (result, curr) {
if (curr instanceof Array) {
result.push(sortLol(curr).slice(0).sort());
return result;
}
return result.concat(curr);
}, []).slice(0).sort();
}
/**
* Create a unique hash key for a set
* of paths
*/
function createKey(list) {
return JSON.stringify(sortLol(list));
}
// Note: For testing
falcor.__Internals.buildQueries = buildQueries;
module.exports = RequestQueue;
},{"./../Falcor":2}],41:[function(_dereq_,module,exports){
(function (global){
/**
Rx Ultralite!
Rx on the Roku Tyler throws this (possibly related to browserify-ing Rx):
Error: 'TypeError: 'undefined' is not a function (evaluating 'root.document.createElement('script')')'
*/
var Rx;
if (typeof window !== "undefined" && typeof window["Rx"] !== "undefined") {
// Browser environment
Rx = window["Rx"];
} else if (typeof global !== "undefined" && typeof global["Rx"] !== "undefined") {
// Node.js environment
Rx = global["Rx"];
} else if (typeof _dereq_ !== 'undefined' || typeof window !== 'undefined' && window.require) {
var r = typeof _dereq_ !== 'undefined' && _dereq_ || window.require;
try {
// CommonJS environment with rx module
Rx = r("rx");
} catch(e) {
Rx = undefined;
}
}
if(Rx === undefined) {
Rx = {
I: function() { return arguments[0]; },
Disposable: (function() {
function Disposable(a) {
this.action = a;
}
Disposable.create = function(a) {
return new Disposable(a);
};
Disposable.empty = new Disposable(function(){});
Disposable.prototype.dispose = function() {
if(typeof this.action === 'function') {
this.action();
}
};
return Disposable;
})(),
Observable: (function() {
function Observable(s) {
this._subscribe = s;
}
Observable.create = Observable.createWithDisposable = function(s) {
return new Observable(s);
};
Observable.fastCreateWithDisposable = Observable.create;
Observable.fastReturnValue = function(value) {
return Observable.create(function(observer) {
observer.onNext(value);
observer.onCompleted();
});
};
// NOTE: Required for Router
Observable.prototype.from;
Observable.prototype.materialize;
Observable.prototype.reduce;
Observable.of = function() {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return Observable.create(function(observer) {
var errorOcurred = false;
try {
for(var i = 0; i < len; ++i) {
observer.onNext(args[i]);
}
} catch(e) {
errorOcurred = true;
observer.onError(e);
}
if(errorOcurred !== true) {
observer.onCompleted();
}
});
}
Observable.prototype.subscribe = function(n, e, c) {
return this._subscribe(
(n != null && typeof n === 'object') ?
n :
Rx.Observer.create(n, e, c)
);
};
Observable.prototype.forEach = Observable.prototype.subscribe;
Observable.prototype.catchException = function(next) {
var self = this;
return Observable.create(function(o) {
return self.subscribe(
function(x) { o.onNext(x); },
function(e) {
return (
(typeof next === 'function') ?
next(e) : next
).subscribe(o);
},
function() { o.onCompleted(); });
});
};
return Observable;
})(),
Observer: (function() {
function Observer(n, e, c) {
this.onNext = n || Rx.I;
this.onError = e || Rx.I;
this.onCompleted = c || Rx.I;
}
Observer.create = function(n, e, c) {
return new Observer(n, e, c);
};
return Observer;
})(),
Subject: (function(){
function Subject() {
this.observers = [];
}
Subject.prototype.subscribe = function(subscriber) {
var a = this.observers,
n = a.length;
a[n] = subscriber;
return {
dispose: function() {
a.splice(n, 1);
}
}
};
Subject.prototype.onNext = function(x) {
var listeners = this.observers.concat(),
i = -1, n = listeners.length;
while(++i < n) {
listeners[i].onNext(x);
}
};
Subject.prototype.onError = function(e) {
var listeners = this.observers.concat(),
i = -1, n = listeners.length;
this.observers.length = 0;
while(++i < n) {
listeners[i].onError(e);
}
};
Subject.prototype.onCompleted = function() {
var listeners = this.observers.concat(),
i = -1, n = listeners.length;
this.observers.length = 0;
while(++i < n) {
listeners[i].onCompleted();
}
};
})()
};
}
module.exports = Rx;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],42:[function(_dereq_,module,exports){
function ImmediateScheduler() {
}
ImmediateScheduler.prototype = {
schedule: function(action) {
action();
}
};
module.exports = ImmediateScheduler;
},{}],43:[function(_dereq_,module,exports){
function TimeoutScheduler(delay) {
this.delay = delay;
}
TimeoutScheduler.prototype = {
schedule: function(action) {
setTimeout(action, this.delay);
}
};
module.exports = TimeoutScheduler;
},{}],44:[function(_dereq_,module,exports){
var hardLink = _dereq_('./util/hardlink');
var createHardlink = hardLink.create;
var onValue = _dereq_('./onValue');
var isExpired = _dereq_('./util/isExpired');
var $path = _dereq_('./../types/path.js');
var __context = _dereq_("../internal/context");
function followReference(model, root, node, referenceContainer, reference, seed, outputFormat) {
var depth = 0;
var k, next;
while (true) {
if (depth === 0 && referenceContainer[__context]) {
depth = reference.length;
next = referenceContainer[__context];
} else {
k = reference[depth++];
next = node[k];
}
if (next) {
var type = next.$type;
var value = type && next.value || next;
if (depth < reference.length) {
if (type) {
node = next;
break;
}
node = next;
continue;
}
// We need to report a value or follow another reference.
else {
node = next;
if (type && isExpired(next)) {
break;
}
if (!referenceContainer[__context]) {
createHardlink(referenceContainer, next);
}
// Restart the reference follower.
if (type === $path) {
if (outputFormat === 'JSONG') {
onValue(model, next, seed, null, null, reference, null, outputFormat);
}
depth = 0;
reference = value;
referenceContainer = next;
node = root;
continue;
}
break;
}
} else {
node = undefined;
}
break;
}
if (depth < reference.length) {
var ref = [];
for (var i = 0; i < depth; i++) {
ref[i] = reference[i];
}
reference = ref;
}
return [node, reference];
}
module.exports = followReference;
},{"../internal/context":66,"./../types/path.js":140,"./onValue":56,"./util/hardlink":58,"./util/isExpired":59}],45:[function(_dereq_,module,exports){
var getBoundValue = _dereq_('./getBoundValue');
var isPathValue = _dereq_('./util/isPathValue');
module.exports = function(walk) {
return function getAsJSON(model, paths, values) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var requestedMissingPaths = results.requestedMissingPaths;
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var missingIdx = 0;
var boundOptimizedPath, optimizedPath;
var i, j, len, bLen;
results.values = values;
if (!values) {
values = [];
}
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (i = 0, len = paths.length; i < len; i++) {
var valueNode = undefined;
var pathSet = paths[i];
if (values[i]) {
valueNode = values[i];
}
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[i] = boundOptimizedPath[i];
}
}
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, 'JSON');
if (missingIdx < requestedMissingPaths.length) {
for (j = missingIdx, length = requestedMissingPaths.length; j < length; j++) {
requestedMissingPaths[j].pathSetIndex = i;
}
missingIdx = length;
}
}
return results;
};
};
},{"./getBoundValue":49,"./util/isPathValue":61}],46:[function(_dereq_,module,exports){
var getBoundValue = _dereq_('./getBoundValue');
var isPathValue = _dereq_('./util/isPathValue');
module.exports = function(walk) {
return function getAsJSONG(model, paths, values) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
results.values = values;
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
if (boundPath.length) {
throw 'It is not legal to use the JSON Graph format from a bound Model. JSON Graph format can only be used from a root model.';
} else {
currentCachePosition = cache;
}
for (var i = 0, len = paths.length; i < len; i++) {
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, values[0], [], results, [], [], inputFormat, 'JSONG');
}
return results;
};
};
},{"./getBoundValue":49,"./util/isPathValue":61}],47:[function(_dereq_,module,exports){
var getBoundValue = _dereq_('./getBoundValue');
var isPathValue = _dereq_('./util/isPathValue');
module.exports = function(walk) {
return function getAsPathMap(model, paths, values) {
var valueNode;
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
valueNode = values[0];
results.values = values;
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[i] = boundOptimizedPath[i];
}
}
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, 'PathMap');
}
return results;
};
};
},{"./getBoundValue":49,"./util/isPathValue":61}],48:[function(_dereq_,module,exports){
var getBoundValue = _dereq_('./getBoundValue');
var isPathValue = _dereq_('./util/isPathValue');
module.exports = function(walk) {
return function getAsValues(model, paths, onNext) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
'Paths' : 'JSON';
var cache = model._cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[i] = boundOptimizedPath[i];
}
}
var pathSet = paths[i];
if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, onNext, null, results, optimizedPath, [], inputFormat, 'Values');
}
return results;
};
};
},{"./getBoundValue":49,"./util/isPathValue":61}],49:[function(_dereq_,module,exports){
var getValueSync = _dereq_('./getValueSync');
module.exports = function getBoundValue(model, path) {
var boxed, value, shorted;
boxed = model._boxed;
model._boxed = true;
value = getValueSync(model, path.concat(null));
model._boxed = boxed;
path = value.optimizedPath;
shorted = value.shorted;
value = value.value;
while (path.length && path[path.length - 1] === null) {
path.pop();
}
return {
path: path,
value: value,
shorted: shorted
};
};
},{"./getValueSync":50}],50:[function(_dereq_,module,exports){
var followReference = _dereq_('./followReference');
var clone = _dereq_('./util/clone');
var isExpired = _dereq_('./util/isExpired');
var promote = _dereq_('./util/lru').promote;
var $path = _dereq_('./../types/path.js');
var $sentinel = _dereq_('./../types/sentinel.js');
var $error = _dereq_('./../types/error.js');
module.exports = function getValueSync(model, simplePath) {
var root = model._cache;
var len = simplePath.length;
var optimizedPath = [];
var shorted = false, shouldShort = false;
var depth = 0;
var key, next = root, type, curr = root, out, ref, refNode;
do {
key = simplePath[depth++];
if (key !== null) {
next = curr[key];
}
if (!next) {
out = undefined;
shorted = true;
break;
}
type = next.$type;
optimizedPath.push(key);
// Up to the last key we follow references
if (depth < len) {
if (type === $path) {
ref = followReference(model, root, root, next, next.value);
refNode = ref[0];
if (!refNode) {
out = undefined;
break;
}
type = refNode.$type;
next = refNode;
optimizedPath = ref[1];
}
if (type) {
break;
}
}
// If there is a value, then we have great success, else, report an undefined.
else {
out = next;
}
curr = next;
} while (next && depth < len);
if (depth < len) {
// Unfortunately, if all that follows are nulls, then we have not shorted.
for (;depth < len; ++depth) {
if (simplePath[depth] !== null) {
shouldShort = true;
break;
}
}
// if we should short or report value. Values are reported on nulls.
if (shouldShort) {
shorted = true;
out = undefined;
} else {
out = next;
}
}
// promotes if not expired
if (out) {
if (isExpired(out)) {
out = undefined;
} else {
promote(model, out);
}
}
if (out && out.$type === $error && !model._treatErrorsAsValues) {
throw {path: simplePath, value: out.value};
} else if (out && model._boxed) {
out = !!type ? clone(out) : out;
} else if (!out && model._materialized) {
out = {$type: $sentinel};
} else if (out) {
out = out.value;
}
return {
value: out,
shorted: shorted,
optimizedPath: optimizedPath
};
};
},{"./../types/error.js":139,"./../types/path.js":140,"./../types/sentinel.js":141,"./followReference":44,"./util/clone":57,"./util/isExpired":59,"./util/lru":62}],51:[function(_dereq_,module,exports){
var followReference = _dereq_('./followReference');
var onError = _dereq_('./onError');
var onMissing = _dereq_('./onMissing');
var onValue = _dereq_('./onValue');
var lru = _dereq_('./util/lru');
var hardLink = _dereq_('./util/hardlink');
var isMaterialized = _dereq_('./util/isMaterialzed');
var removeHardlink = hardLink.remove;
var splice = lru.splice;
var isExpired = _dereq_('./util/isExpired');
var permuteKey = _dereq_('./util/permuteKey');
var $path = _dereq_('./../types/path');
var $error = _dereq_('./../types/error');
var __invalidated = _dereq_("../internal/invalidated");
// TODO: Objectify?
function walk(model, root, curr, pathOrJSON, depth, seedOrFunction, positionalInfo, outerResults, optimizedPath, requestedPath, inputFormat, outputFormat, fromReference) {
if ((!curr || curr && curr.$type) &&
evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfo, outerResults, outputFormat, fromReference)) {
return;
}
// We continue the search to the end of the path/json structure.
else {
// Base case of the searching: Have we hit the end of the road?
// Paths
// 1) depth === path.length
// PathMaps (json input)
// 2) if its an object with no keys
// 3) its a non-object
var jsonQuery = inputFormat === 'JSON';
var atEndOfJSONQuery = false;
var k, i, len;
if (jsonQuery) {
// it has a $type property means we have hit a end.
if (pathOrJSON && pathOrJSON.$type) {
atEndOfJSONQuery = true;
}
// is it an object?
else if (pathOrJSON && typeof pathOrJSON === 'object') {
// A terminating condition
k = Object.keys(pathOrJSON);
if (k.length === 1) {
k = k[0];
}
}
// found a primitive, we hit the end.
else {
atEndOfJSONQuery = true;
}
} else {
k = pathOrJSON[depth];
}
// BaseCase: we have hit the end of our query without finding a 'leaf' node, therefore emit missing.
if (atEndOfJSONQuery || !jsonQuery && depth === pathOrJSON.length) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
return;
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
return;
}
var memo = {done: false};
var permutePosition = positionalInfo;
var permuteRequested = requestedPath;
var permuteOptimized = optimizedPath;
var asJSONG = outputFormat === 'JSONG';
var asJSON = outputFormat === 'JSON';
var isKeySet = false;
var hasChildren = false;
depth++;
var key;
if (k && typeof k === 'object') {
memo.isArray = Array.isArray(k);
memo.arrOffset = 0;
key = permuteKey(k, memo);
isKeySet = true;
} else {
key = k;
memo.done = true;
}
if (asJSON && isKeySet) {
permutePosition = [];
for (i = 0, len = positionalInfo.length; i < len; i++) {
permutePosition[i] = positionalInfo[i];
}
permutePosition.push(depth - 1);
}
do {
fromReference = false;
if (!memo.done) {
permuteOptimized = [];
permuteRequested = [];
for (i = 0, len = requestedPath.length; i < len; i++) {
permuteRequested[i] = requestedPath[i];
}
for (i = 0, len = optimizedPath.length; i < len; i++) {
permuteOptimized[i] = optimizedPath[i];
}
}
var nextPathOrPathMap = jsonQuery ? pathOrJSON[key] : pathOrJSON;
if (jsonQuery && nextPathOrPathMap) {
if (typeof nextPathOrPathMap === 'object') {
if (nextPathOrPathMap.$type) {
hasChildren = false;
} else {
hasChildren = Object.keys(nextPathOrPathMap).length > 0;
}
}
}
var next;
if (key === null || jsonQuery && key === '__null') {
next = curr;
} else {
next = curr[key];
permuteOptimized.push(key);
permuteRequested.push(key);
}
if (next) {
var nType = next.$type;
var value = nType && next.value || next;
if (jsonQuery && hasChildren || !jsonQuery && depth < pathOrJSON.length) {
if (nType && nType === $path && !isExpired(next)) {
if (asJSONG) {
onValue(model, next, seedOrFunction, outerResults, false, permuteOptimized, permutePosition, outputFormat);
}
var ref = followReference(model, root, root, next, value, seedOrFunction, outputFormat);
fromReference = true;
next = ref[0];
var refPath = ref[1];
permuteOptimized = [];
for (i = 0, len = refPath.length; i < len; i++) {
permuteOptimized[i] = refPath[i];
}
}
}
}
walk(model, root, next, nextPathOrPathMap, depth, seedOrFunction, permutePosition, outerResults, permuteOptimized, permuteRequested, inputFormat, outputFormat, fromReference);
if (!memo.done) {
key = permuteKey(k, memo);
}
} while (!memo.done);
}
}
function evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfo, outerResults, outputFormat, fromReference) {
// BaseCase: This position does not exist, emit missing.
if (!curr) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
}
return true;
}
var currType = curr.$type;
positionalInfo = positionalInfo || [];
// The Base Cases. There is a type, therefore we have hit a 'leaf' node.
if (currType === $error) {
if (fromReference) {
requestedPath.push(null);
}
if (outputFormat === 'JSONG' || model._treatErrorsAsValues) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onError(model, curr, requestedPath, optimizedPath, outerResults);
}
}
// Else we have found a value, emit the current position information.
else {
if (isExpired(curr)) {
if (!curr[__invalidated]) {
splice(model, curr);
removeHardlink(curr);
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
} else {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
}
}
return true;
}
module.exports = walk;
},{"../internal/invalidated":69,"./../types/error":139,"./../types/path":140,"./followReference":44,"./onError":54,"./onMissing":55,"./onValue":56,"./util/hardlink":58,"./util/isExpired":59,"./util/isMaterialzed":60,"./util/lru":62,"./util/permuteKey":63}],52:[function(_dereq_,module,exports){
var walk = _dereq_('./getWalk');
module.exports = {
getAsJSON: _dereq_('./getAsJSON')(walk),
getAsJSONG: _dereq_('./getAsJSONG')(walk),
getAsValues: _dereq_('./getAsValues')(walk),
getAsPathMap: _dereq_('./getAsPathMap')(walk),
getValueSync: _dereq_('./getValueSync'),
getBoundValue: _dereq_('./getBoundValue'),
setCache: _dereq_('./legacy_setCache')
};
},{"./getAsJSON":45,"./getAsJSONG":46,"./getAsPathMap":47,"./getAsValues":48,"./getBoundValue":49,"./getValueSync":50,"./getWalk":51,"./legacy_setCache":53}],53:[function(_dereq_,module,exports){
/* istanbul ignore next */
var NOOP = function NOOP() {},
__GENERATION_GUID = 0,
__GENERATION_VERSION = 0,
__CONTAINER = "__reference_container",
__CONTEXT = "__context",
__GENERATION = "__generation",
__GENERATION_UPDATED = "__generation_updated",
__INVALIDATED = "__invalidated",
__KEY = "__key",
__KEYS = "__keys",
__IS_KEY_SET = "__is_key_set",
__NULL = "__null",
__SELF = "./",
__PARENT = "../",
__REF = "__ref",
__REF_INDEX = "__ref_index",
__REFS_LENGTH = "__refs_length",
__ROOT = "/",
__OFFSET = "__offset",
__FALKOR_EMPTY_OBJECT = '__FALKOR_EMPTY_OBJECT',
__INTERNAL_KEYS = [
__CONTAINER, __CONTEXT, __GENERATION, __GENERATION_UPDATED,
__INVALIDATED, __KEY, __KEYS, __IS_KEY_SET, __NULL, __SELF,
__PARENT, __REF, __REF_INDEX, __REFS_LENGTH, __OFFSET, __ROOT
],
$TYPE = "$type",
$SIZE = "$size",
$EXPIRES = "$expires",
$TIMESTAMP = "$timestamp",
SENTINEL = "sentinel",
PATH = "ref",
ERROR = "error",
VALUE = "value",
EXPIRED = "expired",
LEAF = "leaf";
/* istanbul ignore next */
module.exports = function setCache(model, map) {
var root = model._root, expired = root.expired, depth = 0, height = 0, mapStack = [], nodes = [], nodeRoot = model._cache, nodeParent = nodeRoot, node = nodeParent, nodeType, nodeValue, nodeSize, nodeTimestamp, nodeExpires;
mapStack[0] = map;
nodes[-1] = nodeParent;
while (depth > -1) {
/* Walk Path Map */
var isTerminus = false, offset = 0, keys = void 0, index = void 0, key = void 0, isKeySet = false;
node = nodeParent = nodes[depth - 1];
depth = depth;
follow_path_map_9177:
do {
height = depth;
nodeType = node && node[$TYPE] || void 0;
nodeValue = nodeType === SENTINEL ? node[VALUE] : node;
if ((isTerminus = !((map = mapStack[offset = depth * 4]) != null && typeof map === 'object') || map[$TYPE] !== void 0 || Array.isArray(map) || !((keys = mapStack[offset + 1] || (mapStack[offset + 1] = Object.keys(map))) && ((index = mapStack[offset + 2] || (mapStack[offset + 2] = 0)) || true) && ((isKeySet = keys.length > 1) || keys.length > 0))) || (node == null || nodeType !== void 0 || typeof node !== 'object' || Array.isArray(nodeValue))) {
if ((nodeExpires = (node && node[$EXPIRES]) != null) && (nodeExpires !== 1 && (nodeExpires === 0 || nodeExpires < now())) || node != null && node[__INVALIDATED] === true) {
nodeType = void 0;
nodeValue = void 0;
node = (expired[expired.length] = node) && (node[__INVALIDATED] = true) && void 0;
}
if (!isTerminus && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue))) {
if (node == null || nodeType !== void 0 || typeof node !== 'object' || Array.isArray(nodeValue)) {
key = null;
node = node;
depth = depth;
continue follow_path_map_9177;
}
} else {
if (key != null) {
var newNode, sizeOffset, edgeSize = node && node[$SIZE] || 0;
nodeType = map && map[$TYPE] || void 0;
nV2 = nodeType ? map[VALUE] : void 0;
nodeValue = nodeType === SENTINEL ? map[VALUE] : map;
newNode = map;
if ((!nodeType || nodeType === SENTINEL || nodeType === PATH) && Array.isArray(nodeValue)) {
delete nodeValue[$SIZE];
// console.log(1);
if (nodeType) {
nodeSize = 50 + (nodeValue.length || 1);
} else {
nodeSize = nodeValue.length || 1;
}
newNode[$SIZE] = nodeSize;
nodeValue[__CONTAINER] = newNode;
} else if (nodeType === SENTINEL || nodeType === PATH) {
newNode[$SIZE] = nodeSize = 50 + (nV2 && typeof nV2.length === 'number' ? nV2.length : 1);
} else if (nodeType === ERROR) {
newNode[$SIZE] = nodeSize = map && map[$SIZE] || 0 || 50 + 1;
} else if (!(map != null && typeof map === 'object')) {
nodeSize = 50 + (typeof nodeValue === 'string' && nodeValue.length || 1);
nodeType = 'sentinel';
newNode = {};
newNode[VALUE] = nodeValue;
newNode[$TYPE] = nodeType;
newNode[$SIZE] = nodeSize;
} else {
nodeType = newNode[$TYPE] = nodeType || GROUP;
newNode[$SIZE] = nodeSize = map && map[$SIZE] || 0 || 50 + 1;
}
;
if (node !== newNode && (node != null && typeof node === 'object')) {
var nodeRefsLength = node[__REFS_LENGTH] || 0, destRefsLength = newNode[__REFS_LENGTH] || 0, i = -1, ref;
while (++i < nodeRefsLength) {
if ((ref = node[__REF + i]) !== void 0) {
ref[__CONTEXT] = newNode;
newNode[__REF + (destRefsLength + i)] = ref;
node[__REF + i] = void 0;
}
}
newNode[__REFS_LENGTH] = nodeRefsLength + destRefsLength;
node[__REFS_LENGTH] = ref = void 0;
var invParent = nodeParent, invChild = node, invKey = key, keys$2, index$2, offset$2, childType, childValue, isBranch, stack = [
nodeParent,
invKey,
node
], depth$2 = 0;
while (depth$2 > -1) {
nodeParent = stack[offset$2 = depth$2 * 8];
invKey = stack[offset$2 + 1];
node = stack[offset$2 + 2];
if ((childType = stack[offset$2 + 3]) === void 0 || (childType = void 0)) {
childType = stack[offset$2 + 3] = node && node[$TYPE] || void 0 || null;
}
childValue = stack[offset$2 + 4] || (stack[offset$2 + 4] = childType === SENTINEL ? node[VALUE] : node);
if ((isBranch = stack[offset$2 + 5]) === void 0) {
isBranch = stack[offset$2 + 5] = !childType && (node != null && typeof node === 'object') && !Array.isArray(childValue);
}
if (isBranch === true) {
if ((keys$2 = stack[offset$2 + 6]) === void 0) {
keys$2 = stack[offset$2 + 6] = [];
index$2 = -1;
for (var childKey in node) {
!(!(childKey[0] !== '_' || childKey[1] !== '_') || (childKey === __SELF || childKey === __PARENT || childKey === __ROOT) || childKey[0] === '$') && (keys$2[++index$2] = childKey);
}
}
index$2 = stack[offset$2 + 7] || (stack[offset$2 + 7] = 0);
if (index$2 < keys$2.length) {
stack[offset$2 + 7] = index$2 + 1;
stack[offset$2 = ++depth$2 * 8] = node;
stack[offset$2 + 1] = invKey = keys$2[index$2];
stack[offset$2 + 2] = node[invKey];
continue;
}
}
var ref$2 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination;
if (ref$2 && Array.isArray(ref$2)) {
destination = ref$2[__CONTEXT];
if (destination) {
var i$2 = (ref$2[__REF_INDEX] || 0) - 1, n = (destination[__REFS_LENGTH] || 0) - 1;
while (++i$2 <= n) {
destination[__REF + i$2] = destination[__REF + (i$2 + 1)];
}
destination[__REFS_LENGTH] = n;
ref$2[__REF_INDEX] = ref$2[__CONTEXT] = destination = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$3, i$3 = -1, n$2 = node[__REFS_LENGTH] || 0;
while (++i$3 < n$2) {
if ((ref$3 = node[__REF + i$3]) !== void 0) {
ref$3[__CONTEXT] = node[__REF + i$3] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$2 = root, head = root$2.__head, tail = root$2.__tail, next = node.__next, prev = node.__prev;
next != null && typeof next === 'object' && (next.__prev = prev);
prev != null && typeof prev === 'object' && (prev.__next = next);
node === head && (root$2.__head = root$2.__next = next);
node === tail && (root$2.__tail = root$2.__prev = prev);
node.__next = node.__prev = void 0;
head = tail = next = prev = void 0;
;
nodeParent[invKey] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
;
delete stack[offset$2 + 0];
delete stack[offset$2 + 1];
delete stack[offset$2 + 2];
delete stack[offset$2 + 3];
delete stack[offset$2 + 4];
delete stack[offset$2 + 5];
delete stack[offset$2 + 6];
delete stack[offset$2 + 7];
--depth$2;
}
nodeParent = invParent;
node = invChild;
}
nodeParent[key] = node = newNode;
nodeType = node && node[$TYPE] || void 0;
node = !node[__SELF] && ((node[__SELF] = node) || true) && ((node[__KEY] = key) || true) && ((node[__PARENT] = nodeParent) || true) && ((node[__ROOT] = nodeRoot) || true) && (node[__GENERATION] || (node[__GENERATION] = ++__GENERATION_GUID) && node) && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue) && (nodeValue[__CONTAINER] = node)) || node;
sizeOffset = edgeSize - nodeSize;
var self = nodeParent, child = node;
while (node = nodeParent) {
nodeParent = node[__PARENT];
if ((node[$SIZE] = (node[$SIZE] || 0) - sizeOffset) <= 0 && nodeParent) {
var ref$4 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination$2;
if (ref$4 && Array.isArray(ref$4)) {
destination$2 = ref$4[__CONTEXT];
if (destination$2) {
var i$4 = (ref$4[__REF_INDEX] || 0) - 1, n$3 = (destination$2[__REFS_LENGTH] || 0) - 1;
while (++i$4 <= n$3) {
destination$2[__REF + i$4] = destination$2[__REF + (i$4 + 1)];
}
destination$2[__REFS_LENGTH] = n$3;
ref$4[__REF_INDEX] = ref$4[__CONTEXT] = destination$2 = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$5, i$5 = -1, n$4 = node[__REFS_LENGTH] || 0;
while (++i$5 < n$4) {
if ((ref$5 = node[__REF + i$5]) !== void 0) {
ref$5[__CONTEXT] = node[__REF + i$5] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$3 = root, head$2 = root$3.__head, tail$2 = root$3.__tail, next$2 = node.__next, prev$2 = node.__prev;
next$2 != null && typeof next$2 === 'object' && (next$2.__prev = prev$2);
prev$2 != null && typeof prev$2 === 'object' && (prev$2.__next = next$2);
node === head$2 && (root$3.__head = root$3.__next = next$2);
node === tail$2 && (root$3.__tail = root$3.__prev = prev$2);
node.__next = node.__prev = void 0;
head$2 = tail$2 = next$2 = prev$2 = void 0;
;
nodeParent[node[__KEY]] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
} else if (node[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
var self$2 = node, stack$2 = [], depth$3 = 0, linkPaths, ref$6, i$6, k, n$5;
while (depth$3 > -1) {
if ((linkPaths = stack$2[depth$3]) === void 0) {
i$6 = k = -1;
n$5 = node[__REFS_LENGTH] || 0;
node[__GENERATION_UPDATED] = __GENERATION_VERSION;
node[__GENERATION] = ++__GENERATION_GUID;
if ((ref$6 = node[__PARENT]) !== void 0 && ref$6[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
stack$2[depth$3] = linkPaths = new Array(n$5 + 1);
linkPaths[++k] = ref$6;
} else if (n$5 > 0) {
stack$2[depth$3] = linkPaths = new Array(n$5);
}
while (++i$6 < n$5) {
if ((ref$6 = node[__REF + i$6]) !== void 0 && ref$6[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
linkPaths[++k] = ref$6;
}
}
}
if ((node = linkPaths && linkPaths.pop()) !== void 0) {
++depth$3;
} else {
stack$2[depth$3--] = void 0;
}
}
node = self$2;
}
}
nodeParent = self;
node = child;
}
;
node = node;
break follow_path_map_9177;
}
}
if ((key = keys[index]) == null) {
node = node;
break follow_path_map_9177;
} else if (key === __NULL && ((key = null) || true) || !(!(key[0] !== '_' || key[1] !== '_') || (key === __SELF || key === __PARENT || key === __ROOT) || key[0] === '$') && ((mapStack[(depth + 1) * 4] = map[key]) || true)) {
mapStack[(depth + 1) * 4 + 3] = key;
} else {
mapStack[offset + 2] = index + 1;
node = node;
depth = depth;
continue follow_path_map_9177;
}
nodes[depth - 1] = nodeParent = node;
if (key != null) {
node = nodeParent && nodeParent[key];
if (typeof map === 'object') {
for (var key$2 in map) {
key$2[0] === '$' && key$2 !== $SIZE && (nodeParent && (nodeParent[key$2] = map[key$2]) || true);
}
map = map[key];
}
var mapType = map && map[$TYPE] || void 0;
var mapValue = mapType === SENTINEL ? map[VALUE] : map;
if ((node == null || typeof node !== 'object' || !!nodeType && nodeType !== SENTINEL && !Array.isArray(nodeValue)) && (!mapType && (map != null && typeof map === 'object') && !Array.isArray(mapValue))) {
nodeType = void 0;
nodeValue = {};
nodeSize = node && node[$SIZE] || 0;
if (node !== nodeValue && (node != null && typeof node === 'object')) {
var nodeRefsLength$2 = node[__REFS_LENGTH] || 0, destRefsLength$2 = nodeValue[__REFS_LENGTH] || 0, i$7 = -1, ref$7;
while (++i$7 < nodeRefsLength$2) {
if ((ref$7 = node[__REF + i$7]) !== void 0) {
ref$7[__CONTEXT] = nodeValue;
nodeValue[__REF + (destRefsLength$2 + i$7)] = ref$7;
node[__REF + i$7] = void 0;
}
}
nodeValue[__REFS_LENGTH] = nodeRefsLength$2 + destRefsLength$2;
node[__REFS_LENGTH] = ref$7 = void 0;
var invParent$2 = nodeParent, invChild$2 = node, invKey$2 = key, keys$3, index$3, offset$3, childType$2, childValue$2, isBranch$2, stack$3 = [
nodeParent,
invKey$2,
node
], depth$4 = 0;
while (depth$4 > -1) {
nodeParent = stack$3[offset$3 = depth$4 * 8];
invKey$2 = stack$3[offset$3 + 1];
node = stack$3[offset$3 + 2];
if ((childType$2 = stack$3[offset$3 + 3]) === void 0 || (childType$2 = void 0)) {
childType$2 = stack$3[offset$3 + 3] = node && node[$TYPE] || void 0 || null;
}
childValue$2 = stack$3[offset$3 + 4] || (stack$3[offset$3 + 4] = childType$2 === SENTINEL ? node[VALUE] : node);
if ((isBranch$2 = stack$3[offset$3 + 5]) === void 0) {
isBranch$2 = stack$3[offset$3 + 5] = !childType$2 && (node != null && typeof node === 'object') && !Array.isArray(childValue$2);
}
if (isBranch$2 === true) {
if ((keys$3 = stack$3[offset$3 + 6]) === void 0) {
keys$3 = stack$3[offset$3 + 6] = [];
index$3 = -1;
for (var childKey$2 in node) {
!(!(childKey$2[0] !== '_' || childKey$2[1] !== '_') || (childKey$2 === __SELF || childKey$2 === __PARENT || childKey$2 === __ROOT) || childKey$2[0] === '$') && (keys$3[++index$3] = childKey$2);
}
}
index$3 = stack$3[offset$3 + 7] || (stack$3[offset$3 + 7] = 0);
if (index$3 < keys$3.length) {
stack$3[offset$3 + 7] = index$3 + 1;
stack$3[offset$3 = ++depth$4 * 8] = node;
stack$3[offset$3 + 1] = invKey$2 = keys$3[index$3];
stack$3[offset$3 + 2] = node[invKey$2];
continue;
}
}
var ref$8 = node[$TYPE] === SENTINEL ? node[VALUE] : node, destination$3;
if (ref$8 && Array.isArray(ref$8)) {
destination$3 = ref$8[__CONTEXT];
if (destination$3) {
var i$8 = (ref$8[__REF_INDEX] || 0) - 1, n$6 = (destination$3[__REFS_LENGTH] || 0) - 1;
while (++i$8 <= n$6) {
destination$3[__REF + i$8] = destination$3[__REF + (i$8 + 1)];
}
destination$3[__REFS_LENGTH] = n$6;
ref$8[__REF_INDEX] = ref$8[__CONTEXT] = destination$3 = void 0;
}
}
if (node != null && typeof node === 'object') {
var ref$9, i$9 = -1, n$7 = node[__REFS_LENGTH] || 0;
while (++i$9 < n$7) {
if ((ref$9 = node[__REF + i$9]) !== void 0) {
ref$9[__CONTEXT] = node[__REF + i$9] = void 0;
}
}
node[__REFS_LENGTH] = void 0;
var root$4 = root, head$3 = root$4.__head, tail$3 = root$4.__tail, next$3 = node.__next, prev$3 = node.__prev;
next$3 != null && typeof next$3 === 'object' && (next$3.__prev = prev$3);
prev$3 != null && typeof prev$3 === 'object' && (prev$3.__next = next$3);
node === head$3 && (root$4.__head = root$4.__next = next$3);
node === tail$3 && (root$4.__tail = root$4.__prev = prev$3);
node.__next = node.__prev = void 0;
head$3 = tail$3 = next$3 = prev$3 = void 0;
;
nodeParent[invKey$2] = node[__SELF] = node[__PARENT] = node[__ROOT] = void 0;
}
;
delete stack$3[offset$3 + 0];
delete stack$3[offset$3 + 1];
delete stack$3[offset$3 + 2];
delete stack$3[offset$3 + 3];
delete stack$3[offset$3 + 4];
delete stack$3[offset$3 + 5];
delete stack$3[offset$3 + 6];
delete stack$3[offset$3 + 7];
--depth$4;
}
nodeParent = invParent$2;
node = invChild$2;
}
nodeParent[key] = node = nodeValue;
node = !node[__SELF] && ((node[__SELF] = node) || true) && ((node[__KEY] = key) || true) && ((node[__PARENT] = nodeParent) || true) && ((node[__ROOT] = nodeRoot) || true) && (node[__GENERATION] || (node[__GENERATION] = ++__GENERATION_GUID) && node) && ((!nodeType || nodeType === SENTINEL) && Array.isArray(nodeValue) && (nodeValue[__CONTAINER] = node)) || node;
var self$3 = node, node$2;
while (node$2 = node) {
if (node[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
var self$4 = node, stack$4 = [], depth$5 = 0, linkPaths$2, ref$10, i$10, k$2, n$8;
while (depth$5 > -1) {
if ((linkPaths$2 = stack$4[depth$5]) === void 0) {
i$10 = k$2 = -1;
n$8 = node[__REFS_LENGTH] || 0;
node[__GENERATION_UPDATED] = __GENERATION_VERSION;
node[__GENERATION] = ++__GENERATION_GUID;
if ((ref$10 = node[__PARENT]) !== void 0 && ref$10[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
stack$4[depth$5] = linkPaths$2 = new Array(n$8 + 1);
linkPaths$2[++k$2] = ref$10;
} else if (n$8 > 0) {
stack$4[depth$5] = linkPaths$2 = new Array(n$8);
}
while (++i$10 < n$8) {
if ((ref$10 = node[__REF + i$10]) !== void 0 && ref$10[__GENERATION_UPDATED] !== __GENERATION_VERSION) {
linkPaths$2[++k$2] = ref$10;
}
}
}
if ((node = linkPaths$2 && linkPaths$2.pop()) !== void 0) {
++depth$5;
} else {
stack$4[depth$5--] = void 0;
}
}
node = self$4;
}
node = node$2[__PARENT];
}
node = self$3;
}
}
node = node;
depth = depth + 1;
continue follow_path_map_9177;
} while (true);
node = node;
var offset$4 = depth * 4, keys$4, index$4;
do {
delete mapStack[offset$4 + 0];
delete mapStack[offset$4 + 1];
delete mapStack[offset$4 + 2];
delete mapStack[offset$4 + 3];
} while ((keys$4 = mapStack[(offset$4 = 4 * --depth) + 1]) && ((index$4 = mapStack[offset$4 + 2]) || true) && (mapStack[offset$4 + 2] = ++index$4) >= keys$4.length);
}
return nodeRoot;
}
},{}],54:[function(_dereq_,module,exports){
var lru = _dereq_('./util/lru');
var clone = _dereq_('./util/clone');
var promote = lru.promote;
module.exports = function onError(model, node, permuteRequested, permuteOptimized, outerResults) {
outerResults.errors.push({path: permuteRequested, value: node.value});
promote(model, node);
if (permuteOptimized) {
outerResults.requestedPaths.push(permuteRequested);
outerResults.optimizedPaths.push(permuteOptimized);
}
};
},{"./util/clone":57,"./util/lru":62}],55:[function(_dereq_,module,exports){
var support = _dereq_('./util/support');
var fastCat = support.fastCat,
fastCatSkipNulls = support.fastCatSkipNulls,
fastCopy = support.fastCopy;
var isExpired = _dereq_('./util/isExpired');
var spreadJSON = _dereq_('./util/spreadJSON');
var clone = _dereq_('./util/clone');
module.exports = function onMissing(model, node, path, depth, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat) {
var pathSlice;
if (Array.isArray(path)) {
if (depth < path.length) {
pathSlice = fastCopy(path, depth);
} else {
pathSlice = [];
}
concatAndInsertMissing(pathSlice, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat);
} else {
pathSlice = [];
spreadJSON(path, pathSlice);
for (var i = 0, len = pathSlice.length; i < len; i++) {
concatAndInsertMissing(pathSlice[i], outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, true);
}
}
};
function concatAndInsertMissing(remainingPath, results, permuteRequested, permuteOptimized, permutePosition, outputFormat, __null) {
var i = 0, len;
if (__null) {
for (i = 0, len = remainingPath.length; i < len; i++) {
if (remainingPath[i] === '__null') {
remainingPath[i] = null;
}
}
}
if (outputFormat === 'JSON') {
permuteRequested = fastCat(permuteRequested, remainingPath);
for (i = 0, len = permutePosition.length; i < len; i++) {
var idx = permutePosition[i];
var r = permuteRequested[idx];
permuteRequested[idx] = [r];
}
results.requestedMissingPaths.push(permuteRequested);
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
} else {
results.requestedMissingPaths.push(fastCat(permuteRequested, remainingPath));
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
}
}
},{"./util/clone":57,"./util/isExpired":59,"./util/spreadJSON":64,"./util/support":65}],56:[function(_dereq_,module,exports){
var lru = _dereq_('./util/lru');
var clone = _dereq_('./util/clone');
var promote = lru.promote;
var $path = _dereq_('./../types/path');
var $sentinel = _dereq_('./../types/sentinel');
var $error = _dereq_('./../types/error');
module.exports = function onValue(model, node, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, fromReference) {
var i, len, k, key, curr, prev, prevK;
var materialized = false, valueNode;
if (node) {
promote(model, node);
}
if (!node || node.value === undefined) {
materialized = model._materialized;
}
// materialized
if (materialized) {
valueNode = {$type: $sentinel};
}
// Boxed Mode & Reference Node & Error node (only happens when model is in treat errors as values).
else if (model._boxed) {
valueNode = clone(node);
}
else if (node.$type === $path || node.$type === $error) {
if (outputFormat === 'JSONG') {
valueNode = clone(node);
} else {
valueNode = node.value;
}
}
else {
if (outputFormat === 'JSONG') {
if (typeof node.value === 'object') {
valueNode = clone(node);
} else {
valueNode = node.value;
}
} else {
valueNode = node.value;
}
}
if (permuteRequested) {
if (fromReference && permuteRequested[permuteRequested.length - 1] !== null) {
permuteRequested.push(null);
}
outerResults.requestedPaths.push(permuteRequested);
outerResults.optimizedPaths.push(permuteOptimized);
}
switch (outputFormat) {
case 'Values':
// in any subscription situation, onNexts are always provided, even as a noOp.
seedOrFunction({path: permuteRequested, value: valueNode});
break;
case 'PathMap':
len = permuteRequested.length - 1;
if (len === -1) {
seedOrFunction.json = valueNode;
} else {
curr = seedOrFunction.json;
if (!curr) {
curr = seedOrFunction.json = {};
}
for (i = 0; i < len; i++) {
k = permuteRequested[i];
if (!curr[k]) {
curr[k] = {};
}
prev = curr;
prevK = k;
curr = curr[k];
}
k = permuteRequested[i];
if (k !== null) {
curr[k] = valueNode;
} else {
prev[prevK] = valueNode;
}
}
break;
case 'JSON':
if (seedOrFunction) {
if (permutePosition.length) {
if (!seedOrFunction.json) {
seedOrFunction.json = {};
}
curr = seedOrFunction.json;
for (i = 0, len = permutePosition.length - 1; i < len; i++) {
k = permutePosition[i];
key = permuteRequested[k];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
k = permutePosition[i];
key = permuteRequested[k];
curr[key] = valueNode;
} else {
seedOrFunction.json = valueNode;
}
}
break;
case 'JSONG':
curr = seedOrFunction.jsong;
if (!curr) {
curr = seedOrFunction.jsong = {};
seedOrFunction.paths = [];
}
for (i = 0, len = permuteOptimized.length - 1; i < len; i++) {
key = permuteOptimized[i];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
key = permuteOptimized[i];
// TODO: Special case? do string comparisons make big difference?
curr[key] = materialized ? {$type: $sentinel} : valueNode;
if (permuteRequested) {
seedOrFunction.paths.push(permuteRequested);
}
break;
}
};
},{"./../types/error":139,"./../types/path":140,"./../types/sentinel":141,"./util/clone":57,"./util/lru":62}],57:[function(_dereq_,module,exports){
// Copies the node
var prefix = _dereq_("../../internal/prefix");
module.exports = function clone(node) {
var outValue, i, len;
var keys = Object.keys(node);
outValue = {};
for (i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
if (k[0] === prefix) {
continue;
}
outValue[k] = node[k];
}
return outValue;
};
},{"../../internal/prefix":74}],58:[function(_dereq_,module,exports){
var __ref = _dereq_("../../internal/ref");
var __context = _dereq_("../../internal/context");
var __ref_index = _dereq_("../../internal/ref-index");
var __refs_length = _dereq_("../../internal/refs-length");
function createHardlink(from, to) {
// create a back reference
var backRefs = to[__refs_length] || 0;
to[__ref + backRefs] = from;
to[__refs_length] = backRefs + 1;
// create a hard reference
from[__ref_index] = backRefs;
from[__context] = to;
}
function removeHardlink(cacheObject) {
var context = cacheObject[__context];
if (context) {
var idx = cacheObject[__ref_index];
var len = context[__refs_length];
while (idx < len) {
context[__ref + idx] = context[__REF + idx + 1];
++idx;
}
context[__refs_length] = len - 1;
cacheObject[__context] = undefined;
cacheObject[__ref_index] = undefined;
}
}
module.exports = {
create: createHardlink,
remove: removeHardlink
};
},{"../../internal/context":66,"../../internal/ref":77,"../../internal/ref-index":76,"../../internal/refs-length":78}],59:[function(_dereq_,module,exports){
var now = _dereq_('../../support/now');
module.exports = function isExpired(node) {
var $expires = node.$expires === undefined && -1 || node.$expires;
return $expires !== -1 && $expires !== 1 && ($expires === 0 || $expires < now());
};
},{"../../support/now":126}],60:[function(_dereq_,module,exports){
module.exports = function isMaterialized(model) {
return model._materialized && !(model._router || model._dataSource);
};
},{}],61:[function(_dereq_,module,exports){
module.exports = function(x) {
return x.path && x.value;
};
},{}],62:[function(_dereq_,module,exports){
var __head = _dereq_("../../internal/head");
var __tail = _dereq_("../../internal/tail");
var __next = _dereq_("../../internal/next");
var __prev = _dereq_("../../internal/prev");
var __invalidated = _dereq_("../../internal/invalidated");
// [H] -> Next -> ... -> [T]
// [T] -> Prev -> ... -> [H]
function lruPromote(model, object) {
var root = model._root;
var head = root[__head];
if (head === object) {
return;
}
// First insert
if (!head) {
root[__head] = object;
return;
}
// The head and the tail need to separate
if (!root[__tail]) {
root[__head] = object;
root[__tail] = head;
object[__next] = head;
// Now tail
head[__prev] = object;
return;
}
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = undefined;
// Insert into head position
root[__head] = object;
object[__next] = head;
head[__prev] = object;
}
function lruSplice(model, object) {
var root = model._root;
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = undefined;
if (object === root[__head]) {
root[__head] = undefined;
}
if (object === root[__tail]) {
root[__tail] = undefined;
}
object[__invalidated] = true;
root.expired.push(object);
}
module.exports = {
promote: lruPromote,
splice: lruSplice
};
},{"../../internal/head":68,"../../internal/invalidated":69,"../../internal/next":71,"../../internal/prev":75,"../../internal/tail":79}],63:[function(_dereq_,module,exports){
var prefix = _dereq_("../../internal/prefix");
module.exports = function permuteKey(key, memo) {
if (memo.isArray) {
if (memo.loaded && memo.rangeOffset > memo.to) {
memo.arrOffset++;
memo.loaded = false;
}
var idx = memo.arrOffset, length = key.length;
if (idx === length) {
memo.done = true;
return '';
}
var el = key[memo.arrOffset];
var type = typeof el;
if (type === 'object') {
if (!memo.loaded) {
memo.from = el.from || 0;
memo.to = el.to || el.length && memo.from + el.length - 1 || 0;
memo.rangeOffset = memo.from;
memo.loaded = true;
}
return memo.rangeOffset++;
} else {
do {
if (type !== 'string') {
break;
}
if (el[0] !== prefix && el[0] !== '$') {
break;
}
el = key[++idx];
} while (el === undefined || idx < length);
if (el === undefined || idx === length) {
memo.done = true;
return '';
}
memo.arrOffset = idx + 1;
return el;
}
} else {
if (!memo.loaded) {
memo.from = key.from || 0;
memo.to = key.to || key.length && memo.from + key.length - 1 || 0;
memo.rangeOffset = memo.from;
memo.loaded = true;
}
if (memo.rangeOffset > memo.to) {
memo.done = true;
return '';
}
return memo.rangeOffset++;
}
};
},{"../../internal/prefix":74}],64:[function(_dereq_,module,exports){
var fastCopy = _dereq_('./support').fastCopy;
module.exports = function spreadJSON(root, bins, bin) {
bin = bin || [];
if (!bins.length) {
bins.push(bin);
}
if (!root || typeof root !== 'object' || root.$type) {
return [];
}
var keys = Object.keys(root);
if (keys.length === 1) {
bin.push(keys[0]);
spreadJSON(root[keys[0]], bins, bin);
} else {
for (var i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
var nextBin = fastCopy(bin);
nextBin.push(k);
bins.push(nextBin);
spreadJSON(root[k], bins, nextBin);
}
}
};
},{"./support":65}],65:[function(_dereq_,module,exports){
function fastCopy(arr, i) {
var a = [], len, j;
for (j = 0, i = i || 0, len = arr.length; i < len; j++, i++) {
a[j] = arr[i];
}
return a;
}
function fastCatSkipNulls(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
if (arr2[j] !== null) {
a[i++] = arr2[j];
}
}
return a;
}
function fastCat(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
a[i++] = arr2[j];
}
return a;
}
module.exports = {
fastCat: fastCat,
fastCatSkipNulls: fastCatSkipNulls,
fastCopy: fastCopy
};
},{}],66:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "context";
},{"./prefix":74}],67:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "generation";
},{"./prefix":74}],68:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "head";
},{"./prefix":74}],69:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "invalidated";
},{"./prefix":74}],70:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "key";
},{"./prefix":74}],71:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "next";
},{"./prefix":74}],72:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "offset";
},{"./prefix":74}],73:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "parent";
},{"./prefix":74}],74:[function(_dereq_,module,exports){
// This may look like an empty string, but it's actually a single zero-width-space character.
module.exports = "";
},{}],75:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "prev";
},{"./prefix":74}],76:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "ref-index";
},{"./prefix":74}],77:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "ref";
},{"./prefix":74}],78:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "refs-length";
},{"./prefix":74}],79:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "tail";
},{"./prefix":74}],80:[function(_dereq_,module,exports){
module.exports = _dereq_("./prefix") + "version";
},{"./prefix":74}],81:[function(_dereq_,module,exports){
module.exports = {
invPathSetsAsJSON: _dereq_("./invalidate-path-sets-as-json-dense"),
invPathSetsAsJSONG: _dereq_("./invalidate-path-sets-as-json-graph"),
invPathSetsAsPathMap: _dereq_("./invalidate-path-sets-as-json-sparse"),
invPathSetsAsValues: _dereq_("./invalidate-path-sets-as-json-values")
};
},{"./invalidate-path-sets-as-json-dense":82,"./invalidate-path-sets-as-json-graph":83,"./invalidate-path-sets-as-json-sparse":84,"./invalidate-path-sets-as-json-values":85}],82:[function(_dereq_,module,exports){
module.exports = invalidate_path_sets_as_json_dense;
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var array_slice = _dereq_("../support/array-slice");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var update_graph = _dereq_("../support/update-graph");
var invalidate_node = _dereq_("../support/invalidate-node");
var collect = _dereq_("../lru/collect");
function invalidate_path_sets_as_json_dense(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots[3] = parents[3] = nodes[3] = undefined;
}
var pathset = pathsets[index];
roots.index = index;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
if (is_keyset && !!(parents[3] = json)) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
nodes[0] = node;
if (!!json) {
var type = is_object(node) && node.$type || undefined;
var jsonkey = keyset;
if (jsonkey == null) {
json = roots;
jsonkey = 3;
}
json[jsonkey] = clone(roots, node, type, node && node.value);
}
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
roots.json = roots[3];
roots.hasValue = true;
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/array-slice":105,"../support/clone-dense-json":106,"../support/get-valid-key":116,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/update-graph":137,"../walk/walk-path-set":147}],83:[function(_dereq_,module,exports){
module.exports = invalidate_path_sets_as_json_graph;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var update_graph = _dereq_("../support/update-graph");
var invalidate_node = _dereq_("../support/invalidate-node");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function invalidate_path_sets_as_json_graph(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var type = is_object(node) && node.$type || undefined;
if (is_branch) {
parents[0] = nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
clone_success(roots, requested, optimized);
roots.json = roots[1];
roots.hasValue = true;
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/update-graph":137,"../types/path":140,"../walk/walk-path-set-soft-link":146}],84:[function(_dereq_,module,exports){
module.exports = invalidate_path_sets_as_json_sparse;
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var array_slice = _dereq_("../support/array-slice");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var update_graph = _dereq_("../support/update-graph");
var invalidate_node = _dereq_("../support/invalidate-node");
var collect = _dereq_("../lru/collect");
function invalidate_path_sets_as_json_sparse(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
parents[3] = json;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
nodes[0] = node;
var type = is_object(node) && node.$type || undefined;
json[jsonkey] = clone(roots, node, type, node && node.value);
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
roots.json = roots[3];
roots.hasValue = true;
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/array-slice":105,"../support/clone-dense-json":106,"../support/get-valid-key":116,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/update-graph":137,"../walk/walk-path-set":147}],85:[function(_dereq_,module,exports){
module.exports = invalidate_path_sets_as_json_values;
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var array_slice = _dereq_("../support/array-slice");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var update_graph = _dereq_("../support/update-graph");
var invalidate_node = _dereq_("../support/invalidate-node");
var collect = _dereq_("../lru/collect");
function invalidate_path_sets_as_json_values(model, pathsets, onNext) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pathset = pathsets[index];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key];
if (!is_top_level) {
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
parents[0] = nodes[0] = node;
return;
}
nodes[0] = node;
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || undefined;
var onNext = roots.onNext;
if (!!type && onNext) {
onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
roots.requestedPaths.push(array_slice(requested, roots.offset));
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/array-slice":105,"../support/clone-dense-json":106,"../support/get-valid-key":116,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/update-graph":137,"../walk/walk-path-set":147}],86:[function(_dereq_,module,exports){
var __head = _dereq_("../internal/head");
var __tail = _dereq_("../internal/tail");
var __next = _dereq_("../internal/next");
var __prev = _dereq_("../internal/prev");
var update_graph = _dereq_("../support/update-graph");
module.exports = function(lru, expired, version, total, max, ratio) {
var targetSize = max * ratio;
var node, size;
while(!!(node = expired.pop())) {
size = node.$size || 0;
total -= size;
update_graph(node, size, version, lru);
}
if(total >= max) {
var prev = lru[__tail];
while((total >= targetSize) && !!(node = prev)) {
prev = prev[__prev];
size = node.$size || 0;
total -= size;
update_graph(node, size, version, lru);
}
if((lru[__tail] = lru[__prev] = prev) == null) {
lru[__head] = lru[__next] = undefined;
} else {
prev[__next] = undefined;
}
}
};
},{"../internal/head":68,"../internal/next":71,"../internal/prev":75,"../internal/tail":79,"../support/update-graph":137}],87:[function(_dereq_,module,exports){
var $expires_never = _dereq_("../values/expires-never");
var __head = _dereq_("../internal/head");
var __tail = _dereq_("../internal/tail");
var __next = _dereq_("../internal/next");
var __prev = _dereq_("../internal/prev");
var is_object = _dereq_("../support/is-object");
module.exports = function(root, node) {
if(is_object(node) && (node.$expires !== $expires_never)) {
var head = root[__head], tail = root[__tail],
next = node[__next], prev = node[__prev];
if (node !== head) {
(next != null && typeof next === "object") && (next[__prev] = prev);
(prev != null && typeof prev === "object") && (prev[__next] = next);
(next = head) && (head != null && typeof head === "object") && (head[__prev] = node);
(root[__head] = root[__next] = head = node);
(head[__next] = next);
(head[__prev] = undefined);
}
if (tail == null || node === tail) {
root[__tail] = root[__prev] = tail = prev || node;
}
}
return node;
};
},{"../internal/head":68,"../internal/next":71,"../internal/prev":75,"../internal/tail":79,"../support/is-object":122,"../values/expires-never":142}],88:[function(_dereq_,module,exports){
var __head = _dereq_("../internal/head");
var __tail = _dereq_("../internal/tail");
var __next = _dereq_("../internal/next");
var __prev = _dereq_("../internal/prev");
module.exports = function(root, node) {
var head = root[__head], tail = root[__tail],
next = node[__next], prev = node[__prev];
(next != null && typeof next === "object") && (next[__prev] = prev);
(prev != null && typeof prev === "object") && (prev[__next] = next);
(node === head) && (root[__head] = root[__next] = next);
(node === tail) && (root[__tail] = root[__prev] = prev);
node[__next] = node[__prev] = undefined;
head = tail = next = prev = undefined;
};
},{"../internal/head":68,"../internal/next":71,"../internal/prev":75,"../internal/tail":79}],89:[function(_dereq_,module,exports){
module.exports = {
setPathSetsAsJSON: _dereq_('./set-json-values-as-json-dense'),
setPathSetsAsJSONG: _dereq_('./set-json-values-as-json-graph'),
setPathSetsAsPathMap: _dereq_('./set-json-values-as-json-sparse'),
setPathSetsAsValues: _dereq_('./set-json-values-as-json-values'),
setPathMapsAsJSON: _dereq_('./set-json-sparse-as-json-dense'),
setPathMapsAsJSONG: _dereq_('./set-json-sparse-as-json-graph'),
setPathMapsAsPathMap: _dereq_('./set-json-sparse-as-json-sparse'),
setPathMapsAsValues: _dereq_('./set-json-sparse-as-json-values'),
setJSONGsAsJSON: _dereq_('./set-json-graph-as-json-dense'),
setJSONGsAsJSONG: _dereq_('./set-json-graph-as-json-graph'),
setJSONGsAsPathMap: _dereq_('./set-json-graph-as-json-sparse'),
setJSONGsAsValues: _dereq_('./set-json-graph-as-json-values'),
setCache: _dereq_('./set-cache')
};
},{"./set-cache":90,"./set-json-graph-as-json-dense":91,"./set-json-graph-as-json-graph":92,"./set-json-graph-as-json-sparse":93,"./set-json-graph-as-json-values":94,"./set-json-sparse-as-json-dense":95,"./set-json-sparse-as-json-graph":96,"./set-json-sparse-as-json-sparse":97,"./set-json-sparse-as-json-values":98,"./set-json-values-as-json-dense":99,"./set-json-values-as-json-graph":100,"./set-json-values-as-json-sparse":101,"./set-json-values-as-json-values":102}],90:[function(_dereq_,module,exports){
module.exports = set_cache;
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var collect = _dereq_("../lru/collect");
function set_cache(model, pathmap, error_selector) {
var roots = options([], model, error_selector);
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
roots[0] = roots.root;
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return model;
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key],
type;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/sentinel":141,"../walk/walk-path-map":145}],91:[function(_dereq_,module,exports){
module.exports = set_json_graph_as_json_dense;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var merge_node = _dereq_("../support/merge-node");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_graph_as_json_dense(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var index2 = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index3 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index3 < count2) {
json = values && values[++index2];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pathset = pathsets[index3];
roots.index = index3;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
messageParent = parents[2];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
var length = requested.length;
var offset = roots.offset;
parents[3] = json;
if (is_branch) {
parents[0] = node;
parents[2] = message;
if ((length > offset) && is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/is-object":122,"../support/merge-node":125,"../support/options":127,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../types/path":140,"../walk/walk-path-set-soft-link":146}],92:[function(_dereq_,module,exports){
module.exports = set_json_graph_as_json_graph;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-graph-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var merge_node = _dereq_("../support/merge-node");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var promote = _dereq_("../lru/promote");
var collect = _dereq_("../lru/collect");
function set_json_graph_as_json_graph(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = 0;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
messageParent = parents[2];
} else {
json = nodes[1];
parent = nodes[0];
messageParent = nodes[2];
}
var jsonkey = key;
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
parents[1] = json;
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var type = is_object(node) && node.$type || undefined;
if (is_branch) {
parents[0] = node;
parents[2] = message;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":86,"../lru/promote":87,"../support/array-clone":104,"../support/clone-graph-json":107,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/is-object":122,"../support/merge-node":125,"../support/options":127,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../types/path":140,"../walk/walk-path-set-soft-link":146}],93:[function(_dereq_,module,exports){
module.exports = set_json_graph_as_json_sparse;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var merge_node = _dereq_("../support/merge-node");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_graph_as_json_sparse(model, envelopes, values, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, messageParent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
messageParent = parents[2];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
parents[3] = json;
if (is_branch) {
var length = requested.length;
var offset = roots.offset;
var type = is_object(node) && node.$type || undefined;
parents[0] = node;
parents[2] = message;
if ((length > offset) && (!type || type == $path)) {
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/is-object":122,"../support/merge-node":125,"../support/options":127,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../types/path":140,"../walk/walk-path-set-soft-link":146}],94:[function(_dereq_,module,exports){
module.exports = set_json_graph_as_json_values;
var $path = _dereq_("../types/path");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var array_slice = _dereq_("../support/array-slice");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var merge_node = _dereq_("../support/merge-node");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_graph_as_json_values(model, envelopes, onNext, error_selector) {
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, error_selector);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[2] = jsong;
nodes[2] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset) {
var parent, messageParent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
messageParent = parents[2];
} else {
parent = nodes[0];
messageParent = nodes[2];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[2] = message;
nodes[0] = node = merge_node(roots, parent, node, messageParent, message, key);
if (!is_top_level) {
parents[0] = parent;
parents[2] = messageParent;
return;
}
if (is_branch) {
parents[0] = node;
parents[2] = message;
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_slice(requested, roots.offset),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/array-slice":105,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/get-valid-key":116,"../support/is-object":122,"../support/merge-node":125,"../support/options":127,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../types/path":140,"../walk/walk-path-set-soft-link":146}],95:[function(_dereq_,module,exports){
module.exports = set_json_sparse_as_json_dense;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-map");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_sparse_as_json_dense(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pathmap = pathmaps[index];
roots.index = index;
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
if (is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-map":133,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-map":145}],96:[function(_dereq_,module,exports){
module.exports = set_json_sparse_as_json_graph;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-graph-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-map");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var promote = _dereq_("../lru/promote");
var collect = _dereq_("../lru/collect");
function set_json_sparse_as_json_graph(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
type = node.$type;
parents[0] = nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":86,"../lru/promote":87,"../support/array-clone":104,"../support/clone-graph-json":107,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-map":133,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-map-soft-link":144}],97:[function(_dereq_,module,exports){
module.exports = set_json_sparse_as_json_sparse;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-map");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_sparse_as_json_sparse(model, pathmaps, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-map":133,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-map":145}],98:[function(_dereq_,module,exports){
module.exports = set_path_map_as_json_values;
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_map = _dereq_("../walk/walk-path-map");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-map");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_path_map_as_json_values(model, pathmaps, onNext, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var keys_stack = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pathmap = pathmaps[index];
walk_path_map(onNode, onEdge, pathmap, keys_stack, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = pathmap;
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
nodes[0] = node;
}
function onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathmap, keys_stack, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-map":133,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/sentinel":141,"../walk/walk-path-map":145}],99:[function(_dereq_,module,exports){
module.exports = set_json_values_as_json_dense;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var invalidate_node = _dereq_("../support/invalidate-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_values_as_json_dense(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json, hasValue, hasValues;
roots[0] = roots.root;
while (++index < count) {
json = values && values[index];
if (is_object(json)) {
roots.json = roots[3] = parents[3] = nodes[3] = json.json || (json.json = {})
} else {
roots.json = roots[3] = parents[3] = nodes[3] = undefined;
}
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
roots.index = index;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (!!hasValue) {
hasValues = true;
if (is_object(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (is_object(json)) {
delete json.json;
}
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[3];
parent = parents[0];
} else {
json = is_keyset && nodes[3] || parents[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
if (is_keyset && !!json) {
nodes[3] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if(keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else if(!!(json = parents[3])) {
json[keyset] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-set":147}],100:[function(_dereq_,module,exports){
module.exports = set_json_values_as_json_graph;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-graph-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set-soft-link");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var invalidate_node = _dereq_("../support/invalidate-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var promote = _dereq_("../lru/promote");
var collect = _dereq_("../lru/collect");
function set_json_values_as_json_graph(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[1] = parents[1] = nodes[1] = json.jsong || (json.jsong = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.jsong = roots[1];
} else {
delete json.jsong;
delete json.paths;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
json = parents[1];
parent = parents[0];
} else {
json = nodes[1];
parent = nodes[0];
}
var jsonkey = key;
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
type = node.$type;
parents[0] = parent;
nodes[0] = node;
parents[1] = json;
if (type == $path) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[1] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
promote(roots.lru, node);
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[1];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"../lru/collect":86,"../lru/promote":87,"../support/array-clone":104,"../support/clone-graph-json":107,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-set-soft-link":146}],101:[function(_dereq_,module,exports){
module.exports = set_json_values_as_json_sparse;
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var invalidate_node = _dereq_("../support/invalidate-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_values_as_json_sparse(model, pathvalues, values, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[0] = roots.root;
roots[3] = parents[3] = nodes[3] = json.json || (json.json = {});
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if(hasValue) {
json.json = roots[3];
} else {
delete json.json;
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent, json, jsonkey;
if (key == null) {
if ((key = get_valid_key(optimized)) == null) {
return;
}
jsonkey = get_valid_key(requested);
json = parents[3];
parent = parents[0];
} else {
jsonkey = key;
json = nodes[3];
parent = nodes[0];
}
var node = parent[key],
type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
parents[3] = json;
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
nodes[3] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
if (keyset == null && !roots.hasValue && (keyset = get_valid_key(optimized)) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[3];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[3];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/path":140,"../types/sentinel":141,"../walk/walk-path-set":147}],102:[function(_dereq_,module,exports){
module.exports = set_json_values_as_json_values;
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("../support/clone-dense-json");
var array_clone = _dereq_("../support/array-clone");
var options = _dereq_("../support/options");
var walk_path_set = _dereq_("../walk/walk-path-set");
var is_object = _dereq_("../support/is-object");
var get_valid_key = _dereq_("../support/get-valid-key");
var create_branch = _dereq_("../support/create-branch");
var wrap_node = _dereq_("../support/wrap-node");
var invalidate_node = _dereq_("../support/invalidate-node");
var replace_node = _dereq_("../support/replace-node");
var graph_node = _dereq_("../support/graph-node");
var update_back_refs = _dereq_("../support/update-back-refs");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("../support/inc-generation");
var node_as_miss = _dereq_("../support/treat-node-as-missing-path-set");
var node_as_error = _dereq_("../support/treat-node-as-error");
var clone_success = _dereq_("../support/clone-success-paths");
var collect = _dereq_("../lru/collect");
function set_json_values_as_json_values(model, pathvalues, onNext, error_selector) {
var roots = options([], model, error_selector);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = array_clone(nodes);
var requested = [];
var optimized = [];
roots[0] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walk_path_set(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
collect(
roots.lru,
roots.expired,
roots.version,
roots.root.$size || 0,
model._maxSize,
model._collectRatio
);
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, is_top_level, is_branch, key, keyset, is_keyset) {
var parent;
if (key == null) {
if ((key = get_valid_key(optimized, nodes)) == null) {
return;
}
parent = parents[0];
} else {
parent = nodes[0];
}
var node = parent[key], type;
if (!is_top_level) {
type = is_object(node) && node.$type || undefined;
type = type && is_branch && "." || type;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
if (is_branch) {
type = is_object(node) && node.$type || undefined;
node = create_branch(roots, parent, node, type, key);
parents[0] = parent;
nodes[0] = node;
return;
}
var selector = roots.error_selector;
var root = roots[0];
var size = is_object(node) && node.$size || 0;
var mess = roots.value;
if(mess === undefined && roots.headless) {
invalidate_node(parent, node, key, roots.lru);
update_graph(parent, size, roots.version, roots.lru);
node = undefined;
} else {
type = is_object(mess) && mess.$type || undefined;
mess = wrap_node(mess, type, !!type ? mess.value : mess);
type || (type = $sentinel);
if (type == $error && !!selector) {
mess = selector(requested, mess);
}
node = replace_node(parent, node, mess, key, roots.lru);
node = graph_node(root, parent, node, key, inc_generation());
update_graph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[0] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[0];
var type = is_object(node) && node.$type || (node = undefined);
if (node_as_miss(roots, node, type, pathset, depth, requested, optimized) === false) {
clone_success(roots, requested, optimized);
if (node_as_error(roots, node, type, requested) === false) {
roots.onNext({
path: array_clone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
}
},{"../lru/collect":86,"../support/array-clone":104,"../support/clone-dense-json":106,"../support/clone-success-paths":112,"../support/create-branch":114,"../support/get-valid-key":116,"../support/graph-node":117,"../support/inc-generation":118,"../support/invalidate-node":120,"../support/is-object":122,"../support/options":127,"../support/replace-node":130,"../support/treat-node-as-error":132,"../support/treat-node-as-missing-path-set":134,"../support/update-back-refs":136,"../support/update-graph":137,"../support/wrap-node":138,"../types/error":139,"../types/sentinel":141,"../walk/walk-path-set":147}],103:[function(_dereq_,module,exports){
module.exports = function(array, value) {
var i = -1;
var n = array.length;
var array2 = new Array(n + 1);
while(++i < n) { array2[i] = array[i]; }
array2[i] = value;
return array2;
};
},{}],104:[function(_dereq_,module,exports){
module.exports = function(array) {
var i = -1;
var n = array.length;
var array2 = new Array(n);
while(++i < n) { array2[i] = array[i]; }
return array2;
};
},{}],105:[function(_dereq_,module,exports){
module.exports = function(array, index) {
var i = -1;
var n = array.length - index;
var array2 = new Array(n);
while(++i < n) { array2[i] = array[i + index]; }
return array2;
};
},{}],106:[function(_dereq_,module,exports){
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("./clone");
module.exports = function(roots, node, type, value) {
if(node == null || value === undefined) {
return { $type: $sentinel };
}
if(roots.boxed == true) {
return !!type && clone(node) || node;
}
return value;
}
},{"../types/sentinel":141,"./clone":113}],107:[function(_dereq_,module,exports){
var $sentinel = _dereq_("../types/sentinel");
var clone = _dereq_("./clone");
var is_primitive = _dereq_("./is-primitive");
module.exports = function(roots, node, type, value) {
if(node == null || value === undefined) {
return { $type: $sentinel };
}
if(roots.boxed == true) {
return !!type && clone(node) || node;
}
if(!type || (type === $sentinel && is_primitive(value))) {
return value;
}
return clone(node);
}
},{"../types/sentinel":141,"./clone":113,"./is-primitive":123}],108:[function(_dereq_,module,exports){
var clone_requested = _dereq_("./clone-requested-path");
var clone_optimized = _dereq_("./clone-optimized-path");
var walk_path_map = _dereq_("../walk/walk-path-map-soft-link");
var is_object = _dereq_("./is-object");
var empty = [];
module.exports = function(roots, pathmap, keys_stack, depth, requested, optimized) {
var patset_keys = explode_keys(pathmap, keys_stack.concat(), depth);
var pathset = patset_keys.map(function(keys) {
keys = keys.filter(function(key) { return key != "null"; });
switch(keys.length) {
case 0:
return null;
case 1:
return keys[0];
default:
return keys;
}
});
roots.requestedMissingPaths.push(clone_requested(roots.bound, requested, pathset, depth, roots.index));
roots.optimizedMissingPaths.push(clone_optimized(optimized, pathset, depth));
}
function explode_keys(pathmap, keys_stack, depth) {
if(is_object(pathmap)) {
var keys = Object.keys(pathmap);
var keys2 = keys_stack[depth] || (keys_stack[depth] = []);
keys2.push.apply(keys2, keys);
keys.forEach(function(key) {
explode_keys(pathmap[key], keys_stack, depth + 1);
});
}
return keys_stack;
}
},{"../walk/walk-path-map-soft-link":144,"./clone-optimized-path":110,"./clone-requested-path":111,"./is-object":122}],109:[function(_dereq_,module,exports){
var clone_requested_path = _dereq_("./clone-requested-path");
var clone_optimized_path = _dereq_("./clone-optimized-path");
module.exports = function(roots, pathset, depth, requested, optimized) {
roots.requestedMissingPaths.push(clone_requested_path(roots.bound, requested, pathset, depth, roots.index));
roots.optimizedMissingPaths.push(clone_optimized_path(optimized, pathset, depth));
}
},{"./clone-optimized-path":110,"./clone-requested-path":111}],110:[function(_dereq_,module,exports){
module.exports = function(optimized, pathset, depth) {
var x;
var i = -1;
var j = depth - 1;
var n = optimized.length;
var m = pathset.length;
var array2 = [];
while(++i < n) {
array2[i] = optimized[i];
}
while(++j < m) {
if((x = pathset[j]) != null) {
array2[i++] = x;
}
}
return array2;
}
},{}],111:[function(_dereq_,module,exports){
var is_object = _dereq_("./is-object");
module.exports = function(bound, requested, pathset, depth, index) {
var x;
var i = -1;
var j = -1;
var l = 0;
var m = requested.length;
var n = bound.length;
var array2 = [];
while(++i < n) {
array2[i] = bound[i];
}
while(++j < m) {
if((x = requested[j]) != null) {
if(is_object(pathset[l++])) {
array2[i++] = [x];
} else {
array2[i++] = x;
}
}
}
m = n + l + pathset.length - depth;
while(i < m) {
array2[i++] = pathset[l++];
}
if(index != null) {
array2.pathSetIndex = index;
}
return array2;
}
},{"./is-object":122}],112:[function(_dereq_,module,exports){
var array_slice = _dereq_("./array-slice");
var array_clone = _dereq_("./array-clone");
module.exports = function(roots, requested, optimized) {
roots.requestedPaths.push(array_slice(requested, roots.offset));
roots.optimizedPaths.push(array_clone(optimized));
}
},{"./array-clone":104,"./array-slice":105}],113:[function(_dereq_,module,exports){
var is_object = _dereq_("./is-object");
var prefix = _dereq_("../internal/prefix");
module.exports = function(value) {
var dest = value, src = dest, i = -1, n, keys, key;
if(is_object(dest)) {
dest = {};
keys = Object.keys(src);
n = keys.length;
while(++i < n) {
key = keys[i];
if(key[0] !== prefix) {
dest[key] = src[key];
}
}
}
return dest;
}
},{"../internal/prefix":74,"./is-object":122}],114:[function(_dereq_,module,exports){
var $path = _dereq_("../types/path");
var $expired = "expired";
var replace_node = _dereq_("./replace-node");
var graph_node = _dereq_("./graph-node");
var update_back_refs = _dereq_("./update-back-refs");
var is_primitive = _dereq_("./is-primitive");
var is_expired = _dereq_("./is-expired");
module.exports = function(roots, parent, node, type, key) {
if(!!type && is_expired(roots, node)) {
type = $expired;
}
if((!!type && type != $path) || is_primitive(node)) {
node = replace_node(parent, node, {}, key, roots.lru);
node = graph_node(roots[0], parent, node, key, 0);
node = update_back_refs(node, roots.version);
}
return node;
}
},{"../types/path":140,"./graph-node":117,"./is-expired":121,"./is-primitive":123,"./replace-node":130,"./update-back-refs":136}],115:[function(_dereq_,module,exports){
var __ref = _dereq_("../internal/ref");
var __context = _dereq_("../internal/context");
var __ref_index = _dereq_("../internal/ref-index");
var __refs_length = _dereq_("../internal/refs-length");
module.exports = function(node) {
var ref, i = -1, n = node[__refs_length] || 0;
while(++i < n) {
if((ref = node[__ref + i]) !== undefined) {
ref[__context] = ref[__ref_index] = node[__ref + i] = undefined;
}
}
node[__refs_length] = undefined
}
},{"../internal/context":66,"../internal/ref":77,"../internal/ref-index":76,"../internal/refs-length":78}],116:[function(_dereq_,module,exports){
module.exports = function(path) {
var key, index = path.length - 1;
do {
if((key = path[index]) != null) {
return key;
}
} while(--index > -1);
return null;
}
},{}],117:[function(_dereq_,module,exports){
var __parent = _dereq_("../internal/parent");
var __key = _dereq_("../internal/key");
var __generation = _dereq_("../internal/generation");
module.exports = function(root, parent, node, key, generation) {
node[__parent] = parent;
node[__key] = key;
node[__generation] = generation;
return node;
}
},{"../internal/generation":67,"../internal/key":70,"../internal/parent":73}],118:[function(_dereq_,module,exports){
var generation = 0;
module.exports = function() { return generation++; }
},{}],119:[function(_dereq_,module,exports){
var version = 0;
module.exports = function() { return version++; }
},{}],120:[function(_dereq_,module,exports){
module.exports = invalidate;
var is_object = _dereq_("./is-object");
var remove_node = _dereq_("./remove-node");
var prefix = _dereq_("../internal/prefix");
function invalidate(parent, node, key, lru) {
if(remove_node(parent, node, key, lru)) {
var type = is_object(node) && node.$type || undefined;
if(type == null) {
var keys = Object.keys(node);
for(var i = -1, n = keys.length; ++i < n;) {
var key = keys[i];
if(key[0] !== prefix && key[0] !== "$") {
invalidate(node, node[key], key, lru);
}
}
}
return true;
}
return false;
}
},{"../internal/prefix":74,"./is-object":122,"./remove-node":129}],121:[function(_dereq_,module,exports){
var $expires_now = _dereq_("../values/expires-now");
var $expires_never = _dereq_("../values/expires-never");
var __invalidated = _dereq_("../internal/invalidated");
var now = _dereq_("./now");
var splice = _dereq_("../lru/splice");
module.exports = function(roots, node) {
var expires = node.$expires;
if((expires != null ) && (
expires != $expires_never ) && (
expires == $expires_now || expires < now())) {
if(!node[__invalidated]) {
node[__invalidated] = true;
roots.expired.push(node);
splice(roots.lru, node);
}
return true;
}
return false;
}
},{"../internal/invalidated":69,"../lru/splice":88,"../values/expires-never":142,"../values/expires-now":143,"./now":126}],122:[function(_dereq_,module,exports){
var obj_typeof = "object";
module.exports = function(value) {
return value != null && typeof value == obj_typeof;
}
},{}],123:[function(_dereq_,module,exports){
var obj_typeof = "object";
module.exports = function(value) {
return value == null || typeof value != obj_typeof;
}
},{}],124:[function(_dereq_,module,exports){
module.exports = key_to_keyset;
var __offset = _dereq_("../internal/offset");
var is_array = Array.isArray;
var is_object = _dereq_("./is-object");
function key_to_keyset(key, iskeyset) {
if(iskeyset) {
if(is_array(key)) {
key = key[key[__offset]];
return key_to_keyset(key, is_object(key));
} else {
return key[__offset];
}
}
return key;
}
},{"../internal/offset":72,"./is-object":122}],125:[function(_dereq_,module,exports){
var $self = "./";
var $path = _dereq_("../types/path");
var $sentinel = _dereq_("../types/sentinel");
var $expires_now = _dereq_("../values/expires-now");
var is_object = _dereq_("./is-object");
var is_primitive = _dereq_("./is-primitive");
var is_expired = _dereq_("./is-expired");
var promote = _dereq_("../lru/promote");
var wrap_node = _dereq_("./wrap-node");
var graph_node = _dereq_("./graph-node");
var replace_node = _dereq_("../support/replace-node");
var update_graph = _dereq_("../support/update-graph");
var inc_generation = _dereq_("./inc-generation");
var invalidate_node = _dereq_("./invalidate-node");
module.exports = function(roots, parent, node, messageParent, message, key) {
var type, messageType, node_is_object, message_is_object;
// If the cache and message are the same, we can probably return early:
// - If they're both null, return null.
// - If they're both branches, return the branch.
// - If they're both edges, continue below.
if(node == message) {
if(node == null) {
return null;
} else if(node_is_object = is_object(node)) {
type = node.$type;
if(type == null) {
if(node[$self] == null) {
return graph_node(roots[0], parent, node, key, 0);
}
return node;
}
}
} else if(node_is_object = is_object(node)) {
type = node.$type;
}
var value, messageValue;
if(type == $path) {
if(message == null) {
// If the cache is an expired reference, but the message
// is empty, remove the cache value and return undefined
// so we build a missing path.
if(is_expired(roots, node)) {
invalidate_node(parent, node, key, roots.lru);
return undefined;
}
// If the cache has a reference and the message is empty,
// leave the cache alone and follow the reference.
return node;
} else if(message_is_object = is_object(message)) {
messageType = message.$type;
// If the cache and the message are both references,
// check if we need to replace the cache reference.
if(messageType == $path) {
if(node === message) {
// If the cache and message are the same reference,
// we performed a whole-branch merge of one of the
// grandparents. If we've previously graphed this
// reference, break early.
if(node[$self] != null) {
return node;
}
}
// If the message doesn't expire immediately and is newer than the
// cache (or either cache or message don't have timestamps), attempt
// to use the message value.
// Note: Number and `undefined` compared LT/GT to `undefined` is `false`.
else if((
is_expired(roots, message) === false) && ((
message.$timestamp < node.$timestamp) === false)) {
// Compare the cache and message references.
// - If they're the same, break early so we don't insert.
// - If they're different, replace the cache reference.
value = node.value;
messageValue = message.value;
var count = value.length;
// If the reference lengths are equal, check their keys for equality.
if(count === messageValue.length) {
while(--count > -1) {
// If any of their keys are different, replace the reference
// in the cache with the reference in the message.
if(value[count] !== messageValue[count]) {
break;
}
}
// If all their keys are equal, leave the cache value alone.
if(count === -1) {
return node;
}
}
}
}
}
} else {
if(message_is_object = is_object(message)) {
messageType = message.$type;
}
if(node_is_object && !type) {
// Otherwise if the cache is a branch and the message is either
// null or also a branch, continue with the cache branch.
if(message == null || (message_is_object && !messageType)) {
return node;
}
}
}
// If the message is an expired edge, report it back out so we don't build a missing path, but
// don't insert it into the cache. If a value exists in the cache that didn't come from a
// whole-branch grandparent merge, remove the cache value.
if(!!messageType && !!message[$self] && is_expired(roots, message)) {
if(node_is_object && node != message) {
invalidate_node(parent, node, key, roots.lru);
}
return message;
}
// If the cache is a value, but the message is a branch, merge the branch over the value.
else if(!!type && message_is_object && !messageType) {
node = replace_node(parent, node, message, key, roots.lru);
return graph_node(roots[0], parent, node, key, 0);
}
// If the message is a value, insert it into the cache.
else if(!message_is_object || !!messageType) {
var offset = 0;
// If we've arrived at this message value, but didn't perform a whole-branch merge
// on one of its ancestors, replace the cache node with the message value.
if(node != message) {
messageValue || (messageValue = !!messageType ? message.value : message);
message = wrap_node(message, messageType, messageValue);
var size = node_is_object && node.$size || 0;
var messageSize = message.$size;
offset = size - messageSize;
node = replace_node(parent, node, message, key, roots.lru);
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// If the cache and the message are the same value, we branch-merged one of its
// ancestors. Give the message a $size and $type, attach its graph pointers, and
// update the cache sizes and generations.
else if(node_is_object && node[$self] == null) {
node = parent[key] = wrap_node(node, type, node.value);
offset = -node.$size;
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// Otherwise, cache and message are the same primitive value. Wrap in a sentinel and insert.
else {
node = parent[key] = wrap_node(node, type, node);
offset = -node.$size;
update_graph(parent, offset, roots.version, roots.lru);
node = graph_node(roots[0], parent, node, key, inc_generation());
}
// If the node is already expired, return undefined to build a missing path.
// if(is_expired(roots, node)) {
// return undefined;
// }
// Promote the message edge in the LRU.
promote(roots.lru, node);
}
// If we get here, the cache is empty and the message is a branch.
// Merge the whole branch over.
else if(node == null) {
node = parent[key] = graph_node(roots[0], parent, message, key, 0);
}
return node;
}
},{"../lru/promote":87,"../support/replace-node":130,"../support/update-graph":137,"../types/path":140,"../types/sentinel":141,"../values/expires-now":143,"./graph-node":117,"./inc-generation":118,"./invalidate-node":120,"./is-expired":121,"./is-object":122,"./is-primitive":123,"./wrap-node":138}],126:[function(_dereq_,module,exports){
module.exports = Date.now;
},{}],127:[function(_dereq_,module,exports){
var inc_version = _dereq_("../support/inc-version");
var getBoundValue = _dereq_('../get/getBoundValue');
module.exports = function(options, model, error_selector) {
var bound = options.bound || (options.bound = model._path || []);
var root = options.root || (options.root = model._cache);
var nodes = options.nodes || (options.nodes = []);
var lru = options.lru || (options.lru = model._root);
options.expired || (options.expired = lru.expired);
options.errors || (options.errors = []);
options.requestedPaths || (options.requestedPaths = []);
options.optimizedPaths || (options.optimizedPaths = []);
options.requestedMissingPaths || (options.requestedMissingPaths = []);
options.optimizedMissingPaths || (options.optimizedMissingPaths = []);
options.boxed = model._boxed || false;
options.materialized = model._materialized;
options.errorsAsValues = model._treatErrorsAsValues || false;
options.headless = model._dataSource == null;
options.version = inc_version();
options.offset || (options.offset = 0);
options.error_selector = error_selector || model._errorSelector;
if(bound.length) {
nodes[0] = getBoundValue(model, bound).value;
} else {
nodes[0] = root;
}
return options;
};
},{"../get/getBoundValue":49,"../support/inc-version":119}],128:[function(_dereq_,module,exports){
module.exports = permute_keyset;
var __offset = _dereq_("../internal/offset");
var is_array = Array.isArray;
var is_object = _dereq_("./is-object");
function permute_keyset(key) {
if(is_array(key)) {
if(key[__offset] === undefined) {
key[__offset] = -1;
if(key.length == 0) {
return false;
}
}
if(++key[__offset] >= key.length) {
return permute_keyset(key[key[__offset] = -1]);
} else {
return true;
}
} else if(is_object(key)) {
if(key[__offset] === undefined) {
key[__offset] = (key.from || (key.from = 0)) - 1;
if(key.to === undefined) {
if(key.length === undefined) {
throw new Error("Range keysets must specify at least one index to retrieve.");
} else if(key.length === 0) {
return false;
}
key.to = key.from + (key.length || 1) - 1;
}
}
if(++key[__offset] > key.to) {
key[__offset] = key.from - 1;
return false;
}
return true;
}
return false;
}
},{"../internal/offset":72,"./is-object":122}],129:[function(_dereq_,module,exports){
var $path = _dereq_("../types/path");
var __parent = _dereq_("../internal/parent");
var unlink = _dereq_("./unlink");
var delete_back_refs = _dereq_("./delete-back-refs");
var splice = _dereq_("../lru/splice");
var is_object = _dereq_("./is-object");
module.exports = function(parent, node, key, lru) {
if(is_object(node)) {
var type = node.$type;
if(!!type) {
if(type == $path) { unlink(node); }
splice(lru, node);
}
delete_back_refs(node);
parent[key] = node[__parent] = undefined;
return true;
}
return false;
}
},{"../internal/parent":73,"../lru/splice":88,"../types/path":140,"./delete-back-refs":115,"./is-object":122,"./unlink":135}],130:[function(_dereq_,module,exports){
var transfer_back_refs = _dereq_("./transfer-back-refs");
var invalidate_node = _dereq_("./invalidate-node");
module.exports = function(parent, node, replacement, key, lru) {
if(node != null && node !== replacement && typeof node == "object") {
transfer_back_refs(node, replacement);
invalidate_node(parent, node, key, lru);
}
return parent[key] = replacement;
}
},{"./invalidate-node":120,"./transfer-back-refs":131}],131:[function(_dereq_,module,exports){
var __ref = _dereq_("../internal/ref");
var __context = _dereq_("../internal/context");
var __refs_length = _dereq_("../internal/refs-length");
module.exports = function(node, dest) {
var nodeRefsLength = node[__refs_length] || 0,
destRefsLength = dest[__refs_length] || 0,
i = -1, ref;
while(++i < nodeRefsLength) {
ref = node[__ref + i];
if(ref !== undefined) {
ref[__context] = dest;
dest[__ref + (destRefsLength + i)] = ref;
node[__ref + i] = undefined;
}
}
dest[__refs_length] = nodeRefsLength + destRefsLength;
node[__refs_length] = ref = undefined;
}
},{"../internal/context":66,"../internal/ref":77,"../internal/refs-length":78}],132:[function(_dereq_,module,exports){
var $error = _dereq_("../types/error");
var promote = _dereq_("../lru/promote");
var array_clone = _dereq_("./array-clone");
module.exports = function(roots, node, type, path) {
if(node == null) {
return false;
}
promote(roots.lru, node);
if(type != $error || roots.errorsAsValues) {
return false;
}
roots.errors.push({ path: array_clone(path), value: node.value });
return true;
};
},{"../lru/promote":87,"../types/error":139,"./array-clone":104}],133:[function(_dereq_,module,exports){
var $sentinel = _dereq_("../types/sentinel");
var clone_misses = _dereq_("./clone-missing-path-maps");
var is_expired = _dereq_("./is-expired");
module.exports = function(roots, node, type, pathmap, keys_stack, depth, requested, optimized) {
var dematerialized = !roots.materialized;
if(node == null && dematerialized) {
clone_misses(roots, pathmap, keys_stack, depth, requested, optimized);
return true;
} else if(!!type) {
if(type == $sentinel && node.value === undefined && dematerialized && !roots.boxed) {
return true;
} else if(is_expired(roots, node)) {
clone_misses(roots, pathmap, keys_stack, depth, requested, optimized);
return true;
}
}
return false;
};
},{"../types/sentinel":141,"./clone-missing-path-maps":108,"./is-expired":121}],134:[function(_dereq_,module,exports){
var $sentinel = _dereq_("../types/sentinel");
var clone_misses = _dereq_("./clone-missing-path-sets");
var is_expired = _dereq_("./is-expired");
module.exports = function(roots, node, type, pathset, depth, requested, optimized) {
var dematerialized = !roots.materialized;
if(node == null && dematerialized) {
clone_misses(roots, pathset, depth, requested, optimized);
return true;
} else if(!!type) {
if(type == $sentinel && node.value === undefined && dematerialized && !roots.boxed) {
return true;
} else if(is_expired(roots, node)) {
clone_misses(roots, pathset, depth, requested, optimized);
return true;
}
}
return false;
};
},{"../types/sentinel":141,"./clone-missing-path-sets":109,"./is-expired":121}],135:[function(_dereq_,module,exports){
var __ref = _dereq_("../internal/ref");
var __context = _dereq_("../internal/context");
var __ref_index = _dereq_("../internal/ref-index");
var __refs_length = _dereq_("../internal/refs-length");
module.exports = function(ref) {
var destination = ref[__context];
if(destination) {
var i = (ref[__ref_index] || 0) - 1,
n = (destination[__refs_length] || 0) - 1;
while(++i <= n) {
destination[__ref + i] = destination[__ref + (i + 1)];
}
destination[__refs_length] = n;
ref[__ref_index] = ref[__context] = destination = undefined;
}
}
},{"../internal/context":66,"../internal/ref":77,"../internal/ref-index":76,"../internal/refs-length":78}],136:[function(_dereq_,module,exports){
module.exports = update_back_refs;
var __ref = _dereq_("../internal/ref");
var __parent = _dereq_("../internal/parent");
var __version = _dereq_("../internal/version");
var __generation = _dereq_("../internal/generation");
var __refs_length = _dereq_("../internal/refs-length");
var generation = _dereq_("./inc-generation");
function update_back_refs(node, version) {
if(node && node[__version] !== version) {
node[__version] = version;
node[__generation] = generation();
update_back_refs(node[__parent], version);
var i = -1, n = node[__refs_length] || 0;
while(++i < n) {
update_back_refs(node[__ref + i], version);
}
}
return node;
}
},{"../internal/generation":67,"../internal/parent":73,"../internal/ref":77,"../internal/refs-length":78,"../internal/version":80,"./inc-generation":118}],137:[function(_dereq_,module,exports){
var __key = _dereq_("../internal/key");
var __version = _dereq_("../internal/version");
var __parent = _dereq_("../internal/parent");
var remove_node = _dereq_("./remove-node");
var update_back_refs = _dereq_("./update-back-refs");
module.exports = function(node, offset, version, lru) {
var child;
while(child = node) {
node = child[__parent];
if((child.$size = (child.$size || 0) - offset) <= 0 && node != null) {
remove_node(node, child, child[__key], lru);
} else if(child[__version] !== version) {
update_back_refs(child, version);
}
}
}
},{"../internal/key":70,"../internal/parent":73,"../internal/version":80,"./remove-node":129,"./update-back-refs":136}],138:[function(_dereq_,module,exports){
var $path = _dereq_("../types/path");
var $error = _dereq_("../types/error");
var $sentinel = _dereq_("../types/sentinel");
var now = _dereq_("./now");
var clone = _dereq_("./clone");
var is_array = Array.isArray;
var is_object = _dereq_("./is-object");
module.exports = function(node, type, value) {
var dest = node, size = 0;
if(!!type) {
dest = clone(node);
size = dest.$size;
// }
// if(type == $path) {
// dest = clone(node);
// size = 50 + (value.length || 1);
// } else if(is_object(node) && (type || (type = node.$type))) {
// dest = clone(node);
// size = dest.$size;
} else {
dest = { value: value };
type = $sentinel;
}
if(size <= 0 || size == null) {
switch(typeof value) {
case "number":
case "boolean":
case "function":
case "undefined":
size = 51;
break;
case "object":
size = is_array(value) && (50 + value.length) || 51;
break;
case "string":
size = 50 + value.length;
break;
}
}
var expires = is_object(node) && node.$expires || undefined;
if(typeof expires === "number" && expires < 0) {
dest.$expires = now() + (expires * -1);
}
dest.$type = type;
dest.$size = size;
return dest;
}
},{"../types/error":139,"../types/path":140,"../types/sentinel":141,"./clone":113,"./is-object":122,"./now":126}],139:[function(_dereq_,module,exports){
module.exports = "error";
},{}],140:[function(_dereq_,module,exports){
module.exports = "ref";
},{}],141:[function(_dereq_,module,exports){
module.exports = "sentinel";
},{}],142:[function(_dereq_,module,exports){
module.exports = 1;
},{}],143:[function(_dereq_,module,exports){
module.exports = 0;
},{}],144:[function(_dereq_,module,exports){
module.exports = walk_path_map;
var prefix = _dereq_("../internal/prefix");
var $path = _dereq_("../types/path");
var walk_reference = _dereq_("./walk-reference");
var array_slice = _dereq_("../support/array-slice");
var array_clone = _dereq_("../support/array-clone");
var array_append = _dereq_("../support/array-append");
var is_expired = _dereq_("../support/is-expired");
var is_primitive = _dereq_("../support/is-primitive");
var is_object = _dereq_("../support/is-object");
var is_array = Array.isArray;
var promote = _dereq_("../lru/promote");
function walk_path_map(onNode, onEdge, pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(is_primitive(pathmap) || is_primitive(node)) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[0] = parents[0] = roots[0];
nodes[1] = parents[1] = roots[1];
nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, true, null, keyset, false);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
if(type != null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keys_stack[depth] = Object.keys(pathmap);
if(keys.length == 0) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var is_outer_keyset = keys.length > 1;
for(var i = -1, n = keys.length; ++i < n;) {
var inner_key = keys[i];
if((inner_key[0] === prefix) || (inner_key[0] === "$")) {
continue;
}
var inner_keyset = is_outer_keyset ? inner_key : keyset;
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var pathmap2 = pathmap[inner_key];
var requested2, optimized2, is_branch;
var has_child_key = false;
var is_branch = is_object(pathmap2) && !pathmap2.$type;// && !is_array(pathmap2);
if(is_branch) {
for(child_key in pathmap2) {
if((child_key[0] === prefix) || (child_key[0] === "$")) {
continue;
}
child_key = pathmap2.hasOwnProperty(child_key);
break;
}
is_branch = child_key === true;
}
if(inner_key == "null") {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
inner_key = key;
inner_keyset = keyset;
pathmap2 = pathmap;
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
if(is_branch) {
walk_path_map(onNode, onEdge,
pathmap2, keys_stack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
} else {
onEdge(pathmap2, keys_stack, depth, roots, parents2, nodes2, requested2, optimized2, inner_key, inner_keyset);
}
}
}
},{"../internal/prefix":74,"../lru/promote":87,"../support/array-append":103,"../support/array-clone":104,"../support/array-slice":105,"../support/is-expired":121,"../support/is-object":122,"../support/is-primitive":123,"../types/path":140,"./walk-reference":148}],145:[function(_dereq_,module,exports){
module.exports = walk_path_map;
var prefix = _dereq_("../internal/prefix");
var __context = _dereq_("../internal/context");
var $path = _dereq_("../types/path");
var walk_reference = _dereq_("./walk-reference");
var array_slice = _dereq_("../support/array-slice");
var array_clone = _dereq_("../support/array-clone");
var array_append = _dereq_("../support/array-append");
var is_expired = _dereq_("../support/is-expired");
var is_primitive = _dereq_("../support/is-primitive");
var is_object = _dereq_("../support/is-object");
var is_array = Array.isArray;
var promote = _dereq_("../lru/promote");
function walk_path_map(onNode, onEdge, pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(is_primitive(pathmap) || is_primitive(node)) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if(node != null) {
type = node.$type;
optimized = array_clone(reference);
nodes[0] = node;
} else {
nodes[0] = parents[0] = roots[0];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, true, null, keyset, false);
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
}
if(type != null) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keys_stack[depth] = Object.keys(pathmap);
if(keys.length == 0) {
return onEdge(pathmap, keys_stack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var is_outer_keyset = keys.length > 1;
for(var i = -1, n = keys.length; ++i < n;) {
var inner_key = keys[i];
if((inner_key[0] === prefix) || (inner_key[0] === "$")) {
continue;
}
var inner_keyset = is_outer_keyset ? inner_key : keyset;
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var pathmap2 = pathmap[inner_key];
var requested2, optimized2, is_branch;
var child_key = false;
var is_branch = is_object(pathmap2) && !pathmap2.$type;// && !is_array(pathmap2);
if(is_branch) {
for(child_key in pathmap2) {
if((child_key[0] === prefix) || (child_key[0] === "$")) {
continue;
}
child_key = pathmap2.hasOwnProperty(child_key);
break;
}
is_branch = child_key === true;
}
if(inner_key == "null") {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
inner_key = key;
inner_keyset = keyset;
pathmap2 = pathmap;
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
if(is_branch) {
walk_path_map(onNode, onEdge,
pathmap2, keys_stack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
} else {
onEdge(pathmap2, keys_stack, depth, roots, parents2, nodes2, requested2, optimized2, inner_key, inner_keyset);
}
}
}
},{"../internal/context":66,"../internal/prefix":74,"../lru/promote":87,"../support/array-append":103,"../support/array-clone":104,"../support/array-slice":105,"../support/is-expired":121,"../support/is-object":122,"../support/is-primitive":123,"../types/path":140,"./walk-reference":148}],146:[function(_dereq_,module,exports){
module.exports = walk_path_set;
var $path = _dereq_("../types/path");
var empty_array = new Array(0);
var walk_reference = _dereq_("./walk-reference");
var array_slice = _dereq_("../support/array-slice");
var array_clone = _dereq_("../support/array-clone");
var array_append = _dereq_("../support/array-append");
var is_expired = _dereq_("../support/is-expired");
var is_primitive = _dereq_("../support/is-primitive");
var is_object = _dereq_("../support/is-object");
var keyset_to_key = _dereq_("../support/keyset-to-key");
var permute_keyset = _dereq_("../support/permute-keyset");
var promote = _dereq_("../lru/promote");
function walk_path_set(onNode, onEdge, pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(depth >= pathset.length || is_primitive(node)) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[0] = parents[0] = roots[0];
nodes[1] = parents[1] = roots[1];
nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathset, roots, parents, nodes, requested, optimized, true, false, null, keyset, false);
return onEdge(pathset, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
if(type != null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outer_key = pathset[depth];
var is_outer_keyset = is_object(outer_key);
var is_branch = depth < pathset.length - 1;
var run_once = false;
while(is_outer_keyset && permute_keyset(outer_key) && (run_once = true) || (run_once = !run_once)) {
var inner_key, inner_keyset;
if(is_outer_keyset === true) {
inner_key = keyset_to_key(outer_key, true);
inner_keyset = inner_key;
} else {
inner_key = outer_key;
inner_keyset = keyset;
}
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var requested2, optimized2;
if(inner_key == null) {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
// optimized2 = optimized;
inner_key = key;
inner_keyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
walk_path_set(onNode, onEdge,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
}
}
},{"../lru/promote":87,"../support/array-append":103,"../support/array-clone":104,"../support/array-slice":105,"../support/is-expired":121,"../support/is-object":122,"../support/is-primitive":123,"../support/keyset-to-key":124,"../support/permute-keyset":128,"../types/path":140,"./walk-reference":148}],147:[function(_dereq_,module,exports){
module.exports = walk_path_set;
var prefix = _dereq_("../internal/prefix");
var __context = _dereq_("../internal/context");
var $path = _dereq_("../types/path");
var empty_array = new Array(0);
var walk_reference = _dereq_("./walk-reference");
var array_slice = _dereq_("../support/array-slice");
var array_clone = _dereq_("../support/array-clone");
var array_append = _dereq_("../support/array-append");
var is_expired = _dereq_("../support/is-expired");
var is_primitive = _dereq_("../support/is-primitive");
var is_object = _dereq_("../support/is-object");
var keyset_to_key = _dereq_("../support/keyset-to-key");
var permute_keyset = _dereq_("../support/permute-keyset");
var promote = _dereq_("../lru/promote");
function walk_path_set(onNode, onEdge, pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, is_keyset) {
var node = nodes[0];
if(depth >= pathset.length || is_primitive(node)) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while(type === $path) {
if(is_expired(roots, node)) {
nodes[0] = undefined;
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if(node != null) {
type = node.$type;
optimized = array_clone(reference);
nodes[0] = node;
} else {
nodes[0] = parents[0] = roots[0];
// nodes[1] = parents[1] = roots[1];
// nodes[2] = parents[2] = roots[2];
walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[0];
if(node == null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else if(is_primitive(node) || ((type = node.$type) && type != $path)) {
onNode(pathset, roots, parents, nodes, requested, optimized, true, false, null, keyset, false);
return onEdge(pathset, depth, roots, parents, nodes, array_append(requested, null), optimized, key, keyset);
}
}
}
if(type != null) {
return onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outer_key = pathset[depth];
var is_outer_keyset = is_object(outer_key);
var is_branch = depth < pathset.length - 1;
var run_once = false;
while(is_outer_keyset && permute_keyset(outer_key) && (run_once = true) || (run_once = !run_once)) {
var inner_key, inner_keyset;
if(is_outer_keyset === true) {
inner_key = keyset_to_key(outer_key, true);
inner_keyset = inner_key;
} else {
inner_key = outer_key;
inner_keyset = keyset;
}
var nodes2 = array_clone(nodes);
var parents2 = array_clone(parents);
var requested2, optimized2;
if(inner_key == null) {
requested2 = array_append(requested, null);
optimized2 = array_clone(optimized);
// optimized2 = optimized;
inner_key = key;
inner_keyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, null, inner_keyset, false);
} else {
requested2 = array_append(requested, inner_key);
optimized2 = array_append(optimized, inner_key);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, true, is_branch, inner_key, inner_keyset, is_outer_keyset);
}
walk_path_set(onNode, onEdge,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
inner_key, inner_keyset, is_outer_keyset
);
}
}
},{"../internal/context":66,"../internal/prefix":74,"../lru/promote":87,"../support/array-append":103,"../support/array-clone":104,"../support/array-slice":105,"../support/is-expired":121,"../support/is-object":122,"../support/is-primitive":123,"../support/keyset-to-key":124,"../support/permute-keyset":128,"../types/path":140,"./walk-reference":148}],148:[function(_dereq_,module,exports){
module.exports = walk_reference;
var prefix = _dereq_("../internal/prefix");
var __ref = _dereq_("../internal/ref");
var __context = _dereq_("../internal/context");
var __ref_index = _dereq_("../internal/ref-index");
var __refs_length = _dereq_("../internal/refs-length");
var is_object = _dereq_("../support/is-object");
var is_primitive = _dereq_("../support/is-primitive");
var array_slice = _dereq_("../support/array-slice");
var array_append = _dereq_("../support/array-append");
function walk_reference(onNode, container, reference, roots, parents, nodes, requested, optimized) {
optimized.length = 0;
var index = -1;
var count = reference.length;
var node, key, keyset;
while(++index < count) {
node = nodes[0];
if(node == null) {
return nodes;
} else if(is_primitive(node) || node.$type) {
onNode(reference, roots, parents, nodes, requested, optimized, false, false, keyset, null, false);
return nodes;
}
do {
key = reference[index];
if(key != null) {
keyset = key;
optimized.push(key);
onNode(reference, roots, parents, nodes, requested, optimized, false, index < count - 1, key, null, false);
break;
}
} while(++index < count);
}
node = nodes[0];
if(is_object(node) && container[__context] !== node) {
var backrefs = node[__refs_length] || 0;
node[__refs_length] = backrefs + 1;
node[__ref + backrefs] = container;
container[__context] = node;
container[__ref_index] = backrefs;
}
return nodes;
}
},{"../internal/context":66,"../internal/prefix":74,"../internal/ref":77,"../internal/ref-index":76,"../internal/refs-length":78,"../support/array-append":103,"../support/array-slice":105,"../support/is-object":122,"../support/is-primitive":123}],149:[function(_dereq_,module,exports){
var falcor = _dereq_('./lib/falcor');
var get = _dereq_('./lib/get');
var set = _dereq_('./lib/set');
var inv = _dereq_('./lib/invalidate');
var prototype = falcor.Model.prototype;
prototype._getBoundValue = get.getBoundValue;
prototype._getValueSync = get.getValueSync;
prototype._getPathSetsAsValues = get.getAsValues;
prototype._getPathSetsAsJSON = get.getAsJSON;
prototype._getPathSetsAsPathMap = get.getAsPathMap;
prototype._getPathSetsAsJSONG = get.getAsJSONG;
prototype._getPathMapsAsValues = get.getAsValues;
prototype._getPathMapsAsJSON = get.getAsJSON;
prototype._getPathMapsAsPathMap = get.getAsPathMap;
prototype._getPathMapsAsJSONG = get.getAsJSONG;
prototype._setPathSetsAsJSON = set.setPathSetsAsJSON;
prototype._setPathSetsAsJSONG = set.setPathSetsAsJSONG;
prototype._setPathSetsAsPathMap = set.setPathSetsAsPathMap;
prototype._setPathSetsAsValues = set.setPathSetsAsValues;
prototype._setPathMapsAsJSON = set.setPathMapsAsJSON;
prototype._setPathMapsAsJSONG = set.setPathMapsAsJSONG;
prototype._setPathMapsAsPathMap = set.setPathMapsAsPathMap;
prototype._setPathMapsAsValues = set.setPathMapsAsValues;
prototype._setJSONGsAsJSON = set.setJSONGsAsJSON;
prototype._setJSONGsAsJSONG = set.setJSONGsAsJSONG;
prototype._setJSONGsAsPathMap = set.setJSONGsAsPathMap;
prototype._setJSONGsAsValues = set.setJSONGsAsValues;
prototype._invPathSetsAsJSON = inv.invPathSetsAsJSON;
prototype._invPathSetsAsJSONG = inv.invPathSetsAsJSONG;
prototype._invPathSetsAsPathMap = inv.invPathSetsAsPathMap;
prototype._invPathSetsAsValues = inv.invPathSetsAsValues;
// prototype._setCache = get.setCache;
prototype._setCache = set.setCache;
module.exports = falcor;
},{"./lib/falcor":5,"./lib/get":52,"./lib/invalidate":81,"./lib/set":89}]},{},[1])
(1)
});
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],149:[function(require,module,exports){
var falcor = require('falcor');
var Observable = falcor.Observable;
function XMLHttpSource(jsongUrl, timeout) {
this._jsongUrl = jsongUrl;
this._timeout = timeout || 15000;
}
XMLHttpSource.prototype = {
/**
* @inheritDoc DataSource#get
*/
get: function (pathSet) {
var method = 'GET';
var config = buildQueryObject(this._jsongUrl, method, {
path: pathSet,
method: 'get'
});
return request(method, config);
},
/**
* @inheritDoc DataSource#set
*/
set: function () {
// TODO: What to send what to send
},
/**
* @inheritDoc DataSource#call
*/
call: function (callPath, args, pathSuffix, paths) {
var method = 'GET';
var queryData = [];
args = args || [];
pathSuffix = pathSuffix || [];
paths = paths || [];
paths.forEach(function (path) {
queryData.push('path=' + encodeURIComponent(JSON.stringify(path)));
});
queryData.push('method=call');
queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
if (Array.isArray(args)) {
args.forEach(function (value) {
queryData.push('param=' + encodeURIComponent(JSON.stringify(value)));
});
}
if (Array.isArray(pathSuffix)) {
pathSuffix.forEach(function (value) {
queryData.push('pathSuffix=' + encodeURIComponent(JSON.stringify(value)));
});
}
var config = buildQueryObject(this._jsongUrl, method, queryData.join('&'));
return request(method, config);
}
};
function request(method, config) {
return Observable.create(function (observer) {
// i have to actual work now :(
var xhr = new XMLHttpRequest();
// Link the response methods
xhr.onload = onXhrLoad.bind(null, observer, xhr);
xhr.onerror = onXhrError.bind(null, observer, xhr);
xhr.ontimeout = onXhrTimeout.bind(null, observer, xhr);
// Sets information
xhr.timeout = config.timeout;
// Anything but explicit false results in true.
xhr.withCredentials = !(config.withCredentials === false);
xhr.responseType = 'json';
// Takes the url and opens the connection
xhr.open(method, config.url);
// Fills the request headers
var requestHeaders = config.requestHeaders || {};
var keys = Object.keys(requestHeaders);
keys.forEach(function (k) {
xhr.setRequestHeader(k, requestHeaders[k]);
});
// Sends the request.
xhr.send(config.data);
return function () {
// TODO: Dispose of request.
};
});
}
/*
* General handling of a successfully completed request (that had a 200 response code)
*/
function _handleXhrComplete(observer, data) {
observer.onNext(data);
observer.onCompleted();
}
/*
* General handling of ultimate failure (after appropriate retries)
*/
function _handleXhrError(observer, textStatus, errorThrown) {
if (!errorThrown) {
errorThrown = new Error(textStatus);
}
observer.onError(errorThrown);
}
function onXhrLoad(observer, xhr) {
var status,
responseData,
responseObject;
// If there's no observer, the request has been (or is being) cancelled.
if (xhr && observer) {
status = xhr.status;
responseData = xhr.responseText;
if (status >= 200 && status <= 399) {
try {
responseData = JSON.parse(responseData || '');
} catch (e) {
_handleXhrError(observer, 'invalid json', e);
}
_handleXhrComplete(observer, responseData);
} else if (status === 401 || status === 403 || status === 407) {
_handleXhrError(observer, responseData);
} else if (status === 410) {
// TODO: Retry ?
_handleXhrError(observer, responseData);
} else if (status === 408 || status === 504) {
// TODO: Retry ?
_handleXhrError(observer, responseData);
} else {
_handleXhrError(observer, responseData || ('Response code ' + status));
}
}
}
function onXhrError(observer, xhr) {
_handleXhrError(observer, xhr.statusText || 'request error');
}
function onXhrTimeout(observer) {
_handleXhrError(observer, 'request timeout');
}
function buildQueryObject(url, method, queryData) {
var qData = [];
var keys;
var data = {url: url};
if (typeof queryData === 'string') {
qData.push(queryData);
} else {
keys = Object.keys(queryData);
keys.forEach(function (k) {
var value = typeof queryData[k] === 'object' ? JSON.stringify(queryData[k]) : queryData[k];
qData.push(k + '=' + value);
});
}
if (method === 'GET') {
data.url += '?' + qData.join('&');
} else {
data.data = qData.join('&');
}
return data;
}
module.exports = XMLHttpSource;
},{"falcor":148}],150:[function(require,module,exports){
var TokenTypes = {
token: 'token',
dotSeparator: '.',
commaSeparator: ',',
openingBracket: '[',
closingBracket: ']',
openingBrace: '{',
closingBrace: '}',
escape: '\\',
space: ' ',
quote: 'quote',
unknown: 'unknown'
};
module.exports = TokenTypes;
},{}],151:[function(require,module,exports){
module.exports = {
indexer: {
nested: 'Indexers cannot be nested.',
needQuotes: 'unquoted indexers must be numeric.',
empty: 'cannot have empty indexers.',
leadingDot: 'Indexers cannot have leading dots.',
leadingComma: 'Indexers cannot have leading comma.',
requiresComma: 'Indexers require commas between indexer args.'
},
range: {
precedingNaN: 'ranges must be preceded by numbers.',
suceedingNaN: 'ranges must be suceeded by numbers.'
},
quote: {
empty: 'cannot have empty quoted keys.',
illegalEscape: 'Invalid escape character. Only quotes are escapable.'
},
unexpectedToken: 'Unexpected token.',
throwError: function(err, state, token) {
if (token) {
throw err + ' -- ' + state.parseString + ' with next token: ' + token;
}
throw err + ' -- ' + state.parseString;
}
};
},{}],152:[function(require,module,exports){
var Tokenizer = require('./tokenizer');
var head = require('./parse-tree/head');
var parser = function parser(string, extendedRules) {
return head(new Tokenizer(string, extendedRules));
};
module.exports = parser;
// Constructs the paths from paths / pathValues that have strings.
// If it does not have a string, just moves the value into the return
// results.
parser.fromPathsOrPathValues = function(paths, ext) {
var out = [];
for (i = 0, len = paths.length; i < len; i++) {
// Is the path a string
if (typeof paths[i] === 'string') {
out[i] = parser(paths[i], ext);
}
// is the path a path value with a string value.
else if (typeof paths[i].path === 'string') {
out[i] = {
path: parser(paths[i].path, ext), value: paths[i].value
};
}
// just copy it over.
else {
out[i] = paths[i];
}
}
return out;
};
// If the argument is a string, this with convert, else just return
// the path provided.
parser.fromPath = function(path, ext) {
if (typeof path === 'string') {
return parser(path, ext);
}
return path;
};
},{"./parse-tree/head":153,"./tokenizer":157}],153:[function(require,module,exports){
var TokenTypes = require('./../TokenTypes');
var Expections = require('./../exceptions');
var indexer = require('./indexer');
/**
* The top level of the parse tree. This returns the generated path
* from the tokenizer.
*/
module.exports = function head(tokenizer) {
var token = tokenizer.next();
var first = true;
var state = {
parseString: ''
};
var out = [];
while (!token.done) {
// continue to build the parse string.
state.parseString += token.token;
switch (token.type) {
case TokenTypes.token:
out[out.length] = token.token;
break;
// dotSeparators at the top level have no meaning
case TokenTypes.dotSeparator:
if (first) {
// TODO: Fix me
throw 'ohh no!';
}
break;
// Spaces do nothing.
case TokenTypes.space:
// NOTE: Spaces at the top level are allowed.
// titlesById .summary is a valid path.
break;
// Its time to decend the parse tree.
case TokenTypes.openingBracket:
indexer(tokenizer, token, state, out);
break;
// TODO: Fix me
default:
throw 'ohh no!';
}
first = false;
// Keep cycling through the tokenizer.
token = tokenizer.next();
}
if (first) {
// TODO: Ohh no! Fix me
throw 'ohh no!';
}
return out;
};
},{"./../TokenTypes":150,"./../exceptions":151,"./indexer":154}],154:[function(require,module,exports){
var TokenTypes = require('./../TokenTypes');
var E = require('./../exceptions');
var idxE = E.indexer;
var range = require('./range');
var quote = require('./quote');
/**
* The indexer is all the logic that happens in between
* the '[', opening bracket, and ']' closing bracket.
*/
module.exports = function indexer(tokenizer, openingToken, state, out) {
var token = tokenizer.next();
var done = false;
var allowedMaxLength = 1;
// State variables
state.indexer = [];
while (!token.done) {
// continue to build the parse string.
state.parseString += token.token;
switch (token.type) {
case TokenTypes.token:
case TokenTypes.quote:
// ensures that token adders are properly delimited.
if (state.indexer.length === allowedMaxLength) {
E.throwError(idxE.requiresComma, state);
}
break;
}
switch (token.type) {
case TokenTypes.token:
var t = +token.token;
if (isNaN(t)) {
E.throwError(idxE.needQuotes, state);
}
state.indexer[state.indexer.length] = t;
break;
// dotSeparators at the top level have no meaning
case TokenTypes.dotSeparator:
if (!state.indexer.length) {
E.throwError(idxE.leadingDot, state);
}
range(tokenizer, token, state, out);
break;
// Spaces do nothing.
case TokenTypes.space:
break;
case TokenTypes.closingBracket:
done = true;
break;
// The quotes require their own tree due to what can be in it.
case TokenTypes.quote:
quote(tokenizer, token, state, out);
break;
// Its time to decend the parse tree.
case TokenTypes.openingBracket:
E.throwError(idxE.nested, state);
break;
case TokenTypes.commaSeparator:
++allowedMaxLength;
break;
default:
E.throwError(idxE.unexpectedToken, state);
}
// If done, leave loop
if (done) {
break;
}
// Keep cycling through the tokenizer.
token = tokenizer.next();
}
if (state.indexer.length === 0) {
E.throwError(idxE.empty, state);
}
// Remember, if an array of 1, keySets will be generated.
if (state.indexer.length === 1) {
state.indexer = state.indexer[0];
}
out[out.length] = state.indexer;
// Clean state.
state.indexer = undefined;
};
},{"./../TokenTypes":150,"./../exceptions":151,"./quote":155,"./range":156}],155:[function(require,module,exports){
var TokenTypes = require('./../TokenTypes');
var E = require('./../exceptions');
var quoteE = E.quote;
/**
* The indexer is all the logic that happens in between
* the '[', opening bracket, and ']' closing bracket.
*/
module.exports = function quote(tokenizer, openingToken, state, out) {
var token = tokenizer.next();
var innerToken = '';
var openingQuote = openingToken.token;
var escaping = false;
var done = false;
while (!token.done) {
// continue to build the parse string.
state.parseString += token.token;
switch (token.type) {
case TokenTypes.token:
case TokenTypes.space:
case TokenTypes.dotSeparator:
case TokenTypes.commaSeparator:
case TokenTypes.openingBracket:
case TokenTypes.closingBracket:
case TokenTypes.openingBrace:
case TokenTypes.closingBrace:
if (escaping) {
E.throwError(quoteE.illegalEscape, state);
}
innerToken += token.token;
break;
case TokenTypes.quote:
// the simple case. We are escaping
if (escaping) {
innerToken += token.token;
escaping = false;
}
// its not a quote that is the opening quote
else if (token.token !== openingQuote) {
innerToken += token.token;
}
// last thing left. Its a quote that is the opening quote
// therefore we must produce the inner token of the indexer.
else {
done = true;
}
break;
case TokenTypes.escape:
escaping = true;
break;
default:
E.throwError(E.unexpectedToken, state);
}
// If done, leave loop
if (done) {
break;
}
// Keep cycling through the tokenizer.
token = tokenizer.next();
}
if (innerToken.length === 0) {
E.throwError(quoteE.empty, state);
}
state.indexer[state.indexer.length] = innerToken;
};
},{"./../TokenTypes":150,"./../exceptions":151}],156:[function(require,module,exports){
var Tokenizer = require('./../tokenizer');
var TokenTypes = require('./../TokenTypes');
var E = require('./../exceptions');
/**
* The indexer is all the logic that happens in between
* the '[', opening bracket, and ']' closing bracket.
*/
module.exports = function range(tokenizer, openingToken, state, out) {
var token = tokenizer.peek();
var dotCount = 1;
var done = false;
var inclusive = true;
// Grab the last token off the stack. Must be an integer.
var idx = state.indexer.length - 1;
var from = Tokenizer.toNumber(state.indexer[idx]);
var to;
if (isNaN(from)) {
E.throwError(E.range.precedingNaN, state);
}
// Why is number checking so difficult in javascript.
while (!done && !token.done) {
switch (token.type) {
// dotSeparators at the top level have no meaning
case TokenTypes.dotSeparator:
if (dotCount === 3) {
E.throwError(E.unexpectedToken, state);
}
++dotCount;
if (dotCount === 3) {
inclusive = false;
}
break;
case TokenTypes.token:
// move the tokenizer forward and save to.
to = Tokenizer.toNumber(tokenizer.next().token);
// continue to build the parse string.
state.parseString += token.token;
// throw potential error.
if (isNaN(to)) {
E.throwError(E.range.suceedingNaN, state);
}
done = true;
break;
default:
done = true;
break;
}
// Keep cycling through the tokenizer. But ranges have to peek
// before they go to the next token since there is no 'terminating'
// character.
if (!done) {
tokenizer.next();
// continue to build the parse string.
state.parseString += token.token;
// go to the next token without consuming.
token = tokenizer.peek();
}
// break and remove state information.
else {
break;
}
}
state.indexer[idx] = {from: from, to: inclusive ? to : to - 1};
};
},{"./../TokenTypes":150,"./../exceptions":151,"./../tokenizer":157}],157:[function(require,module,exports){
var TokenTypes = require('./../TokenTypes');
var DOT_SEPARATOR = '.';
var COMMA_SEPARATOR = ',';
var OPENING_BRACKET = '[';
var CLOSING_BRACKET = ']';
var OPENING_BRACE = '{';
var CLOSING_BRACE = '}';
var ESCAPE = '\\';
var DOUBLE_OUOTES = '"';
var SINGE_OUOTES = "'";
var SPACE = " ";
var SPECIAL_CHARACTERS = '\\\'"[]., ';
var EXT_SPECIAL_CHARACTERS = '\\{}\'"[]., ';
var Tokenizer = module.exports = function(string, ext) {
this._string = string;
this._idx = -1;
this._extended = ext;
};
Tokenizer.prototype = {
/**
* grabs the next token either from the peek operation or generates the
* next token.
*/
next: function() {
var nextToken = this._nextToken ?
this._nextToken : getNext(this._string, this._idx, this._extended);
this._idx = nextToken.idx;
this._nextToken = false;
return nextToken.token;
},
/**
* will peak but not increment the tokenizer
*/
peek: function() {
var nextToken = this._nextToken ?
this._nextToken : getNext(this._string, this._idx, this._extended);
this._nextToken = nextToken;
return nextToken.token;
}
};
Tokenizer.toNumber = function toNumber(x) {
if (!isNaN(+x)) {
return +x;
}
return NaN;
};
function toOutput(token, type, done) {
return {
token: token,
done: done,
type: type
};
}
function getNext(string, idx, ext) {
var output = false;
var token = '';
var specialChars = ext ?
EXT_SPECIAL_CHARACTERS : SPECIAL_CHARACTERS;
do {
done = idx + 1 >= string.length;
if (done) {
break;
}
// we have to peek at the next token
var character = string[idx + 1];
if (character !== undefined &&
specialChars.indexOf(character) === -1) {
token += character;
++idx;
continue;
}
// The token to delimiting character transition.
else if (token.length) {
break;
}
++idx;
var type;
switch (character) {
case DOT_SEPARATOR:
type = TokenTypes.dotSeparator;
break;
case COMMA_SEPARATOR:
type = TokenTypes.commaSeparator;
break;
case OPENING_BRACKET:
type = TokenTypes.openingBracket;
break;
case CLOSING_BRACKET:
type = TokenTypes.closingBracket;
break;
case OPENING_BRACE:
type = TokenTypes.openingBrace;
break;
case CLOSING_BRACE:
type = TokenTypes.closingBrace;
break;
case SPACE:
type = TokenTypes.space;
break;
case DOUBLE_OUOTES:
case SINGE_OUOTES:
type = TokenTypes.quote;
break;
case ESCAPE:
type = TokenTypes.escape;
break;
default:
type = TokenTypes.unknown;
break;
}
output = toOutput(character, type, false);
break;
} while (!done);
if (!output && token.length) {
output = toOutput(token, TokenTypes.token, false);
}
if (!output) {
output = {done: true};
}
return {
token: output,
idx: idx
};
}
},{"./../TokenTypes":150}],158:[function(require,module,exports){
'use strict';
module.exports = require('./lib')
},{"./lib":163}],159:[function(require,module,exports){
'use strict';
var asap = require('asap/raw')
function noop() {};
// States:
//
// 0 - pending
// 1 - fulfilled with _value
// 2 - rejected with _value
// 3 - adopted the state of another promise, _value
//
// once the state is no longer pending (0) it is immutable
// All `_` prefixed properties will be reduced to `_{random number}`
// at build time to obfuscate them and discourage their use.
// We don't use symbols or Object.defineProperty to fully hide them
// because the performance isn't good enough.
// to avoid using try/catch inside critical functions, we
// extract them to here.
var LAST_ERROR = null;
var IS_ERROR = {};
function getThen(obj) {
try {
return obj.then;
} catch (ex) {
LAST_ERROR = ex;
return IS_ERROR;
}
}
function tryCallOne(fn, a) {
try {
return fn(a);
} catch (ex) {
LAST_ERROR = ex;
return IS_ERROR;
}
}
function tryCallTwo(fn, a, b) {
try {
fn(a, b);
} catch (ex) {
LAST_ERROR = ex;
return IS_ERROR;
}
}
module.exports = Promise;
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
if (typeof fn !== 'function') throw new TypeError('not a function')
this._71 = 0;
this._18 = null;
this._61 = [];
if (fn === noop) return;
doResolve(fn, this);
}
Promise.prototype._10 = function (onFulfilled, onRejected) {
var self = this;
return new this.constructor(function (resolve, reject) {
var res = new Promise(noop);
res.then(resolve, reject);
self._24(new Handler(onFulfilled, onRejected, res));
});
};
Promise.prototype.then = function(onFulfilled, onRejected) {
if (this.constructor !== Promise) return this._10(onFulfilled, onRejected);
var res = new Promise(noop);
this._24(new Handler(onFulfilled, onRejected, res));
return res;
};
Promise.prototype._24 = function(deferred) {
if (this._71 === 3) {
this._18._24(deferred);
return;
}
if (this._71 === 0) {
this._61.push(deferred);
return;
}
var state = this._71;
var value = this._18;
asap(function() {
var cb = state === 1 ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state === 1 ? deferred.promise._82(value) : deferred.promise._67(value))
return
}
var ret = tryCallOne(cb, value);
if (ret === IS_ERROR) {
deferred.promise._67(LAST_ERROR)
} else {
deferred.promise._82(ret)
}
});
};
Promise.prototype._82 = function(newValue) {
//Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === this) {
return this._67(new TypeError('A promise cannot be resolved with itself.'))
}
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = getThen(newValue);
if (then === IS_ERROR) {
return this._67(LAST_ERROR);
}
if (
then === this.then &&
newValue instanceof Promise &&
newValue._24 === this._24
) {
this._71 = 3;
this._18 = newValue;
for (var i = 0; i < this._61.length; i++) {
newValue._24(this._61[i]);
}
return;
} else if (typeof then === 'function') {
doResolve(then.bind(newValue), this)
return
}
}
this._71 = 1
this._18 = newValue
this._94()
}
Promise.prototype._67 = function (newValue) {
this._71 = 2
this._18 = newValue
this._94()
}
Promise.prototype._94 = function () {
for (var i = 0; i < this._61.length; i++)
this._24(this._61[i])
this._61 = null
}
function Handler(onFulfilled, onRejected, promise){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.promise = promise;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, promise) {
var done = false;
var res = tryCallTwo(fn, function (value) {
if (done) return
done = true
promise._82(value)
}, function (reason) {
if (done) return
done = true
promise._67(reason)
})
if (!done && res === IS_ERROR) {
done = true
promise._67(LAST_ERROR)
}
}
},{"asap/raw":167}],160:[function(require,module,exports){
'use strict';
var Promise = require('./core.js')
module.exports = Promise
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
setTimeout(function () {
throw err
}, 0)
})
}
},{"./core.js":159}],161:[function(require,module,exports){
'use strict';
//This file contains the ES6 extensions to the core Promises/A+ API
var Promise = require('./core.js')
var asap = require('asap/raw')
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Promise.prototype
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.all = function (arr) {
var args = Array.prototype.slice.call(arr)
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([])
var remaining = args.length
function res(i, val) {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then
if (typeof then === 'function') {
then.call(val, function (val) { res(i, val) }, reject)
return
}
}
args[i] = val
if (--remaining === 0) {
resolve(args);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i])
}
})
}
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":159,"asap/raw":167}],162:[function(require,module,exports){
'use strict';
var Promise = require('./core.js')
module.exports = Promise
Promise.prototype['finally'] = function (f) {
return this.then(function (value) {
return Promise.resolve(f()).then(function () {
return value
})
}, function (err) {
return Promise.resolve(f()).then(function () {
throw err
})
})
}
},{"./core.js":159}],163:[function(require,module,exports){
'use strict';
module.exports = require('./core.js')
require('./done.js')
require('./finally.js')
require('./es6-extensions.js')
require('./node-extensions.js')
},{"./core.js":159,"./done.js":160,"./es6-extensions.js":161,"./finally.js":162,"./node-extensions.js":164}],164:[function(require,module,exports){
'use strict';
//This file contains then/promise specific extensions that are only useful for node.js interop
var Promise = require('./core.js')
var asap = require('asap')
module.exports = Promise
/* Static Functions */
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
var res = fn.apply(self, args)
if (res && (typeof res === 'object' || typeof res === 'function') && typeof res.then === 'function') {
resolve(res)
}
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
var ctx = this
try {
return fn.apply(this, arguments).nodeify(callback, ctx)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback.call(ctx, ex)
})
}
}
}
}
Promise.prototype.nodeify = function (callback, ctx) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback.call(ctx, null, value)
})
}, function (err) {
asap(function () {
callback.call(ctx, err)
})
})
}
},{"./core.js":159,"asap":165}],165:[function(require,module,exports){
"use strict";
// rawAsap provides everything we need except exception management.
var rawAsap = require("./raw");
// RawTasks are recycled to reduce GC churn.
var freeTasks = [];
// We queue errors to ensure they are thrown in right order (FIFO).
// Array-as-queue is good enough here, since we are just dealing with exceptions.
var pendingErrors = [];
var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError);
function throwFirstError() {
if (pendingErrors.length) {
throw pendingErrors.shift();
}
}
/**
* Calls a task as soon as possible after returning, in its own event, with priority
* over other events like animation, reflow, and repaint. An error thrown from an
* event will not interrupt, nor even substantially slow down the processing of
* other events, but will be rather postponed to a lower priority event.
* @param {{call}} task A callable object, typically a function that takes no
* arguments.
*/
module.exports = asap;
function asap(task) {
var rawTask;
if (freeTasks.length) {
rawTask = freeTasks.pop();
} else {
rawTask = new RawTask();
}
rawTask.task = task;
rawAsap(rawTask);
}
// We wrap tasks with recyclable task objects. A task object implements
// `call`, just like a function.
function RawTask() {
this.task = null;
}
// The sole purpose of wrapping the task is to catch the exception and recycle
// the task object after its single use.
RawTask.prototype.call = function () {
try {
this.task.call();
} catch (error) {
if (asap.onerror) {
// This hook exists purely for testing purposes.
// Its name will be periodically randomized to break any code that
// depends on its existence.
asap.onerror(error);
} else {
// In a web browser, exceptions are not fatal. However, to avoid
// slowing down the queue of pending tasks, we rethrow the error in a
// lower priority turn.
pendingErrors.push(error);
requestErrorThrow();
}
} finally {
this.task = null;
freeTasks[freeTasks.length] = this;
}
};
},{"./raw":166}],166:[function(require,module,exports){
(function (global){
"use strict";
// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including IO, animation, reflow, and redraw
// events in browsers.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
module.exports = rawAsap;
function rawAsap(task) {
if (!queue.length) {
requestFlush();
flushing = true;
}
// Equivalent to push, but avoids a function call.
queue[queue.length] = task;
}
var queue = [];
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
var flushing = false;
// `requestFlush` is an implementation-specific method that attempts to kick
// off a `flush` event as quickly as possible. `flush` will attempt to exhaust
// the event queue before yielding to the browser's own event loop.
var requestFlush;
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
var index = 0;
// If a task schedules additional tasks recursively, the task queue can grow
// unbounded. To prevent memory exhaustion, the task queue will periodically
// truncate already-completed tasks.
var capacity = 1024;
// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
while (index < queue.length) {
var currentIndex = index;
// Advance the index before calling the task. This ensures that we will
// begin flushing on the next task the task throws an error.
index = index + 1;
queue[currentIndex].call();
// Prevent leaking memory for long chains of recursive calls to `asap`.
// If we call `asap` within tasks scheduled by `asap`, the queue will
// grow, but to avoid an O(n) walk for every task we execute, we don't
// shift tasks off the queue after they have been executed.
// Instead, we periodically shift 1024 tasks off the queue.
if (index > capacity) {
// Manually shift all values starting at the index back to the
// beginning of the queue.
for (var scan = 0; scan < index; scan++) {
queue[scan] = queue[scan + index];
}
queue.length -= index;
index = 0;
}
}
queue.length = 0;
index = 0;
flushing = false;
}
// `requestFlush` is implemented using a strategy based on data collected from
// every available SauceLabs Selenium web driver worker at time of writing.
// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593
// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that
// have WebKitMutationObserver but not un-prefixed MutationObserver.
// Must use `global` instead of `window` to work in both frames and web
// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop.
var BrowserMutationObserver = global.MutationObserver || global.WebKitMutationObserver;
// MutationObservers are desirable because they have high priority and work
// reliably everywhere they are implemented.
// They are implemented in all modern browsers.
//
// - Android 4-4.3
// - Chrome 26-34
// - Firefox 14-29
// - Internet Explorer 11
// - iPad Safari 6-7.1
// - iPhone Safari 7-7.1
// - Safari 6-7
if (typeof BrowserMutationObserver === "function") {
requestFlush = makeRequestCallFromMutationObserver(flush);
// MessageChannels are desirable because they give direct access to the HTML
// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera
// 11-12, and in web workers in many engines.
// Although message channels yield to any queued rendering and IO tasks, they
// would be better than imposing the 4ms delay of timers.
// However, they do not work reliably in Internet Explorer or Safari.
// Internet Explorer 10 is the only browser that has setImmediate but does
// not have MutationObservers.
// Although setImmediate yields to the browser's renderer, it would be
// preferrable to falling back to setTimeout since it does not have
// the minimum 4ms penalty.
// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and
// Desktop to a lesser extent) that renders both setImmediate and
// MessageChannel useless for the purposes of ASAP.
// https://github.com/kriskowal/q/issues/396
// Timers are implemented universally.
// We fall back to timers in workers in most engines, and in foreground
// contexts in the following browsers.
// However, note that even this simple case requires nuances to operate in a
// broad spectrum of browsers.
//
// - Firefox 3-13
// - Internet Explorer 6-9
// - iPad Safari 4.3
// - Lynx 2.8.7
} else {
requestFlush = makeRequestCallFromTimer(flush);
}
// `requestFlush` requests that the high priority event queue be flushed as
// soon as possible.
// This is useful to prevent an error thrown in a task from stalling the event
// queue if the exception handled by Node.js’s
// `process.on("uncaughtException")` or by a domain.
rawAsap.requestFlush = requestFlush;
// To request a high priority event, we induce a mutation observer by toggling
// the text of a text node between "1" and "-1".
function makeRequestCallFromMutationObserver(callback) {
var toggle = 1;
var observer = new BrowserMutationObserver(callback);
var node = document.createTextNode("");
observer.observe(node, {characterData: true});
return function requestCall() {
toggle = -toggle;
node.data = toggle;
};
}
// The message channel technique was discovered by Malte Ubl and was the
// original foundation for this library.
// http://www.nonblocking.io/2011/06/windownexttick.html
// Safari 6.0.5 (at least) intermittently fails to create message ports on a
// page's first load. Thankfully, this version of Safari supports
// MutationObservers, so we don't need to fall back in that case.
// function makeRequestCallFromMessageChannel(callback) {
// var channel = new MessageChannel();
// channel.port1.onmessage = callback;
// return function requestCall() {
// channel.port2.postMessage(0);
// };
// }
// For reasons explained above, we are also unable to use `setImmediate`
// under any circumstances.
// Even if we were, there is another bug in Internet Explorer 10.
// It is not sufficient to assign `setImmediate` to `requestFlush` because
// `setImmediate` must be called *by name* and therefore must be wrapped in a
// closure.
// Never forget.
// function makeRequestCallFromSetImmediate(callback) {
// return function requestCall() {
// setImmediate(callback);
// };
// }
// Safari 6.0 has a problem where timers will get lost while the user is
// scrolling. This problem does not impact ASAP because Safari 6.0 supports
// mutation observers, so that implementation is used instead.
// However, if we ever elect to use timers in Safari, the prevalent work-around
// is to add a scroll event listener that calls for a flush.
// `setTimeout` does not call the passed callback if the delay is less than
// approximately 7 in web workers in Firefox 8 through 18, and sometimes not
// even then.
function makeRequestCallFromTimer(callback) {
return function requestCall() {
// We dispatch a timeout with a specified delay of 0 for engines that
// can reliably accommodate that request. This will usually be snapped
// to a 4 milisecond delay, but once we're flushing, there's no delay
// between events.
var timeoutHandle = setTimeout(handleTimer, 0);
// However, since this timer gets frequently dropped in Firefox
// workers, we enlist an interval handle that will try to fire
// an event 20 times per second until it succeeds.
var intervalHandle = setInterval(handleTimer, 50);
function handleTimer() {
// Whichever timer succeeds will cancel both timers and
// execute the callback.
clearTimeout(timeoutHandle);
clearInterval(intervalHandle);
callback();
}
};
}
// This is for `asap.js` only.
// Its name will be periodically randomized to break any code that depends on
// its existence.
rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer;
// ASAP was originally a nextTick shim included in Q. This was factored out
// into this ASAP package. It was later adapted to RSVP which made further
// amendments. These decisions, particularly to marginalize MessageChannel and
// to capture the MutationObserver implementation in a closure, were integrated
// back into ASAP proper.
// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],167:[function(require,module,exports){
(function (process){
"use strict";
var domain; // The domain module is executed on demand
var hasSetImmediate = typeof setImmediate === "function";
// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including network IO events in Node.js.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
module.exports = rawAsap;
function rawAsap(task) {
if (!queue.length) {
requestFlush();
flushing = true;
}
// Avoids a function call
queue[queue.length] = task;
}
var queue = [];
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
var flushing = false;
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
var index = 0;
// If a task schedules additional tasks recursively, the task queue can grown
// unbounded. To prevent memory excaustion, the task queue will periodically
// truncate already-completed tasks.
var capacity = 1024;
// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
while (index < queue.length) {
var currentIndex = index;
// Advance the index before calling the task. This ensures that we will
// begin flushing on the next task the task throws an error.
index = index + 1;
queue[currentIndex].call();
// Prevent leaking memory for long chains of recursive calls to `asap`.
// If we call `asap` within tasks scheduled by `asap`, the queue will
// grow, but to avoid an O(n) walk for every task we execute, we don't
// shift tasks off the queue after they have been executed.
// Instead, we periodically shift 1024 tasks off the queue.
if (index > capacity) {
// Manually shift all values starting at the index back to the
// beginning of the queue.
for (var scan = 0; scan < index; scan++) {
queue[scan] = queue[scan + index];
}
queue.length -= index;
index = 0;
}
}
queue.length = 0;
index = 0;
flushing = false;
}
rawAsap.requestFlush = requestFlush;
function requestFlush() {
// Ensure flushing is not bound to any domain.
// It is not sufficient to exit the domain, because domains exist on a stack.
// To execute code outside of any domain, the following dance is necessary.
var parentDomain = process.domain;
if (parentDomain) {
if (!domain) {
// Lazy execute the domain module.
// Only employed if the user elects to use domains.
domain = require("domain");
}
domain.active = process.domain = null;
}
// `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
// cannot handle recursion.
// `requestFlush` will only be called recursively from `asap.js`, to resume
// flushing after an error is thrown into a domain.
// Conveniently, `setImmediate` was introduced in the same version
// `process.nextTick` started throwing recursion errors.
if (flushing && hasSetImmediate) {
setImmediate(flush);
} else {
process.nextTick(flush);
}
if (parentDomain) {
domain.active = process.domain = parentDomain;
}
}
}).call(this,require("FWaASH"))
},{"FWaASH":147,"domain":145}],168:[function(require,module,exports){
(function (process,global){
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
Error.call(this);
};
EmptyError.prototype = Error.prototype;
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
Error.call(this);
};
ObjectDisposedError.prototype = Error.prototype;
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Error.prototype;
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
Error.call(this);
};
NotSupportedError.prototype = Error.prototype;
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
Error.call(this);
};
NotImplementedError.prototype = Error.prototype;
var notImplemented = Rx.helpers.notImplemented = function () {
throw new NotImplementedError();
};
var notSupported = Rx.helpers.notSupported = function () {
throw new NotSupportedError();
};
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
tryCatchTarget = fn;
return tryCatcher;
}
function thrower(e) {
throw e;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
this.items[this.length] = undefined;
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
len = args.length;
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
for(i = 0; i < len; i++) {
if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.scheduleWithState(this, scheduleItem);
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
}
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState([state, action], invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
period = normalizeTime(period);
var s = state, id = root.setInterval(function () { s = action(s); }, period);
return disposableCreate(function () { root.clearInterval(id); });
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.dequeue();
!item.isCancelled() && item.invoke();
}
}
function scheduleNow(state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { return thrower(result.e); }
} else {
queue.enqueue(si);
}
return si.disposable;
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
currentScheduler.scheduleRequired = function () { return !queue; };
return currentScheduler;
}());
var scheduleMethod, clearMethod;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if (!!root.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
clearMethod = function (handle) {
delete tasksByHandle[handle];
};
function runTask(handle) {
if (currentlyRunning) {
localSetTimeout(function () { runTask(handle) }, 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunning = true;
var result = tryCatch(task)();
clearMethod(handle);
currentlyRunning = false;
if (result === errorObj) { return thrower(result.e); }
}
}
}
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false, oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (isFunction(setImmediate)) {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
setImmediate(function () { runTask(id); });
return id;
};
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
process.nextTick(function () { runTask(id); });
return id;
};
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
runTask(event.data.substring(MSG_PREFIX.length));
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
return id;
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel();
channel.port1.onmessage = function (e) { runTask(e.data); };
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
channel.port2.postMessage(id);
return id;
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
var id = nextHandle++;
tasksByHandle[id] = action;
scriptElement.onreadystatechange = function () {
runTask(id);
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
return id;
};
} else {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
localSetTimeout(function () {
runTask(id);
}, 0);
return id;
};
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this, dt = Scheduler.normalize(dueTime);
if (dt === 0) { return scheduler.scheduleWithState(state, action); }
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, value, exception, accept, acceptObservable, toString) {
this.kind = kind;
this.value = value;
this.exception = exception;
this._accept = accept;
this._acceptObservable = acceptObservable;
this.toString = toString;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(self, function (_, notification) {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept(onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString() { return 'OnNext(' + this.value + ')'; }
return function (value) {
return new Notification('N', value, null, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
return new Notification('E', null, e, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
return new Notification('C', null, null, _accept, _acceptObservable, toString);
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function(err) { o.onError(err); },
self)
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return observer.onError(ex);
}
if (currentItem.done) {
if (lastException !== null) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
if (selector) {
var selectorFn = bindCallback(selector, thisArg, 3);
}
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
Observer.prototype.makeSafe = function(disposable) {
return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (__super__) {
inherits(CheckedObserver, __super__);
function CheckedObserver(observer) {
__super__.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
var res = tryCatch(this._observer.onNext).call(this._observer, value);
this._state = 0;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
var res = tryCatch(this._observer.onError).call(this._observer, err);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
var res = tryCatch(this._observer.onCompleted).call(this._observer);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
}, source);
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
}, source);
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
var ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new ToArrayObserver(observer));
};
return ToArrayObservable;
}(ObservableBase));
function ToArrayObserver(observer) {
this.observer = observer;
this.a = [];
this.isStopped = false;
}
ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
ToArrayObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
}
};
ToArrayObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onNext(this.a);
this.observer.onCompleted();
}
};
ToArrayObserver.prototype.dispose = function () { this.isStopped = true; }
ToArrayObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(null, function () {
observer.onCompleted();
});
});
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, mapper, scheduler) {
this.iterable = iterable;
this.mapper = mapper;
this.scheduler = scheduler;
__super__.call(this);
}
FromObservable.prototype.subscribeCore = function (observer) {
var sink = new FromSink(observer, this);
return sink.run();
};
return FromObservable;
}(ObservableBase));
var FromSink = (function () {
function FromSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromSink.prototype.run = function () {
var list = Object(this.parent.iterable),
it = getIterable(list),
observer = this.observer,
mapper = this.parent.mapper;
function loopRecursive(i, recurse) {
try {
var next = it.next();
} catch (e) {
return observer.onError(e);
}
if (next.done) {
return observer.onCompleted();
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
return observer.onError(e);
}
}
observer.onNext(result);
recurse(i + 1);
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return FromSink;
}());
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromArraySink.prototype.run = function () {
var observer = this.observer, args = this.parent.args, len = args.length;
function loopRecursive(i, recurse) {
if (i < len) {
observer.onNext(args[i]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (o) {
var first = true;
return scheduler.scheduleRecursiveWithState(initialState, function (state, self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
hasResult && (result = resultSelector(state));
} catch (e) {
return o.onError(e);
}
if (hasResult) {
o.onNext(result);
self(state);
} else {
o.onCompleted();
}
});
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
/**
* Creates an Observable sequence from changes to an array using Array.observe.
* @param {Array} array An array to observe changes.
* @returns {Observable} An observable sequence containing changes to an array from Array.observe.
*/
Observable.ofArrayChanges = function(array) {
if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); }
if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') }
return new AnonymousObservable(function(observer) {
function observerFn(changes) {
for(var i = 0, len = changes.length; i < len; i++) {
observer.onNext(changes[i]);
}
}
Array.observe(array, observerFn);
return function () {
Array.unobserve(array, observerFn);
};
});
};
/**
* Creates an Observable sequence from changes to an object using Object.observe.
* @param {Object} obj An object to observe changes.
* @returns {Observable} An observable sequence containing changes to an object from Object.observe.
*/
Observable.ofObjectChanges = function(obj) {
if (obj == null) { throw new TypeError('object must not be null or undefined.'); }
if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') }
return new AnonymousObservable(function(observer) {
function observerFn(changes) {
for(var i = 0, len = changes.length; i < len; i++) {
observer.onNext(changes[i]);
}
}
Object.observe(obj, observerFn);
return function () {
Object.unobserve(obj, observerFn);
};
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = Rx.Scheduler.currentThread);
return new AnonymousObservable(function (observer) {
var keys = Object.keys(obj), len = keys.length;
return scheduler.scheduleRecursiveWithState(0, function (idx, self) {
if (idx < len) {
var key = keys[idx];
observer.onNext([key, obj[key]]);
self(idx + 1);
} else {
observer.onCompleted();
}
});
});
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.count = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.count, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just' or browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (o) {
return scheduler.scheduleWithState(value, function(_,v) {
o.onNext(v);
o.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(error);
});
});
};
/** @deprecated use #some instead */
Observable.throwException = function () {
//deprecate('throwException', 'throwError');
return Observable.throwError.apply(null, arguments);
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) {
try {
var result = handler(e);
} catch (ex) {
return o.onError(ex);
}
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(o));
}, function (x) { o.onCompleted(x); }));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop();
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (o) {
var n = args.length,
falseFactory = function () { return false; },
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
var res = resultSelector.apply(null, values);
} catch (e) {
return o.onError(e);
}
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}
function done (i) {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { o.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return enumerableOf(args).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = observableProto.concatObservable = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function () {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
this.isStopped = false;
}
MergeObserver.prototype.handleSubscribe = function (xs) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(xs) && (xs = observableFromPromise(xs));
sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
};
MergeObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.done = true;
this.activeCount === 0 && this.o.onCompleted();
}
};
MergeObserver.prototype.dispose = function() { this.isStopped = true; };
MergeObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
var parent = this.parent;
parent.g.remove(this.sad);
if (parent.q.length > 0) {
parent.handleSubscribe(parent.q.shift());
} else {
parent.activeCount--;
parent.done && parent.activeCount === 0 && parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
return typeof maxConcurrentOrOther !== 'number' ?
observableMerge(this, maxConcurrentOrOther) :
new MergeObservable(this, maxConcurrentOrOther);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
var MergeAllObservable = (function (__super__) {
inherits(MergeAllObservable, __super__);
function MergeAllObservable(source) {
this.source = source;
__super__.call(this);
}
MergeAllObservable.prototype.subscribeCore = function (observer) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
return g;
};
return MergeAllObservable;
}(ObservableBase));
var MergeAllObserver = (function() {
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.isStopped = false;
this.done = false;
}
MergeAllObserver.prototype.onNext = function(innerSource) {
if(this.isStopped) { return; }
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad)));
};
MergeAllObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeAllObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.done = true;
this.g.length === 1 && this.o.onCompleted();
}
};
MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
MergeAllObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, g, sad) {
this.parent = parent;
this.g = g;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
this.isStopped = true;
parent.g.remove(this.sad);
parent.done && parent.g.length === 1 && parent.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeAllObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = observableProto.mergeObservable = function () {
return new MergeAllObservable(this);
};
var CompositeError = Rx.CompositeError = function(errors) {
this.name = "NotImplementedError";
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
}
CompositeError.prototype = Error.prototype;
/**
* Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
* receive all successfully emitted items from all of the source Observables without being interrupted by
* an error notification from one of them.
*
* This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
* error via the Observer's onError, mergeDelayError will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* @param {Array | Arguments} args Arguments or an array to merge.
* @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
*/
Observable.mergeDelayError = function() {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
var len = arguments.length;
args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
var source = observableOf(null, args);
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
isStopped = false,
errors = [];
function setCompletion() {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
group.add(m);
m.setDisposable(source.subscribe(
function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) { o.onNext(x); },
function (e) {
errors.push(e);
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
},
function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
}));
},
function (e) {
errors.push(e);
isStopped = true;
group.length === 1 && setCompletion();
},
function () {
isStopped = true;
group.length === 1 && setCompletion();
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(o),
other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop)
);
}, source);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
*
* @example
* 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop(), source = this;
if (typeof source === 'undefined') {
throw new Error('Source observable not found for withLatestFrom().');
}
if (typeof resultSelector !== 'function') {
throw new Error('withLatestFrom() expects a resultSelector function.');
}
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, observer.onError.bind(observer), function () {}));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var res;
var allValues = [x].concat(values);
if (!hasValueAll) return;
try {
res = resultSelector.apply(null, allValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
}, observer.onError.bind(observer), function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
return observer.onError(e);
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, function (e) { observer.onError(e); }, function () { observer.onCompleted(); });
}, first);
}
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var parent = this, resultSelector = args.pop();
args.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources;
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
var len = arguments.length;
sources = new Array(len);
for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
}
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (o) { return source.subscribe(o); }, this);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var key = value;
if (keySelector) {
try {
key = keySelector(value);
} catch (e) {
o.onError(e);
return;
}
}
if (hasCurrentKey) {
try {
var comparerEquals = comparer(currentKey, key);
} catch (e) {
o.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
return source.subscribe(function (x) {
try {
tapObserver.onNext(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
try {
tapObserver.onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}, function () {
try {
tapObserver.onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
});
}, this);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
o.onNext(accumulation);
},
function (e) { o.onError(e); },
function () {
!hasValue && hasSeed && o.onNext(seed);
o.onCompleted();
}
);
}, source);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
o.onNext(q);
o.onCompleted();
});
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new ArgumentOutOfRangeError(); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
function concatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this,
onNextFunc = bindCallback(onNext, thisArg, 2),
onErrorFunc = bindCallback(onError, thisArg, 1),
onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNextFunc(x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onErrorFunc(err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompletedFunc();
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
},
function (e) { observer.onError(e); },
function () {
!found && observer.onNext(defaultValue);
observer.onCompleted();
});
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
}
hashSet.push(key) && o.onNext(x);
},
function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [comparer] Used to determine whether the objects are equal.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, comparer) {
return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) {
var source = this;
elementSelector || (elementSelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
function handleError(e) { return function (item) { item.onError(e); }; }
var map = new Dictionary(0, comparer),
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
var fireNewMapEntry = false,
writer = map.tryGetValue(key);
if (!writer) {
writer = new Subject();
map.set(key, writer);
fireNewMapEntry = true;
}
if (fireNewMapEntry) {
var group = new GroupedObservable(key, writer, refCountDisposable),
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(group);
var md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
map.remove(key) && writer.onCompleted();
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(
noop,
function (exn) {
map.getValues().forEach(handleError(exn));
observer.onError(exn);
},
expire)
);
}
var element;
try {
element = elementSelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
map.getValues().forEach(handleError(ex));
observer.onError(ex);
}, function () {
map.getValues().forEach(function (item) { item.onCompleted(); });
observer.onCompleted();
}));
return refCountDisposable;
}, source);
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
var self = this;
return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg)
};
MapObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new MapObserver(observer, this.selector, this));
};
return MapObservable;
}(ObservableBase));
function MapObserver(observer, selector, source) {
this.observer = observer;
this.selector = selector;
this.source = source;
this.i = 0;
this.isStopped = false;
}
MapObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var result = tryCatch(this.selector).call(this, x, this.i++, this.source);
if (result === errorObj) {
return this.observer.onError(result.e);
}
this.observer.onNext(result);
};
MapObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
MapObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
MapObserver.prototype.dispose = function() { this.isStopped = true; };
MapObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var args = arguments, len = arguments.length;
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
return this.map(function (x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
});
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, source).mergeAll();
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
o.onNext(x);
} else {
remaining--;
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining === 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new FilterObserver(observer, this.predicate, this));
};
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
var self = this;
return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg);
};
return FilterObservable;
}(ObservableBase));
function FilterObserver(observer, predicate, source) {
this.observer = observer;
this.predicate = predicate;
this.source = source;
this.i = 0;
this.isStopped = false;
}
FilterObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.observer.onError(shouldYield.e);
}
shouldYield && this.observer.onNext(x);
};
FilterObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
FilterObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
FilterObserver.prototype.dispose = function() { this.isStopped = true; };
FilterObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (o) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
o.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
o.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) { list.push(x); }
}, function (e) { o.onError(e); }, function () {
o.onNext(list);
o.onCompleted();
});
}, source);
}
function firstOnly(x) {
if (x.length === 0) { throw new EmptyError(); }
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @deprecated Use #reduce instead
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var hasSeed = false, accumulator, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
return o.onError(e);
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new EmptyError());
o.onCompleted();
}
);
}, source);
};
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var hasSeed = false, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
return o.onError(e);
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new EmptyError());
o.onCompleted();
}
);
}, source);
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = function (predicate, thisArg) {
var source = this;
return predicate ?
source.filter(predicate, thisArg).some() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, function (e) { observer.onError(e); }, function () {
observer.onNext(false);
observer.onCompleted();
});
}, source);
};
/** @deprecated use #some instead */
observableProto.any = function () {
//deprecate('any', 'some');
return this.some.apply(this, arguments);
};
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().map(not);
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = function (predicate, thisArg) {
return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not);
};
/** @deprecated use #every instead */
observableProto.all = function () {
//deprecate('all', 'every');
return this.every.apply(this, arguments);
};
/**
* Determines whether an observable sequence includes a specified element with an optional equality comparer.
* @param searchElement The value to locate in the source sequence.
* @param {Number} [fromIndex] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
*/
observableProto.includes = function (searchElement, fromIndex) {
var source = this;
function comparer(a, b) {
return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
}
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(false);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i++ >= n && comparer(x, searchElement)) {
o.onNext(true);
o.onCompleted();
}
},
function (e) { o.onError(e); },
function () {
o.onNext(false);
o.onCompleted();
});
}, this);
};
/**
* @deprecated use #includes instead.
*/
observableProto.contains = function (searchElement, fromIndex) {
//deprecate('contains', 'includes');
observableProto.includes(searchElement, fromIndex);
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.filter(predicate, thisArg).count() :
this.reduce(function (count) { return count + 1; }, 0);
};
/**
* Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
* @param {Any} searchElement Element to locate in the array.
* @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
* @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
*/
observableProto.indexOf = function(searchElement, fromIndex) {
var source = this;
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(-1);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i >= n && x === searchElement) {
o.onNext(i);
o.onCompleted();
}
i++;
},
function (e) { o.onError(e); },
function () {
o.onNext(-1);
o.onCompleted();
});
}, source);
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).sum() :
this.reduce(function (prev, curr) { return prev + curr; }, 0);
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).average() :
this.reduce(function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}, {sum: 0, count: 0 }).map(function (s) {
if (s.count === 0) { throw new EmptyError(); }
return s.sum / s.count;
});
};
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
o.onError(e);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (doner) {
o.onNext(false);
o.onCompleted();
} else {
ql.push(x);
}
}, function(e) { o.onError(e); }, function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (doner) {
o.onNext(true);
o.onCompleted();
}
}
});
(isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal;
if (ql.length > 0) {
var v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
o.onError(exception);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (donel) {
o.onNext(false);
o.onCompleted();
} else {
qr.push(x);
}
}, function(e) { o.onError(e); }, function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (donel) {
o.onNext(true);
o.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
}, first);
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (o) {
var i = index;
return source.subscribe(function (x) {
if (i-- === 0) {
o.onNext(x);
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new ArgumentOutOfRangeError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
o.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate && isFunction(predicate) ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate && isFunction(predicate) ?
this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue);
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) {
o.onNext(x);
o.onCompleted();
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
var callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = callback(x, i, source);
} catch (e) {
o.onError(e);
return;
}
if (shouldRun) {
o.onNext(yieldIndex ? i : x);
o.onCompleted();
} else {
i++;
}
}, function (e) { o.onError(e); }, function () {
o.onNext(yieldIndex ? -1 : undefined);
o.onCompleted();
});
}, source);
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Converts the observable sequence to a Set if it exists.
* @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
*/
observableProto.toSet = function () {
if (typeof root.Set === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var s = new root.Set();
return source.subscribe(
function (x) { s.add(x); },
function (e) { o.onError(e); },
function () {
o.onNext(s);
o.onCompleted();
});
}, source);
};
/**
* Converts the observable sequence to a Map if it exists.
* @param {Function} keySelector A function which produces the key for the Map.
* @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
*/
observableProto.toMap = function (keySelector, elementSelector) {
if (typeof root.Map === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var m = new root.Map();
return source.subscribe(
function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
var element = x;
if (elementSelector) {
try {
element = elementSelector(x);
} catch (e) {
o.onError(e);
return;
}
}
m.set(key, element);
},
function (e) { o.onError(e); },
function () {
o.onNext(m);
o.onCompleted();
});
}, source);
};
var fnString = 'function',
throwString = 'throw',
isObject = Rx.internals.isObject;
function toThunk(obj, ctx) {
if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); }
if (isGenerator(obj)) { return observableSpawn(obj); }
if (isObservable(obj)) { return observableToThunk(obj); }
if (isPromise(obj)) { return promiseToThunk(obj); }
if (typeof obj === fnString) { return obj; }
if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
return obj;
}
function objectToThunk(obj) {
var ctx = this;
return function (done) {
var keys = Object.keys(obj),
pending = keys.length,
results = new obj.constructor(),
finished;
if (!pending) {
timeoutScheduler.schedule(function () { done(null, results); });
return;
}
for (var i = 0, len = keys.length; i < len; i++) {
run(obj[keys[i]], keys[i]);
}
function run(fn, key) {
if (finished) { return; }
try {
fn = toThunk(fn, ctx);
if (typeof fn !== fnString) {
results[key] = fn;
return --pending || done(null, results);
}
fn.call(ctx, function(err, res) {
if (finished) { return; }
if (err) {
finished = true;
return done(err);
}
results[key] = res;
--pending || done(null, results);
});
} catch (e) {
finished = true;
done(e);
}
}
}
}
function observableToThunk(observable) {
return function (fn) {
var value, hasValue = false;
observable.subscribe(
function (v) {
value = v;
hasValue = true;
},
fn,
function () {
hasValue && fn(null, value);
});
}
}
function promiseToThunk(promise) {
return function(fn) {
promise.then(function(res) {
fn(null, res);
}, fn);
}
}
function isObservable(obj) {
return obj && typeof obj.subscribe === fnString;
}
function isGeneratorFunction(obj) {
return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
function isGenerator(obj) {
return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString;
}
/*
* Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions.
* @param {Function} The spawning function.
* @returns {Function} a function which has a done continuation.
*/
var observableSpawn = Rx.spawn = function (fn) {
var isGenFun = isGeneratorFunction(fn);
return function (done) {
var ctx = this,
gen = fn;
if (isGenFun) {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
var len = args.length,
hasCallback = len && typeof args[len - 1] === fnString;
done = hasCallback ? args.pop() : handleError;
gen = fn.apply(this, args);
} else {
done = done || handleError;
}
next();
function exit(err, res) {
timeoutScheduler.schedule(done.bind(ctx, err, res));
}
function next(err, res) {
var ret;
// multiple args
if (arguments.length > 2) {
for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); }
}
if (err) {
try {
ret = gen[throwString](err);
} catch (e) {
return exit(e);
}
}
if (!err) {
try {
ret = gen.next(res);
} catch (e) {
return exit(e);
}
}
if (ret.done) {
return exit(null, ret.value);
}
ret.value = toThunk(ret.value, ctx);
if (typeof ret.value === fnString) {
var called = false;
try {
ret.value.call(ctx, function() {
if (called) {
return;
}
called = true;
next.apply(ctx, arguments);
});
} catch (e) {
timeoutScheduler.schedule(function () {
if (called) {
return;
}
called = true;
next.call(ctx, e);
});
}
return;
}
// Not supported
next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.'));
}
}
};
function handleError(err) {
if (!err) { return; }
timeoutScheduler.schedule(function() {
throw err;
});
}
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, context, scheduler) {
return observableToAsync(func, context, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
* @param {Function} function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return function () {
var args = arguments,
subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler() {
var len = arguments.length, results = new Array(len);
for(var i = 0; i < len; i++) { results[i] = arguments[i]; }
if (selector) {
try {
results = selector.apply(context, results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var len = arguments.length, results = [];
for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
if (selector) {
try {
results = selector.apply(context, results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette, Ember.js
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) {
o.onError(err);
return;
}
try {
res = resultSelector.apply(null, values);
} catch (ex) {
o.onError(ex);
return;
}
o.onNext(res);
}
if (isDone && values[1]) {
o.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(o) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
o.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
o.onNext(q.shift());
}
o.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
o.onNext(q.shift());
}
o.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onCompleted();
else
this.queue.push(Rx.Notification.createOnCompleted());
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onError(error);
else
this.queue.push(Rx.Notification.createOnError(error));
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(Rx.Notification.createOnNext(value));
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while ((this.queue.length >= numberOfItems && numberOfItems > 0) ||
(this.queue.length > 0 && this.queue[0].kind !== 'N')) {
var first = this.queue.shift();
first.accept(this.subject);
if (first.kind === 'N') numberOfItems--;
else { this.disposeCurrentRequest(); this.queue = []; }
}
return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0};
}
//TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function
//if (this.hasFailed) {
// this.subject.onError(this.error);
//} else if (this.hasCompleted) {
// this.subject.onCompleted();
//}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable;
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var StopAndWaitObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () { self.source.request(1); });
return this.subscription;
}
inherits(StopAndWaitObservable, __super__);
function StopAndWaitObservable (source) {
__super__.call(this, subscribe, source);
this.source = source;
}
var StopAndWaitObserver = (function (__sub__) {
inherits(StopAndWaitObserver, __sub__);
function StopAndWaitObserver (observer, observable, cancel) {
__sub__.call(this);
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
}
var stopAndWaitObserverProto = StopAndWaitObserver.prototype;
stopAndWaitObserverProto.completed = function () {
this.observer.onCompleted();
this.dispose();
};
stopAndWaitObserverProto.error = function (error) {
this.observer.onError(error);
this.dispose();
}
stopAndWaitObserverProto.next = function (value) {
this.observer.onNext(value);
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(1);
});
};
stopAndWaitObserverProto.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return StopAndWaitObserver;
}(AbstractObserver));
return StopAndWaitObservable;
}(Observable));
/**
* Attaches a stop and wait observable to the current observable.
* @returns {Observable} A stop and wait observable.
*/
ControlledObservable.prototype.stopAndWait = function () {
return new StopAndWaitObservable(this);
};
var WindowedObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () {
self.source.request(self.windowSize);
});
return this.subscription;
}
inherits(WindowedObservable, __super__);
function WindowedObservable(source, windowSize) {
__super__.call(this, subscribe, source);
this.source = source;
this.windowSize = windowSize;
}
var WindowedObserver = (function (__sub__) {
inherits(WindowedObserver, __sub__);
function WindowedObserver(observer, observable, cancel) {
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
this.received = 0;
}
var windowedObserverPrototype = WindowedObserver.prototype;
windowedObserverPrototype.completed = function () {
this.observer.onCompleted();
this.dispose();
};
windowedObserverPrototype.error = function (error) {
this.observer.onError(error);
this.dispose();
};
windowedObserverPrototype.next = function (value) {
this.observer.onNext(value);
this.received = ++this.received % this.observable.windowSize;
if (this.received === 0) {
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(self.observable.windowSize);
});
}
};
windowedObserverPrototype.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return WindowedObserver;
}(AbstractObserver));
return WindowedObservable;
}(Observable));
/**
* Creates a sliding windowed observable based upon the window size.
* @param {Number} windowSize The number of items in the window
* @returns {Observable} A windowed observable based upon the window size.
*/
ControlledObservable.prototype.windowed = function (windowSize) {
return new WindowedObservable(this, windowSize);
};
/**
* Pipes the existing Observable sequence into a Node.js Stream.
* @param {Stream} dest The destination Node.js stream.
* @returns {Stream} The destination stream.
*/
observableProto.pipe = function (dest) {
var source = this.pausableBuffered();
function onDrain() {
source.resume();
}
dest.addListener('drain', onDrain);
source.subscribe(
function (x) {
!dest.write(String(x)) && source.pause();
},
function (err) {
dest.emit('error', err);
},
function () {
// Hack check because STDIO is not closable
!dest._isStdio && dest.end();
dest.removeListener('drain', onDrain);
});
source.resume();
return dest;
};
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param windowSize [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
return this.replay(null, bufferSize, windowSize, scheduler).refCount();
};
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Gets the current value or throws an exception.
* Value is frozen after onCompleted is called.
* After onError is called always throws the specified exception.
* An exception is always thrown after dispose is called.
* @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
*/
getValue: function () {
checkDisposed(this);
if (this.hasError) {
throw this.error;
}
return this.value;
},
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
var maxSafeInteger = Math.pow(2, 53) - 1;
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
var Dictionary = (function () {
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647],
noSuchkey = "no such key",
duplicatekey = "duplicate key";
function isPrime(candidate) {
if ((candidate & 1) === 0) { return candidate === 2; }
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) { return false; }
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) { return num; }
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) { return candidate; }
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) { return hash; }
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash << 5) - hash) + character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) { throw new Error(noSuchkey); }
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') { return stringHashFn(obj); }
if (typeof obj === 'number') { return numberHashFn(obj); }
if (typeof obj === 'boolean') { return obj === true ? 1 : 0; }
if (obj instanceof Date) { return numberHashFn(obj.valueOf()); }
if (obj instanceof RegExp) { return stringHashFn(obj.toString()); }
if (typeof obj.valueOf === 'function') {
// Hack check for valueOf
var valueOf = obj.valueOf();
if (typeof valueOf === 'number') { return numberHashFn(valueOf); }
if (typeof valueOf === 'string') { return stringHashFn(valueOf); }
}
if (obj.hashCode) { return obj.hashCode(); }
var id = 17 * uniqueIdCounter++;
obj.hashCode = function () { return id; };
return id;
};
}());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
function Dictionary(capacity, comparer) {
if (capacity < 0) { throw new ArgumentOutOfRangeError(); }
if (capacity > 0) { this._initialize(capacity); }
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
}
var dictionaryProto = Dictionary.prototype;
dictionaryProto._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
dictionaryProto.add = function (key, value) {
this._insert(key, value, true);
};
dictionaryProto._insert = function (key, value, add) {
if (!this.buckets) { this._initialize(0); }
var index3,
num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) { throw new Error(duplicatekey); }
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
dictionaryProto._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; }
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; }
for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); }
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
dictionaryProto.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length,
index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
dictionaryProto.clear = function () {
var index, len;
if (this.size <= 0) { return; }
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
dictionaryProto._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
dictionaryProto.count = function () {
return this.size - this.freeCount;
};
dictionaryProto.tryGetValue = function (key) {
var entry = this._findEntry(key);
return entry >= 0 ?
this.entries[entry].value :
undefined;
};
dictionaryProto.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
dictionaryProto.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) { return this.entries[entry].value; }
throw new Error(noSuchkey);
};
dictionaryProto.set = function (key, value) {
this._insert(key, value, false);
};
dictionaryProto.containskey = function (key) {
return this._findEntry(key) >= 0;
};
return Dictionary;
}());
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var leftDone = false, rightDone = false;
var leftId = 0, rightId = 0;
var leftMap = new Dictionary(), rightMap = new Dictionary();
group.add(left.subscribe(
function (value) {
var id = leftId++;
var md = new SingleAssignmentDisposable();
leftMap.add(id, value);
group.add(md);
var expire = function () {
leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
rightMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(value, v);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
leftDone = true;
(rightDone || leftMap.count() === 0) && observer.onCompleted();
})
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
var md = new SingleAssignmentDisposable();
rightMap.add(id, value);
group.add(md);
var expire = function () {
rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
leftMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(v, value);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
rightDone = true;
(leftDone || rightMap.count() === 0) && observer.onCompleted();
})
);
return group;
}, left);
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary(), rightMap = new Dictionary();
var leftId = 0, rightId = 0;
function handleError(e) { return function (v) { v.onError(e); }; };
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftId++;
leftMap.add(id, s);
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(result);
rightMap.getValues().forEach(function (v) { s.onNext(v); });
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
leftMap.remove(id) && s.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
observer.onCompleted.bind(observer))
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
leftMap.getValues().forEach(function (v) { v.onNext(value); });
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
})
);
return r;
}, left);
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) {
return win;
});
}
function observableWindowWithBoundaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var win = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
d.add(windowBoundaries.subscribe(function (w) {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
return r;
}, source);
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
win = new Subject();
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
function createWindowClose () {
var windowClose;
try {
windowClose = windowClosingSelector();
} catch (e) {
observer.onError(e);
return;
}
isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
var m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
createWindowClose();
}));
}
createWindowClose();
return r;
}, source);
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
}, source);
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
return [
this.filter(predicate, thisArg),
this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
function enumerableWhile(condition, source) {
return new Enumerable(function () {
return new Enumerator(function () {
return condition() ?
{ done: false, value: source } :
{ done: true, value: undefined };
});
});
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) {
return enumerableOf(sources, resultSelector, thisArg).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
}, this);
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = [];
if (Array.isArray(arguments[0])) {
allSources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); }
}
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
}, first);
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.map(function (x) {
var curr = new ChainObservable(x);
chain && chain.onNext(x);
chain = curr;
return curr;
})
.tap(
noop,
function (e) { chain && chain.onError(e); },
function () { chain && chain.onCompleted(); }
)
.observeOn(scheduler)
.map(selector);
}, source);
};
var ChainObservable = (function (__super__) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeAll().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, __super__);
function ChainObservable(head) {
__super__.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwError(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = root.Map || (function () {
function Map() {
this._keys = [];
this._values = [];
}
Map.prototype.get = function (key) {
var i = this._keys.indexOf(key);
return i !== -1 ? this._values[i] : undefined;
};
Map.prototype.set = function (key, value) {
var i = this._keys.indexOf(key);
i !== -1 && (this._values[i] = value);
this._values[this._keys.push(key) - 1] = value;
};
Map.prototype.forEach = function (callback, thisArg) {
for (var i = 0, len = this._keys.length; i < len; i++) {
callback.call(thisArg, this._values[i], this._keys[i]);
}
};
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
* @param other Observable sequence to match in addition to the current pattern.
* @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
return new Pattern(this.patterns.concat(other));
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
* @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.thenDo = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
function ActivePlan(joinObserverArray, onNext, onCompleted) {
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
var joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
this.joinObservers.forEach(function (v) { v.queue.shift(); });
};
ActivePlan.prototype.match = function () {
var i, len, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
var firstValues = [],
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
var values = [];
for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
var JoinObserver = (function (__super__) {
inherits(JoinObserver, __super__);
function JoinObserver(source, onError) {
__super__.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
return this.onError(notification.exception);
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
JoinObserverPrototype.error = noop;
JoinObserverPrototype.completed = noop;
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
JoinObserverPrototype.removeActivePlan = function (activePlan) {
this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
this.activePlans.length === 0 && this.dispose();
};
JoinObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param {Function} selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.thenDo = function (selector) {
return new Pattern([this]).thenDo(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var len = arguments.length, plans;
if (Array.isArray(arguments[0])) {
plans = arguments[0];
} else {
plans = new Array(len);
for(var i = 0; i < len; i++) { plans[i] = arguments[i]; }
}
return new AnonymousObservable(function (o) {
var activePlans = [],
externalSubscriptions = new Map();
var outObserver = observerCreate(
function (x) { o.onNext(x); },
function (err) {
externalSubscriptions.forEach(function (v) { v.onError(err); });
o.onError(err);
},
function (x) { o.onCompleted(); }
);
try {
for (var i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
activePlans.length === 0 && o.onCompleted();
}));
}
} catch (e) {
observableThrow(e).subscribe(o);
}
var group = new CompositeDisposable();
externalSubscriptions.forEach(function (joinObserver) {
joinObserver.subscribe();
group.add(joinObserver);
});
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count);
self(count + 1, d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
}, source);
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
* @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasvalue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, this);
};
/**
* @deprecated use #debounce or #throttleWithTimeout instead.
*/
observableProto.throttle = function(dueTime, scheduler) {
//deprecate('throttle', 'debounce or throttleWithTimeout');
return this.debounce(dueTime, scheduler);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
timeShiftOrScheduler == null && (timeShift = timeSpan);
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (isScheduler(timeShiftOrScheduler)) {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
if (isShift) {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
isSpan && q.shift().onCompleted();
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
},
function (e) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
observer.onError(e);
},
function () {
for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var timerD = new SerialDisposable(),
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable),
n = 0,
windowId = 0,
s = new Subject();
function createTimer(id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
if (id !== windowId) { return; }
n = 0;
var newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
}
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(
function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
if (++n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
newWindow && createTimer(newId);
},
function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.map(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return { value: x, interval: span };
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty);
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) { observer.onCompleted(); }
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(start, observer.onError.bind(observer), start));
}
return new CompositeDisposable(subscription, delays);
}, this);
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false;
function setTimer(timeout) {
var myId = id;
function timerWins () {
return id === myId;
}
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
d.dispose();
}, function (e) {
timerWins() && observer.onError(e);
}, function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
}));
};
setTimer(firstTimeout);
function observerWins() {
var res = !switched;
if (res) { id++; }
return res;
}
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
}
}, function (e) {
observerWins() && observer.onError(e);
}, function () {
observerWins() && observer.onCompleted();
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
* @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounceWithSelector = function (durationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
var subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = durationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
isPromise(throttle) && (throttle = observableFromPromise(throttle));
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
hasValue && observer.onNext(value);
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, source);
};
/**
* @deprecated use #debounceWithSelector instead.
*/
observableProto.throttleWithSelector = function (durationSelector) {
//deprecate('throttleWithSelector', 'debounceWithSelector');
return this.debounceWithSelector(durationSelector);
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
o.onCompleted();
});
}, source);
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) { o.onNext(next.value); }
}
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
now - next.interval <= duration && res.push(next.value);
}
o.onNext(res);
o.onCompleted();
});
}, source);
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o));
}, source);
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
}, source);
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [scheduler]);
* @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && o.onNext(x); },
function (e) { o.onError(e); }, function () { o.onCompleted(); }));
}, source);
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} [scheduler] Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
return new CompositeDisposable(
scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }),
source.subscribe(o));
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(o) {
return {
'@@transducer/init': function() {
return o;
},
'@@transducer/step': function(obs, input) {
return obs.onNext(input);
},
'@@transducer/result': function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(o) {
var xform = transducer(transformForObserver(o));
return source.subscribe(
function(v) {
try {
xform['@@transducer/step'](o, v);
} catch (e) {
o.onError(e);
}
},
function (e) { o.onError(e); },
function() { xform['@@transducer/result'](o); }
);
}, source);
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
}, this);
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this,
selectorFunc = bindCallback(selector, thisArg, 3);
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selectorFunc(x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
function (e) { observer.onError(e); },
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
}, this);
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (__super__) {
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, __super__);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
__super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time),
dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); }
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
while (this.queue.length > 0) {
var next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this;
function run(scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
}
var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
this.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (__super__) {
inherits(HistoricalScheduler, __super__);
/**
* Creates a new historical scheduler with the specified initial clock value.
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
__super__.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
var sub = tryCatch(subscribe)(ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
function s(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, subscribe];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var GroupedObservable = (function (__super__) {
inherits(GroupedObservable, __super__);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
__super__.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Used to pause and resume streams.
*/
Rx.Pauser = (function (__super__) {
inherits(Pauser, __super__);
function Pauser() {
__super__.call(this);
}
/**
* Pauses the underlying sequence.
*/
Pauser.prototype.pause = function () { this.onNext(false); };
/**
* Resumes the underlying sequence.
*/
Pauser.prototype.resume = function () { this.onNext(true); };
return Pauser;
}(Subject));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
}).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"FWaASH":147}]},{},[1]) |
packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/index.js | jzmq/react | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import React, {Fragment, useContext, useMemo} from 'react';
import {StoreContext} from 'react-devtools-shared/src/devtools/views/context';
import {useSubscription} from 'react-devtools-shared/src/devtools/views/hooks';
import {NativeStyleContext} from './context';
import LayoutViewer from './LayoutViewer';
import StyleEditor from './StyleEditor';
import {TreeStateContext} from '../TreeContext';
type Props = {||};
export default function NativeStyleEditorWrapper(_: Props) {
const store = useContext(StoreContext);
const subscription = useMemo(
() => ({
getCurrentValue: () => store.supportsNativeStyleEditor,
subscribe: (callback: Function) => {
store.addListener('supportsNativeStyleEditor', callback);
return () => {
store.removeListener('supportsNativeStyleEditor', callback);
};
},
}),
[store],
);
const supportsNativeStyleEditor = useSubscription<boolean>(subscription);
if (!supportsNativeStyleEditor) {
return null;
}
return <NativeStyleEditor />;
}
function NativeStyleEditor(_: Props) {
const {getStyleAndLayout} = useContext(NativeStyleContext);
const {inspectedElementID} = useContext(TreeStateContext);
if (inspectedElementID === null) {
return null;
}
const maybeStyleAndLayout = getStyleAndLayout(inspectedElementID);
if (maybeStyleAndLayout === null) {
return null;
}
const {layout, style} = maybeStyleAndLayout;
return (
<Fragment>
{layout !== null && (
<LayoutViewer id={inspectedElementID} layout={layout} />
)}
{style !== null && (
<StyleEditor
id={inspectedElementID}
style={style !== null ? style : {}}
/>
)}
</Fragment>
);
}
|
examples/universal/client/index.js | dalinaum/redux | import 'babel-core/polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from '../common/store/configureStore';
import App from '../common/containers/App';
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState);
const rootElement = document.getElementById('app');
React.render(
<Provider store={store}>
{() => <App/>}
</Provider>,
rootElement
);
|
examples/universal/src/client.js | 4Catalyzer/found | import createInitialBrowserRouter from 'found/createInitialBrowserRouter';
import React from 'react';
import ReactDOM from 'react-dom';
import render from './render';
import routeConfig from './routeConfig';
(async () => {
const BrowserRouter = await createInitialBrowserRouter({
routeConfig,
render,
});
ReactDOM.hydrate(<BrowserRouter />, document.getElementById('root'));
})();
|
step-capstone/src/components/TravelObjects/Flight.js | googleinterns/step98-2020 | import React from 'react';
import '../../styles/TimeLine.css';
import {Typography} from '@material-ui/core';
/*
Takes data in this form:
{
finalized: true,
type: "flight",
departureAirport: "BOS",
arrivalAirport: "SFO",
startDate: "4:00pm EST",
endDate: "7:00pm PST",
description: "Additional notes"
}
*/
export default function Flight( props ) {
let timeString = props.data.startDate.toLocaleString() + ' - ' + props.data.endDate.toLocaleString();
/*Given 2 Date objects, return true if they have the same date; return false otherwise */
const sameDate = (timeA, timeB) => {
return (timeA.getDate() === timeB.getDate() && timeA.getMonth() === timeB.getMonth() && timeA.getFullYear() === timeB.getFullYear());
}
if (props.data.finalized && sameDate(props.data.startDate, props.data.endDate)) {
timeString = props.data.startDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}) + ' - ' + props.data.endDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
}
return(
<div className="event double flights" style={props.styleConfig}>
<Typography variant="h6" gutterBottom>Flight from { props.data.departureAirport } to { props.data.arrivalAirport }</Typography>
<Typography variant="subtitle2" gutterBottom>{ timeString }</Typography>
</div>
)
}
|
wrappers/toml.js | caryfuk/architektka | import React from 'react'
import toml from 'toml-js'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import Helmet from 'react-helmet'
import { config } from 'config'
import { findDOMNode } from 'react-dom';
let Lightbox
module.exports = React.createClass({
propTypes () {
return {
route: React.PropTypes.object,
}
},
getInitialState () {
return {
photoIndex: 0,
isOpen: false,
isMounted: false
}
},
componentDidMount() {
Lightbox = require('react-image-lightbox');
this.setState({
isMounted: true
});
},
render () {
const route = this.props.route
const data = route.page.data
const title = data.title_en
const description = data.description_en
const {
photoIndex,
isOpen,
isMounted
} = this.state
return (
<div className='detailPage'>
<Helmet
title={`${title} | ${config.siteTitle}`}
/>
<h1>{isMounted ? <span onClick={()=>{ history.back() }}><</span> : false} {title}</h1>
<p>{description}</p>
<ul>
{data.images && data.images.map((image, i) => {
return (
<li
key={i}
style={{
animationDelay: `${i*0.05}s`,
WebkitAnimationDelay: `${i*0.05}s`
}}
onClick={() => this.setState({ isOpen: true, photoIndex: i })}>
<img src={`600/${image.url}.jpg`} />
</li>
)
})}
</ul>
{isMounted && isOpen && data.images.length > 0 &&
<Lightbox
mainSrc={`1600/${data.images[photoIndex].url}.jpg`}
imageCaption={
data.images[photoIndex].description_en
}
nextSrc={`1600/${data.images[(photoIndex + 1) % data.images.length].url}.jpg`}
prevSrc={`1600/${data.images[(photoIndex + data.images.length - 1) % data.images.length].url}.jpg`}
imagePadding={0}
onCloseRequest={() => this.setState({ isOpen: false })}
onMovePrevRequest={() => this.setState({
photoIndex: (photoIndex + data.images.length - 1) % data.images.length,
})}
onMoveNextRequest={() => this.setState({
photoIndex: (photoIndex + 1) % data.images.length,
})}
/>
}
</div>
)
},
})
|
app/src/js/component/chart-account/SearchAccount.js | enoa7/chart-account | import React from 'react';
export default class SearchAccount extends React.Component{
render() {
return (
<div className="search-box">
<i className="fa fa-search"></i>
<input type="text" className="" placeholder="Search.." />
</div>
)
}
} |
modules/field_ui/field_ui.js | stevepolitodesign/lucidia | /**
* @file
* Attaches the behaviors for the Field UI module.
*/
(function($) {
Drupal.behaviors.fieldUIFieldOverview = {
attach: function (context, settings) {
$('table#field-overview', context).once('field-overview', function () {
Drupal.fieldUIFieldOverview.attachUpdateSelects(this, settings);
});
}
};
Drupal.fieldUIFieldOverview = {
/**
* Implements dependent select dropdowns on the 'Manage fields' screen.
*/
attachUpdateSelects: function(table, settings) {
var widgetTypes = settings.fieldWidgetTypes;
var fields = settings.fields;
// Store the default text of widget selects.
$('.widget-type-select', table).each(function () {
this.initialValue = this.options[0].text;
});
// 'Field type' select updates its 'Widget' select.
$('.field-type-select', table).each(function () {
this.targetSelect = $('.widget-type-select', $(this).closest('tr'));
$(this).bind('change keyup', function () {
var selectedFieldType = this.options[this.selectedIndex].value;
var options = (selectedFieldType in widgetTypes ? widgetTypes[selectedFieldType] : []);
this.targetSelect.fieldUIPopulateOptions(options);
});
// Trigger change on initial pageload to get the right widget options
// when field type comes pre-selected (on failed validation).
$(this).trigger('change', false);
});
// 'Existing field' select updates its 'Widget' select and 'Label' textfield.
$('.field-select', table).each(function () {
this.targetSelect = $('.widget-type-select', $(this).closest('tr'));
this.targetTextfield = $('.label-textfield', $(this).closest('tr'));
this.targetTextfield
.data('field_ui_edited', false)
.bind('keyup', function (e) {
$(this).data('field_ui_edited', $(this).val() != '');
});
$(this).bind('change keyup', function (e, updateText) {
var updateText = (typeof updateText == 'undefined' ? true : updateText);
var selectedField = this.options[this.selectedIndex].value;
var selectedFieldType = (selectedField in fields ? fields[selectedField].type : null);
var selectedFieldWidget = (selectedField in fields ? fields[selectedField].widget : null);
var options = (selectedFieldType && (selectedFieldType in widgetTypes) ? widgetTypes[selectedFieldType] : []);
this.targetSelect.fieldUIPopulateOptions(options, selectedFieldWidget);
// Only overwrite the "Label" input if it has not been manually
// changed, or if it is empty.
if (updateText && !this.targetTextfield.data('field_ui_edited')) {
this.targetTextfield.val(selectedField in fields ? fields[selectedField].label : '');
}
});
// Trigger change on initial pageload to get the right widget options
// and label when field type comes pre-selected (on failed validation).
$(this).trigger('change', false);
});
}
};
/**
* Populates options in a select input.
*/
jQuery.fn.fieldUIPopulateOptions = function (options, selected) {
return this.each(function () {
var disabled = false;
if (options.length == 0) {
options = [this.initialValue];
disabled = true;
}
// If possible, keep the same widget selected when changing field type.
// This is based on textual value, since the internal value might be
// different (options_buttons vs. node_reference_buttons).
var previousSelectedText = this.options[this.selectedIndex].text;
var html = '';
jQuery.each(options, function (value, text) {
// Figure out which value should be selected. The 'selected' param
// takes precedence.
var is_selected = ((typeof selected != 'undefined' && value == selected) || (typeof selected == 'undefined' && text == previousSelectedText));
html += '<option value="' + value + '"' + (is_selected ? ' selected="selected"' : '') + '>' + text + '</option>';
});
$(this).html(html).attr('disabled', disabled ? 'disabled' : false);
});
};
Drupal.behaviors.fieldUIDisplayOverview = {
attach: function (context, settings) {
$('table#field-display-overview', context).once('field-display-overview', function() {
Drupal.fieldUIOverview.attach(this, settings.fieldUIRowsData, Drupal.fieldUIDisplayOverview);
});
}
};
Drupal.fieldUIOverview = {
/**
* Attaches the fieldUIOverview behavior.
*/
attach: function (table, rowsData, rowHandlers) {
var tableDrag = Drupal.tableDrag[table.id];
// Add custom tabledrag callbacks.
tableDrag.onDrop = this.onDrop;
tableDrag.row.prototype.onSwap = this.onSwap;
// Create row handlers.
$('tr.draggable', table).each(function () {
// Extract server-side data for the row.
var row = this;
if (row.id in rowsData) {
var data = rowsData[row.id];
data.tableDrag = tableDrag;
// Create the row handler, make it accessible from the DOM row element.
var rowHandler = new rowHandlers[data.rowHandler](row, data);
$(row).data('fieldUIRowHandler', rowHandler);
}
});
},
/**
* Event handler to be attached to form inputs triggering a region change.
*/
onChange: function () {
var $trigger = $(this);
var row = $trigger.closest('tr').get(0);
var rowHandler = $(row).data('fieldUIRowHandler');
var refreshRows = {};
refreshRows[rowHandler.name] = $trigger.get(0);
// Handle region change.
var region = rowHandler.getRegion();
if (region != rowHandler.region) {
// Remove parenting.
$('select.field-parent', row).val('');
// Let the row handler deal with the region change.
$.extend(refreshRows, rowHandler.regionChange(region));
// Update the row region.
rowHandler.region = region;
}
// Ajax-update the rows.
Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows);
},
/**
* Lets row handlers react when a row is dropped into a new region.
*/
onDrop: function () {
var dragObject = this;
var row = dragObject.rowObject.element;
var rowHandler = $(row).data('fieldUIRowHandler');
if (rowHandler !== undefined) {
var regionRow = $(row).prevAll('tr.region-message').get(0);
var region = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
if (region != rowHandler.region) {
// Let the row handler deal with the region change.
refreshRows = rowHandler.regionChange(region);
// Update the row region.
rowHandler.region = region;
// Ajax-update the rows.
Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows);
}
}
},
/**
* Refreshes placeholder rows in empty regions while a row is being dragged.
*
* Copied from block.js.
*
* @param table
* The table DOM element.
* @param rowObject
* The tableDrag rowObject for the row being dragged.
*/
onSwap: function (draggedRow) {
var rowObject = this;
$('tr.region-message', rowObject.table).each(function () {
// If the dragged row is in this region, but above the message row, swap
// it down one space.
if ($(this).prev('tr').get(0) == rowObject.group[rowObject.group.length - 1]) {
// Prevent a recursion problem when using the keyboard to move rows up.
if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) {
rowObject.swap('after', this);
}
}
// This region has become empty.
if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').length == 0) {
$(this).removeClass('region-populated').addClass('region-empty');
}
// This region has become populated.
else if ($(this).is('.region-empty')) {
$(this).removeClass('region-empty').addClass('region-populated');
}
});
},
/**
* Triggers Ajax refresh of selected rows.
*
* The 'format type' selects can trigger a series of changes in child rows.
* The #ajax behavior is therefore not attached directly to the selects, but
* triggered manually through a hidden #ajax 'Refresh' button.
*
* @param rows
* A hash object, whose keys are the names of the rows to refresh (they
* will receive the 'ajax-new-content' effect on the server side), and
* whose values are the DOM element in the row that should get an Ajax
* throbber.
*/
AJAXRefreshRows: function (rows) {
// Separate keys and values.
var rowNames = [];
var ajaxElements = [];
$.each(rows, function (rowName, ajaxElement) {
rowNames.push(rowName);
ajaxElements.push(ajaxElement);
});
if (rowNames.length) {
// Add a throbber next each of the ajaxElements.
var $throbber = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>');
$(ajaxElements)
.addClass('progress-disabled')
.after($throbber);
// Fire the Ajax update.
$('input[name=refresh_rows]').val(rowNames.join(' '));
$('input#edit-refresh').mousedown();
// Disabled elements do not appear in POST ajax data, so we mark the
// elements disabled only after firing the request.
$(ajaxElements).attr('disabled', true);
}
}
};
/**
* Row handlers for the 'Manage display' screen.
*/
Drupal.fieldUIDisplayOverview = {};
/**
* Constructor for a 'field' row handler.
*
* This handler is used for both fields and 'extra fields' rows.
*
* @param row
* The row DOM element.
* @param data
* Additional data to be populated in the constructed object.
*/
Drupal.fieldUIDisplayOverview.field = function (row, data) {
this.row = row;
this.name = data.name;
this.region = data.region;
this.tableDrag = data.tableDrag;
// Attach change listener to the 'formatter type' select.
this.$formatSelect = $('select.field-formatter-type', row);
this.$formatSelect.change(Drupal.fieldUIOverview.onChange);
return this;
};
Drupal.fieldUIDisplayOverview.field.prototype = {
/**
* Returns the region corresponding to the current form values of the row.
*/
getRegion: function () {
return (this.$formatSelect.val() == 'hidden') ? 'hidden' : 'visible';
},
/**
* Reacts to a row being changed regions.
*
* This function is called when the row is moved to a different region, as a
* result of either :
* - a drag-and-drop action (the row's form elements then probably need to be
* updated accordingly)
* - user input in one of the form elements watched by the
* Drupal.fieldUIOverview.onChange change listener.
*
* @param region
* The name of the new region for the row.
* @return
* A hash object indicating which rows should be Ajax-updated as a result
* of the change, in the format expected by
* Drupal.displayOverview.AJAXRefreshRows().
*/
regionChange: function (region) {
// When triggered by a row drag, the 'format' select needs to be adjusted
// to the new region.
var currentValue = this.$formatSelect.val();
switch (region) {
case 'visible':
if (currentValue == 'hidden') {
// Restore the formatter back to the default formatter. Pseudo-fields do
// not have default formatters, we just return to 'visible' for those.
var value = (this.defaultFormatter != undefined) ? this.defaultFormatter : 'visible';
}
break;
default:
var value = 'hidden';
break;
}
if (value != undefined) {
this.$formatSelect.val(value);
}
var refreshRows = {};
refreshRows[this.name] = this.$formatSelect.get(0);
return refreshRows;
}
};
})(jQuery);
|
src/components/header.js | RaneWallin/FCCLeaderboard | import React from 'react';
const SiteHeader = () => {
return (
<header>
<h1>FreeCodeCamp Leaderboard</h1>
<h2>Designed and Coded by Rane</h2>
<h4>View source on <a href="https://github.com/RaneWallin/FCCLeaderboard/tree/gh-pages">GitHub</a></h4>
</header>
);
}
export default SiteHeader; |
src/components/PasswordInput/PasswordInput.js | miker169/ps-react-miker169 | import React from 'react';
import PropTypes from 'prop-types';
import ProgressBar from '../ProgressBar';
import EyeIcon from '../EyeIcon';
import TextInput from '../TextInput';
/** Password input with integrated label, quality tips, and show password toggle. */
class PasswordInput extends React.Component {
constructor(props) {
super(props);
this.state = {
showPassword: false
}
}
toggleShowPassword = event => {
this.setState(prevState => {
return { showPassword: !prevState.showPassword };
});
if (event) event.preventDefault();
}
render() {
const { htmlId, value, label, error, onChange, placeholder, maxLength, showVisibilityToggle, quality, ...props } = this.props;
const { showPassword } = this.state;
return (
<TextInput
htmlId={htmlId}
label={label}
placeholder={placeholder}
type={showPassword ? 'text' : 'password'}
onChange={onChange}
value={value}
maxLength={maxLength}
error={error}
required
{...props}>
{
showVisibilityToggle &&
<a
href=""
onClick={this.toggleShowPassword}
style={{ marginLeft: 5 }}>
<EyeIcon />
</a>
}
{
value.length > 0 && quality && <ProgressBar percent={quality} width={130} />
}
</TextInput>
);
}
}
PasswordInput.propTypes = {
/** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */
htmlId: PropTypes.string.isRequired,
/** Input name. Recommend setting this to match object's property so a single change handler can be used by convention.*/
name: PropTypes.string.isRequired,
/** Password value */
value: PropTypes.any,
/** Input label */
label: PropTypes.string,
/** Function called when password input value changes */
onChange: PropTypes.func.isRequired,
/** Max password length accepted */
maxLength: PropTypes.number,
/** Placeholder displayed when no password is entered */
placeholder: PropTypes.string,
/** Set to true to show the toggle for displaying the currently entered password */
showVisibilityToggle: PropTypes.bool,
/** Display password quality visually via ProgressBar, accepts a number between 0 and 100 */
quality: PropTypes.number,
/** Validation error to display */
error: PropTypes.string
};
PasswordInput.defaultProps = {
maxLength: 50,
showVisibilityToggle: false,
label: 'Password'
};
export default PasswordInput; |
app/components/Products.js | Ketevann/graceshopper | import React from 'react'
import { Link } from 'react-router'
import { BarLoader } from 'react-spinners';
import {
deleteProduct, findProduct, search, filterRemove, updatePath
} from '../reducers/products'
import store from '../store'
import Search from './Search'
import {
cancelSearch, searchProduct
} from '../reducers/search'
class Products extends React.Component {
constructor(props) {
super(props)
this.state = {
loading: true
}
this.handleClick = this.handleClick.bind(this)
}
componentDidMount() {
store.dispatch(this.props.updatePath(true))
}
componentWillUnmount() {
store.dispatch(this.props.updatePath(false))
}
handleClick = (id, action) => {
if (action === 'delete')
this.props.deleteProduct(id)
else this.props.somefunc
}
filter = (products) => {
var filteredProducts = this.props.products.all.filter(product => {
return product.categories.toLowerCase() === products.toLowerCase()
})
return filteredProducts;
}
renderProduct(allproducts) {
return allproducts.map((product) => {
if (product.length === 0) {
return <div>Your search did not return any results</div>
}
return (
<div key={product.id} className='col-md-4 col-sm-6 items' >
<Link to={`/products/${product.id}`}>
<img id="prodimg" src={product.img} />
<p className="productinfo" data-price="{product.price}">{product.name} $ {product.price}</p>
</Link>
{this.props.auth && this.props.auth.role === 'admin' ?
<div className="productedit">
<button className="btn btn-default" onClick={() => this.handleClick(product.id, 'delete')}>Remove</button>
<Link to={`/update/${product.id}`}><button className="btn btn-default" >Edit</button></Link>
<div className="productstockinfo">
<div>Inventory: {product.inventory}</div>
<div>In Stock: {product.inStock}</div>
</div>
</div> :
null}
</div>
)
})
}
render() {
const divStyle = {
width: 250,
height: 230
}
return (
<div className="">
<h1 className="productsheader" onClick={() => { store.dispatch(filterRemove()) }}>All Products</h1>
{this.props.auth && this.props.auth.role === 'admin' ?
<h1>
<Link to='/add'><button className="btn btn-default" >Add Products</button></Link></h1> : null}
{this.props.products && this.props.products.search ?
<div>{this.renderProduct(this.filter(this.props.products.val))}</div> :
this.props.products.all ?
<div>{this.renderProduct(this.props.products.all)}</div>
: <div className='sweet-loading'>
<BarLoader
color={'#123abc'}
loading={this.state.loading}
/>
</div>
}
</div>
)
}
}
import { connect } from 'react-redux'
const mapStateToProps = (state, ownProps) => {
return {
products: state.products,
filtered: state.filter,
auth: state.auth,
filter: state.filter,
searched: state.searchNames
}
}
export default connect(
mapStateToProps,
{
filterRemove,
deleteProduct,
search,
searchProduct,
cancelSearch,
updatePath
},
)(Products)
|
src/svg-icons/action/translate.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionTranslate = (props) => (
<SvgIcon {...props}>
<path d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
</SvgIcon>
);
ActionTranslate = pure(ActionTranslate);
ActionTranslate.displayName = 'ActionTranslate';
ActionTranslate.muiName = 'SvgIcon';
export default ActionTranslate;
|
lib/components/Markdown/index.js | welovekpop/uwave-web-welovekpop.club | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _jsx2 = _interopRequireDefault(require("@babel/runtime/helpers/builtin/jsx"));
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactMarkdown = _interopRequireDefault(require("react-markdown"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Markdown = function Markdown(_ref) {
var source = _ref.source;
return (0, _jsx2.default)(_reactMarkdown.default, {
escapeHtml: false,
source: source
});
};
Markdown.propTypes = process.env.NODE_ENV !== "production" ? {
source: _propTypes.default.string.isRequired
} : {};
var _default = Markdown;
exports.default = _default;
//# sourceMappingURL=index.js.map
|
ajax/libs/forerunnerdb/1.3.40/fdb-core+persist.min.js | boneskull/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){{var d=a("../lib/Core");a("../lib/Persist")}"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":4,"../lib/Persist":23}],2:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if("dropped"===this._state)return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log("Dropping collection "+this._name),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&this.primaryKey(a.primaryKey()),this.$super.apply(this,arguments)}),n.prototype.setData=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw'ForerunnerDB.Collection "'+this.name()+'": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: '+d[this._primaryKey]}else h.set(d[k],d);e=JSON.stringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.update=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';b=this.decouple(b),b=this.transformIn(b),this.debug()&&console.log('Updating some collection data for collection "'+this.name()+'"');var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},h=f.updateObject(i,e.update,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_BEFORE,d,i)!==!1?(h=f.updateObject(d,i,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_AFTER,d,i)):h=!1):h=f.updateObject(d,b,a,c,""),h};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw'ForerunnerDB.Collection "'+this.name()+'": Primary key violation in update! Key violated: '+a[this._primaryKey];return!0},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":this._updateIncrement(a,p,b[p]),q=!0;break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw'ForerunnerDB.Collection "'+this.name()+'": Cannot update cast to unknown type: '+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot push to a key that is not an array! ('+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pullAll without being given an array of values to pull! ('+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! ('+p+")";var s,t,u,v,w=a[p],x=w.length,y=!0,z=d&&d.$addToSet;for(b[p].$key?(u=!1,v=new h(b[p].$key),t=v.value(b[p])[0],delete b[p].$key):z&&z.key?(u=!1,v=new h(z.key),t=v.value(b[p])[0]):(t=JSON.stringify(b[p]),u=!0),s=0;x>s;s++)if(u){if(JSON.stringify(w[s])===t){y=!1;break}}else if(t===v.value(w[s])[0]){y=!1;break}y&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+p+")";if(l=b.$index,void 0===l)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush without a $index integer value!';delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move on a key that is not an array! ('+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],"",{})){var A=b.$index;if(void 0===A)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move without a $index integer value!';delete b.$index,this._updateSpliceMove(a[p],j,A),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pop from a key that is not an array! ('+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';var d,e,f,g,h,i,j,k,l=this;if(a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.deferEmit=function(){var a,b=this;this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(a=arguments,this._changeTimeout&&clearTimeout(this._changeTimeout),this._changeTimeout=setTimeout(function(){b.debug()&&console.log("ForerunnerDB.Collection: Emitting "+a[0]),b.emit.apply(b,a)},100))},n.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this[a](f)),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b()},n.prototype.insert=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f=this._deferQueue.insert,g=this._deferThreshold.insert,h=[],i=[];if(a instanceof Array){if(a.length>g)return this._deferQueue.insert=f.concat(a),void this.processQueue("insert",c);for(e=0;e<a.length;e++)d=this._insert(a[e],b+e),d===!0?h.push(a[e]):i.push({doc:a[e],reason:d})}else d=this._insert(a,b),d===!0?h.push(a):i.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),this._onInsert(h,i),c&&c(),this.deferEmit("change",{type:"insert",data:h}),{inserted:h,failed:i}},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=JSON.stringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=JSON.stringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.indexOfDocById=function(a){return this._data.indexOf(this._primaryIndex.get(a[this._primaryKey]))},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},n.prototype.subsetOf=function(){return this.__subsetOf},n.prototype._subsetOf=function(a){return this.__subsetOf=a,this},n.prototype.distinct=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=JSON.stringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C=this._metrics.create("find"),D=this.primaryKey(),E=this,F=!0,G={},H=[],I=[],J=[],K={},L=function(b){return E._match(b,a,"and",K)};if(C.start(),a){if(C.time("analyseQuery"),c=this._analyseQuery(a,b,C),C.time("analyseQuery"),C.data("analysis",c),c.hasJoin&&c.queriesJoin){for(C.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],G[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i);C.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(C.data("index.potential",c.indexMatch),C.data("index.used",c.indexMatch[0].index),C.time("indexLookup"),e=c.indexMatch[0].lookup,C.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(F=!1)):C.flag("usedIndex",!1),F&&(e&&e.length?(d=e.length,C.time("tableScan: "+d),e=e.filter(L)):(d=this._data.length,C.time("tableScan: "+d),e=this._data.filter(L)),b.$orderBy&&(C.time("sort"),e=this.sort(b.$orderBy,e),C.time("sort")),C.time("tableScan: "+d)),b.$limit&&e&&e.length>b.$limit&&(e.length=b.$limit,C.data("limit",b.$limit)),b.$decouple&&(C.time("decouple"),e=this.decouple(e),C.time("decouple"),C.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(s=k,l=this._db.collection(k),m=b.$join[f][k],t=0;t<e.length;t++){o={},p=!1,q=!1;for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$as":s=m[n];break;case"$multi":p=m[n];break;case"$require":q=m[n]}else o[n]=new h(m[n]).value(e[t])[0];r=l.find(o),!q||q&&r[0]?e[t][s]=p===!1?r[0]:r:H.push(e[t])}C.data("flag.join",!0)}if(H.length){for(C.time("removalQueue"),v=0;v<H.length;v++)u=e.indexOf(H[v]),u>-1&&e.splice(u,1);C.time("removalQueue")}if(b.$transform){for(C.time("transform"),v=0;v<e.length;v++)e.splice(v,1,b.$transform(e[v]));C.time("transform"),C.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(C.time("transformOut"),e=this.transformOut(e),C.time("transformOut")),C.data("results",e.length)}else e=[];C.time("scanFields");for(v in b)b.hasOwnProperty(v)&&0!==v.indexOf("$")&&(1===b[v]?I.push(v):0===b[v]&&J.push(v));if(C.time("scanFields"),I.length||J.length){for(C.data("flag.limitFields",!0),C.data("limitFields.on",I),C.data("limitFields.off",J),C.time("limitFields"),v=0;v<e.length;v++){B=e[v];for(w in B)B.hasOwnProperty(w)&&(I.length&&w!==D&&-1===I.indexOf(w)&&delete B[w],J.length&&J.indexOf(w)>-1&&delete B[w])}C.time("limitFields")}if(b.$elemMatch){C.data("flag.elemMatch",!0),C.time("projection-elemMatch");for(v in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length)for(x=0;x<z.length;x++)if(E._match(z[x],b.$elemMatch[v],"",{})){y.set(e[w],v,[z[x]]);break}C.time("projection-elemMatch")}if(b.$elemsMatch){C.data("flag.elemsMatch",!0),C.time("projection-elemsMatch");for(v in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length){for(A=[],x=0;x<z.length;x++)E._match(z[x],b.$elemsMatch[v],"",{})&&A.push(z[x]);y.set(e[w],v,A)}C.time("projection-elemsMatch")}return C.stop(),e.__fdbOp=C,e},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a){var b=this.find(a,{$decouple:!1})[0];return b?this._data.indexOf(b):void 0},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=c,e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f=a.shift(),g=[];if(a.length>0){b=this._sort(f,b),d=this.bucket(f.___fdbKey,b);for(e in d)d.hasOwnProperty(e)&&(c=[].concat(a),g=g.concat(this._bucketSort(c,d[e])));return g}return this._sort(f,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw'ForerunnerDB.Collection "'+this.name()+'": $orderBy clause has invalid direction: '+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d={};for(c=0;c<b.length;c++)d[b[c][a]]=d[b[c][a]]||[],d[b[c][a]].push(b[c]);return d},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),r.push("$as"in b.$join[d][e]?b.$join[d][e].$as:e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];m.subDocs.push(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.noStats?m.subDocs:(m.pathFound||(m.err="No objects found in the parent documents with a matching path of: "+b),m)},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw'ForerunnerDB.Collection "'+this.name()+'": Collection diffing requires that both collections have the same primary key!';for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e);break;case"update":e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f);break;case"remove":e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({object:function(a){return this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+this.name()+'": Cannot get collection '+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log("Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b).db(this),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+this.name()+'": Cannot get collection with undefined name!'}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._collection)this._collection.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,count:this._collection[b].count()}):c.push({name:b,count:this._collection[b].count()}));return c.sort(function(a,b){return a.name.localeCompare(b.name)}),c},d.finishModule("Collection"),b.exports=n},{"./Crc":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":21,"./Path":22,"./ReactorIO":24,"./Shared":25}],3:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": All collections in a collection group must have the same primary key!'}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(){if("dropped"!==this._state){var a,b,c;if(this._debug&&console.log("Dropping collection group "+this._name),this._state="dropped",this._collections&&this._collections.length)for(b=[].concat(this._collections),a=0;a<b.length;a++)this.removeCollection(b[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]);this.emit("drop",this)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup;
},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":2,"./Shared":25}],4:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a){this.init.apply(this,arguments)};h.prototype.init=function(){this._db={},this._debug={}},h.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),h.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},h.moduleLoaded=h.prototype.moduleLoaded,h.version=h.prototype.version,h.shared=d,h.prototype.shared=d,d.addModule("Core",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),h.prototype._isServer=!1,h.prototype.isClient=function(){return!this._isServer},h.prototype.isServer=function(){return this._isServer},h.prototype.isClient=function(){return!this._isServer},h.prototype.isServer=function(){return this._isServer},h.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=h},{"./Db.js":6,"./Metrics.js":10,"./Overload":21,"./Shared":25}],5:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],6:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a){this.init.apply(this,arguments)};j.prototype.init=function(a){this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d=d.concat("string"===e?c.peek(a):c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if("dropped"!==this._state){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if("dropped"!==this._state){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a).core(this),this._db[a]},e.prototype.databases=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._db)this._db.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,collectionCount:this._db[b].collections().length}):c.push({name:b,collectionCount:this._db[b].collections().length}));return c.sort(function(a,b){return a.name.localeCompare(b.name)}),c},b.exports=j},{"./Collection.js":2,"./Crc.js":5,"./Metrics.js":10,"./Overload":21,"./Shared":25}],7:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){},g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new(f.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(f.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},g.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},g.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./Path":22,"./Shared":25}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":22,"./Shared":25}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":25}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":20,"./Shared":25}],11:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],12:[function(a,b,c){"use strict";var d={chain:function(a){this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e=this._chain,f=e.length;for(d=0;f>d;d++)e[d].chainReceive(this,a,b,c)}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],13:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload");d={store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}return void 0},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=JSON.stringify(a),e=[];for(c=0;b>c;c++)e.push(JSON.parse(d));return e}return JSON.parse(JSON.stringify(a))}return void 0},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}])},b.exports=d},{"./Overload":21}],14:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],15:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d;if(this._listeners[a]["*"]){var e=this._listeners[a]["*"];for(d=e.length,c=0;d>c;c++)e[c].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&&b[0]&&b[0][this._primaryKey]){var f,g,h=this._listeners[a];for(d=b.length,c=0;d>c;c++)if(h[b[c][this._primaryKey]])for(f=h[b[c][this._primaryKey]].length,g=0;f>g;g++)h[b[c][this._primaryKey]][g].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};b.exports=e},{"./Overload":21}],16:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d){var e,f,g,h,i,j,k,l=typeof a,m=typeof b,n=!0;if(d=d||{},d.$rootQuery||(d.$rootQuery=b),"string"!==l&&"number"!==l||"string"!==m&&"number"!==m){for(k in b)if(b.hasOwnProperty(k)){if(e=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],d),i>-1)){if(i){if("or"===c)return!0}else n=i;e=!0}if(!e&&b[k]instanceof RegExp)if(e=!0,"object"==typeof a&&void 0!==a[k]&&b[k].test(a[k])){if("or"===c)return!0}else n=!1;if(!e)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],f,d)){if("or"===c)return!0}else n=!1;else if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else n=!1;else if(a&&a[k]===b[k]){if("or"===c)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else n=!1;if("and"===c&&!n)return!1}}else"number"===l?a!==b&&(n=!1):a.localeCompare(b)&&(n=!1);return n},_matchOp:function(a,b,c,d){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$or":for(var e=0;e<c.length;e++)if(this._match(b,c[e],"and",d))return!0;return!1;case"$and":for(var f=0;f<c.length;f++)if(!this._match(b,c[f],"and",d))return!1;return!0;case"$in":if(c instanceof Array){var g,h=c,i=h.length;for(g=0;i>g;g++)if(h[g]===b)return!0;return!1}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use an $in operator on a non-array key: '+a;case"$nin":if(c instanceof Array){var j,k=c,l=k.length;for(j=0;l>j;j++)if(k[j]===b)return!1;return!0}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use a $nin operator on a non-array key: '+a;case"$distinct":d.$rootQuery["//distinctLookup"]=d.$rootQuery["//distinctLookup"]||{};for(var m in c)if(c.hasOwnProperty(m))return d.$rootQuery["//distinctLookup"][m]=d.$rootQuery["//distinctLookup"][m]||{},d.$rootQuery["//distinctLookup"][m][b[m]]?!1:(d.$rootQuery["//distinctLookup"][m][b[m]]=!0,!0)}return-1}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":21}],19:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "'+b+'" for "'+this.name()+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for "'+this.name()+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c=!1;return a.length>0&&(1===b?(a.pop(),c=!0):-1===b&&(a.shift(),c=!0)),c}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":22,"./Shared":25}],21:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)f.push(e);if(d=f.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=f.length;b>=0;b--)if(d=f.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw'ForerunnerDB.Overload "'+this.name()+'": Overloaded method does not have a matching signature for the passed arguments: '+JSON.stringify(f)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],22:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else f.push(b?{path:g,value:a[d]}:{path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":25}],23:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("localforage");k=function(){this.init.apply(this,arguments)},k.prototype.init=function(a){a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),n.config({driver:[n.INDEXEDDB,n.WEBSQL,n.LOCALSTORAGE],name:"ForerunnerDB",storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,
k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":n.setDriver(n.LOCALSTORAGE);break;case"WEBSQL":n.setDriver(n.WEBSQL);break;case"INDEXEDDB":n.setDriver(n.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return n.driver()},k.prototype.save=function(a,b,c){var d;switch(d=function(a,b){a="object"==typeof a?"json::fdb::"+JSON.stringify(a):"raw::fdb::"+a,b&&b(!1,a)},this.mode()){case"localforage":d(b,function(b,d){n.setItem(a,d).then(function(a){c&&c(!1,a)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c,d,e;switch(e=function(a,b){if(a){switch(c=a.split("::fdb::"),c[0]){case"json":d=JSON.parse(c[1]);break;case"raw":d=c[1]}b&&b(!1,d)}else b&&b(!1,a)},this.mode()){case"localforage":n.getItem(a).then(function(a){e(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":n.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){"dropped"!==this._state&&this.drop(!0)},"function":function(a){"dropped"!==this._state&&this.drop(!0,a)},"boolean":function(a){if("dropped"!==this._state){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";if(!this._db)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when the collection is not attached to a database!";this._db.persist.drop(this._name)}f.apply(this)}},"boolean, function":function(a,b){"dropped"!==this._state&&(a&&(this._name?this._db?this._db.persist.drop(this._name,b):b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"):b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")),f.apply(this,b))}}),e.prototype.save=function(a){this._name?this._db?this._db.persist.save(this._name,this._data,a):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;this._name?this._db?this._db.persist.load(this._name,function(c,d){c?a&&a(c):(d&&b.setData(d),a&&a(!1))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},d.prototype.init=function(){this.persist=new k(this),i.apply(this,arguments)},d.prototype.load=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].load(b)},d.prototype.save=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].save(b)},m.finishModule("Persist"),b.exports=k},{"./Collection":2,"./CollectionGroup":3,"./Shared":25,localforage:33}],24:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return"dropped"!==this._state&&(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":25}],25:[function(a,b,c){"use strict";var d={version:"1.3.40",modules:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:function(a,b){var c=this.mixins[b];if(!c)throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])},synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:a("./Overload"),mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating")}};d.mixin(d,"Mixin.Events"),b.exports=d},{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Triggers":18,"./Mixin.Updating":19,"./Overload":21}],26:[function(a,b,c){function d(){if(!h){h=!0;for(var a,b=g.length;b;){a=g,g=[];for(var c=-1;++c<b;)a[c]();b=g.length}h=!1}}function e(){}var f=b.exports={},g=[],h=!1;f.nextTick=function(a){g.push(a),h||setTimeout(d,0)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=e,f.addListener=e,f.once=e,f.off=e,f.removeListener=e,f.removeAllListeners=e,f.emit=e,f.binding=function(a){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(a){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},{}],27:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:29}],28:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":27,asap:29}],29:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:26}],30:[function(a,b,c){(function(){"use strict";function c(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new o(function(a,d){var e=p.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(){e.result.createObjectStore(c.storeName)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return m(d,b),d}function e(a,b){var c=this,d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=a(c.value,c.key,h++);void 0!==d?b(d):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return m(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new o(function(c,e){d.ready().then(function(){var f=d._dbInfo,g=f.db.transaction(f.storeName,"readwrite"),h=g.objectStore(f.storeName);null===b&&(b=void 0);var i=h.put(b,a);g.oncomplete=function(){void 0===b&&(b=null),c(b)},g.onabort=g.onerror=function(){e(i.error)}})["catch"](e)});return m(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(a){var b=a.target.error;"QuotaExceededError"===b&&d(b)}})["catch"](d)});return m(d,b),d}function h(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){c(g.error)}})["catch"](c)});return m(c,a),c}function i(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new o(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function m(a,b){b&&a.then(function(a){n(b,a)},function(a){b(a)})}function n(a,b){return a?setTimeout(function(){return a(null,b)},0):void 0}var o="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,p=p||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(p){var q={_driver:"asyncStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};"undefined"!=typeof b&&b.exports?b.exports=q:"function"==typeof define&&define.amd?define("asyncStorage",function(){return q}):this.asyncStorage=q}}).call(window)},{promise:28}],31:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=0;e>f;f++){var g=p.key(f),h=p.getItem(g);if(h&&(h=o.deserialize(h)),h=a(h,g.substring(d),f+1),void 0!==h)return h}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){("QuotaExceededError"===i.name||"NS_ERROR_DOM_QUOTA_REACHED"===i.name)&&f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":34,promise:28}],32:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":34,promise:28}],33:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){if(n===l.DEFINE)return void a([f],function(a){i._extend(a),c()});if(n===l.EXPORT){var k;switch(f){case i.INDEXEDDB:k=a("./drivers/indexeddb");break;case i.LOCALSTORAGE:k=a("./drivers/localstorage");break;case i.WEBSQL:k=a("./drivers/websql")}i._extend(k)}else i._extend(q[f])}else{if(!h[f])return i._driverSet=g.reject(j),void d(j);i._extend(h[f])}c()}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":30,"./drivers/localstorage":31,"./drivers/websql":32,promise:28}],34:[function(a,b,c){(function(){"use strict";function a(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,f=g;a instanceof ArrayBuffer?(d=a,f+=i):(d=a.buffer,"[object Int8Array]"===c?f+=k:"[object Uint8Array]"===c?f+=l:"[object Uint8ClampedArray]"===c?f+=m:"[object Int16Array]"===c?f+=n:"[object Uint16Array]"===c?f+=p:"[object Int32Array]"===c?f+=o:"[object Uint32Array]"===c?f+=q:"[object Float32Array]"===c?f+=r:"[object Float64Array]"===c?f+=s:b(new Error("Failed to get type for BinaryArray"))),b(f+e(d))}else if("[object Blob]"===c){var h=new FileReader;h.onload=function(){var a=e(this.result);b(g+j+a)},h.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(t){window.console.error("Couldn't convert value into a JSON string: ",a),b(null,t)}}function c(a){if(a.substring(0,h)!==g)return JSON.parse(a);var b=a.substring(t),c=a.substring(h,t),e=d(b);switch(c){case i:return e;case j:return new Blob([e]);case k:return new Int8Array(e);case l:return new Uint8Array(e);case m:return new Uint8ClampedArray(e);case n:return new Int16Array(e);case p:return new Uint16Array(e);case o:return new Int32Array(e);case q:return new Uint32Array(e);case r:return new Float32Array(e);case s:return new Float64Array(e);default:throw new Error("Unkown type: "+c)}}function d(a){var b,c,d,e,g,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=f.indexOf(a[b]),d=f.indexOf(a[b+1]),e=f.indexOf(a[b+2]),g=f.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&g;return k}function e(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=f[c[b]>>2],d+=f[(3&c[b])<<4|c[b+1]>>4],d+=f[(15&c[b+1])<<2|c[b+2]>>6],d+=f[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g="__lfsc__:",h=g.length,i="arbf",j="blob",k="si08",l="ui08",m="uic8",n="si16",o="si32",p="ur16",q="ui32",r="fl32",s="fl64",t=h+i.length,u={serialize:a,deserialize:c,stringToBuffer:d,bufferToString:e};"undefined"!=typeof b&&b.exports?b.exports=u:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return u}):this.localforageSerializer=u}).call(window)},{}]},{},[1]); |
ajax/libs/flocks.js/0.16.18/flocks.min.js | rigdern/cdnjs | if("undefined"===typeof React)var React=require("react");
(function(){function f(a){return"[object Array]"===Object.prototype.toString.call(a)}function k(a){return"undefined"===typeof a}function u(a){return"object"!==typeof a||"[object Array]"===Object.prototype.toString.call(a)?!1:!0}function c(a,b){if("string"===typeof a)if(~"warn debug error log info exception assert".split(" ").indexOf(a,0))console[a]("Flocks2 ["+a+"] "+b.toString());else console.log("Flocks2 [Unknown level] "+b.toString());else k(d.flocks2Config)?console.log("Flocks2 pre-config ["+
a.toString()+"] "+b.toString()):d.flocks2Config.log_level>=a&&console.log("Flocks2 ["+a.toString()+"] "+b.toString())}function l(){c(3," - Flocks2 attempting update");if(!v)return c(1," x Flocks2 skipped update: root is not initialized"),null;if(m)return c(1," x Flocks2 skipped update: lock count updateBlocks is non-zero"),null;if(!w(d))return c(0," ! Flocks2 rolling back update: handler rejected propset"),d=x,null;x=d;c(3," - Flocks2 update passed");React.render(React.createFactory(p)({flocks2context:d}),
document.body);c(3," - Flocks2 update complete; finalizing");y();return!0}function z(a,b){if("string"!==typeof a)throw b||"Argument must be a string";}function A(a,b){if(!f(a))throw b||"Argument must be an array";}function B(a,b){if(!u(a))throw b||"Argument must be a non-array object";}function C(a,b,c){var d;if(!f(a))throw"Path must be an array!";if(0===a.length)return b;if(1===a.length)return d=b[a[0]],b[a[0]]=c,d;if(-1!==["string","number"].indexOf(typeof a[0]))return d=a.splice(1,Number.MAX_VALUE),
C(d,b[a[0]],c)}function D(a,b){A(a,"Flocks2 setByPathh/2 must take an array for its key");c(1,' - Flocks2 setByPath "'+a.join("|")+'"');C(a,d,b);l()}function q(a,b){c(3," - Flocks2 multi-set");if("string"===typeof a)z(a,"Flocks2 set/2 must take a string for its key"),d[a]=b,c(1,' - Flocks2 setByKey "'+a+'"'),l();else if(f(a))D(a,b);else throw"Flocks2 set/1,2 key must be a string or an array";}function r(a,b){var c;if(!f(a))throw"path must be an array!";if(0===a.length)return b;if(1===a.length)return b[a[0]];
if(-1!==["string","number"].indexOf(typeof a[0]))return c=a.splice(1,Number.MAX_VALUE),r(c,b[a[0]])}function E(a){console.log("ERROR: stub called!");B(a,"Flocks2 update/1 must take a plain object")}function H(){++m}function F(){if(0>=m)throw"unlock()ed with no lock!";--m;l()}function t(a){var b=a.constructor(),c;if(null===a||"object"!==typeof a)return a;for(c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}function G(a){if(k(a))return[n];if(f(a)){if(~a.indexOf(n,0))return a;a=t(a);a.push(n);return a}throw"Original mixin list must be an array or undefined!";
}var n,h,v=!1,m=0,p,w=function(a){return!0},y=function(){return!0},x={},d={};h={flocks2context:React.PropTypes.object};n={contextTypes:h,childContextTypes:h,componentWillMount:function(){c(1," - Flocks2 component will mount: "+this.constructor.displayName);c(3,k(this.props.flocks2context)?" - No F2 Context Prop":" - F2 Context Prop found");c(3,k(this.context.flocks2context)?" - No F2 Context":" - F2 Context found");this.props.flocks2context&&(this.context.flocks2context=this.props.flocks2context);
this.fupdate=function(a){return E(a)};this.fgetpath=function(a,b){return r(a,b)};this.fset=function(a,b){return q(a,b)};this.fsetpath=function(a,b){return q(a,b)};this.flock=function(){++m};this.funlock=function(){return F()};this.fctx=this.context.flocks2context},getChildContext:function(){return this.context}};h={version:"0.16.17",plumbing:n,createClass:function(a){a.mixins=G(a.mixins);return React.createClass(a)},mount:function(a,b){var g=a||{},f=b||{},e=function(){console.log("ERROR: stub called!");
l()},e={get:e,override:e,clear:e,get_path:r,set:q,set_path:D,update:E,lock:H,unlock:F};g.log_level=g.log_level||-1;p=g.control;f.flocks2Config=g;d=f;c(1,"Flocks2 root creation begins");if(!p)throw"Flocks2 fatal error: must provide a control in create/2 FlocksConfig";g.handler&&(w=g.handler,c(3," - Flocks2 handler assigned"));g.finalizer&&(y=g.finalizer,c(3," - Flocks2 finalizer assigned"));g.preventAutoContext?c(2," - Flocks2 skipping auto-context"):(c(2," - Flocks2 engaging auto-context"),this.fctx=
t(d));c(3,"Flocks2 creation finished; initializing");v=!0;l();c(3,"Flocks2 expose updater");this.fupd=e;this.fset=e.set;this.fgetpath=e.get_path;this.flock=e.lock;this.funlock=e.unlock;this.fupdate=e.update;c(3,"Flocks2 initialization finished");return e},clone:t,isArray:f,isUndefined:k,isNonArrayObject:u,enforceString:z,enforceArray:A,enforceNonArrayObject:B,atLeastFlocks:G};"undefined"!==typeof module?module.exports=h:window.flocks=h})();
|
src/page/CommentPage.js | jerryshew/react-uikits | import React, { Component } from 'react';
import {CN, TitleBlock} from '../util/tools';
import {NS, COLORS} from '../constant';
import CodeView from './CodeView';
export class CommentPage extends Component {
render() {
return (
<div>
{TitleBlock('评论')}
<ul>
<li>
<CodeView component={
<div className={CN('comments')}>
<div className={CN('comment')}>
<div className="avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar.png"/>
</div>
<div className="content">
<div className="nickname">lacuna fario</div>
<div className="extra">
<span>2016-05-32 8:20 pm</span>
</div>
<div className="text">
Lacuna is a company name from a movie named <i>"Eternal sunshine of the spotless mind"</i>
</div>
<div className="action">
<a href="javascript:;">reply</a>
<a href="javascript:;">delete</a>
</div>
</div>
<div className="comments">
<div className={CN('comment')}>
<div className="avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar0.png"/>
</div>
<div className="content">
<div className="nickname">lily</div>
<div className="extra">
<span>2016-05-32 8:10 pm</span>
</div>
<div className="text">
Emm, that is interesting. I supposed.
</div>
<div className="action">
<a href="javascript:;">reply</a>
<a href="javascript:;">delete</a>
</div>
</div>
</div>
<div className={CN('comment')}>
<div className="avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar.png"/>
</div>
<div className="content">
<div className="nickname">lacuna fario</div>
<div className="extra">
<span>2016-05-32 8:10 pm</span>
</div>
<div className="text">
Okay, you will never know.
</div>
<div className="action">
<a href="javascript:;">reply</a>
<a href="javascript:;">delete</a>
</div>
</div>
</div>
</div>
</div>
<div className={CN('comment')}>
<div className="avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar0.png"/>
</div>
<div className="content">
<div className="nickname">lily</div>
<div className="extra">
<span>2016-05-32 8:10 pm</span>
</div>
<div className="text">
Emm, that is interesting. I supposed.
</div>
<div className="action">
<a href="javascript:;">reply</a>
<a href="javascript:;">delete</a>
</div>
</div>
</div>
</div>
}>
{`<div className="${CN('comment')}">
<div className="avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar.png"/>
</div>
<div className="content">
<div className="nickname">lacuna fario</div>
<div className="extra">
<span>2016-05-32 8:20 pm</span>
</div>
<div className="text">
Lacuna is a company name from a movie named <i>"Eternal sunshine of the spotless mind"</i>
</div>
<div className="action">
<a href="javascript:;">reply</a>
<a href="javascript:;">delete</a>
</div>
</div>
<div className="comments">
<div className="${CN('comment')}">
<div className="avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar0.png"/>
</div>
<div className="content">
<div className="nickname">lily</div>
<div className="extra">
<span>2016-05-32 8:10 pm</span>
</div>
<div className="text">
Emm, that is interesting. I supposed.
</div>
<div className="action">
<a href="javascript:;">reply</a>
<a href="javascript:;">delete</a>
</div>
</div>
</div>
</div>
</div>
`}
</CodeView>
<br/>
</li>
<li>
<h4>向右浮动的额外信息区</h4>
<CodeView component={
<div className={CN('comment')}>
<div className="avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar.png"/>
</div>
<div className="content">
<div className="nickname">lacuna fario</div>
<div className="extra right">
<span>2016-05-32 8:20 pm</span>
</div>
<div className="text">
Lacuna is a company name from a movie named <i>"Eternal sunshine of the spotless mind"</i>
</div>
<div className="action">
<a href="javascript:;">reply</a>
<a href="javascript:;">delete</a>
</div>
</div>
</div>
}>
{`<div className="${CN('comment')}">
...
<div className="content">
...
<div className="extra right">
<span>2016-05-32 8:20 pm</span>
</div>
...
</div>
</div>
`}
</CodeView>
<br/>
</li>
<li>
<h4>圆圈头像</h4>
<CodeView component={
<div className={CN('comment')}>
<div className="round avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar.png"/>
</div>
<div className="content">
<div className="nickname">lacuna fario</div>
<div className="extra">
<span>replied to</span>
<a href="javascript:;">lily</a>
</div>
<div className="extra">
<span>2016-05-32 8:20 pm</span>
</div>
<div className="text">
Lacuna is a company name from a movie named <i>"Eternal sunshine of the spotless mind"</i>
</div>
<div className="action">
<a href="javascript:;">reply</a>
<a href="javascript:;">delete</a>
</div>
</div>
</div>
}>
{`<div className="${CN('comment')}">
<div className="round avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar.png"/>
</div>
...
</div>
`}
</CodeView>
<br/>
</li>
<li>
<CodeView component={
<div className={CN('comments')}>
<div className={CN('loading comment')}>
<div className="avatar">
<img src="http://braavos.me/dot-css/dist/img/avatar.png"/>
</div>
<div className="content">
<div className="nickname">lacuna fario</div>
<div className="extra">
<span>2016-05-32 8:20 pm</span>
</div>
<div className="text">
Lacuna is a company name from a movie named <i>"Eternal sunshine of the spotless mind"</i>
</div>
<div className="action">
<a href="javascript:;">reply</a>
<a href="javascript:;">delete</a>
</div>
</div>
</div>
</div>
}>
{`<div className="${CN('loading comment')}">
...
</div>`}
</CodeView>
<br/>
</li>
</ul>
</div>
);
}
}
|
frontend/src/components/organizationProfile/common/profileConfirmation.js | unicef/un-partner-portal | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { compose } from 'ramda';
import { withStyles } from 'material-ui/styles';
import Typography from 'material-ui/Typography';
import Checkbox from 'material-ui/Checkbox';
import ProfileViewLink from './profileViewLink';
import { formatDateForPrint } from '../../../helpers/dates';
const messages = {
confirm: 'I confirm that my profile is up to date',
lastUpdate: 'Last profile update:',
notSure: 'Not sure?',
};
const styleSheet = theme => ({
checkboxContainer: {
// marginLeft: -14,
},
paddingTop: {
padding: '12px 0px 0px 0px',
},
alignVertical: {
display: 'flex',
alignItems: 'center',
},
captionStyle: {
color: theme.palette.primary[500],
},
});
const ProfileConfirmation = (props) => {
const { classes, update, disabled, checked, partnerId, onChange } = props;
return (
<div className={classes.checkboxContainer}>
<div className={classes.alignVertical}>
<Checkbox
disabled={disabled}
checked={checked}
onChange={onChange}
/>
<div className={classes.paddingTop}>
<Typography type="body1">{messages.confirm}</Typography>
<div className={classes.alignVertical}>
<Typography className={classes.captionStyle} type="body1">
{`${messages.lastUpdate} ${formatDateForPrint(update)}. ${messages.notSure} `}
</Typography>
<ProfileViewLink partnerId={partnerId} />
</div>
</div>
</div>
</div>
);
};
ProfileConfirmation.propTypes = {
classes: PropTypes.object,
disabled: PropTypes.bool,
checked: PropTypes.bool,
partnerId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
onChange: PropTypes.func,
update: PropTypes.string,
};
const mapStateToProps = state => ({
partnerId: state.session.partnerId,
update: state.session.lastUpdate,
});
export default compose(
withStyles(styleSheet, { name: 'ProfileConfirmation' }),
connect(mapStateToProps),
)(ProfileConfirmation);
|
ajax/libs/video.js/4.8.2/video.dev.js | mohitbhatia1994/cdnjs | /**
* @fileoverview Main function src.
*/
// HTML5 Shiv. Must be in <head> to support older browsers.
document.createElement('video');
document.createElement('audio');
document.createElement('track');
/**
* Doubles as the main function for users to create a player instance and also
* the main library object.
*
* **ALIASES** videojs, _V_ (deprecated)
*
* The `vjs` function can be used to initialize or retrieve a player.
*
* var myPlayer = vjs('my_video_id');
*
* @param {String|Element} id Video element or video element ID
* @param {Object=} options Optional options object for config/settings
* @param {Function=} ready Optional ready callback
* @return {vjs.Player} A player instance
* @namespace
*/
var vjs = function(id, options, ready){
var tag; // Element of ID
// Allow for element or ID to be passed in
// String ID
if (typeof id === 'string') {
// Adjust for jQuery ID syntax
if (id.indexOf('#') === 0) {
id = id.slice(1);
}
// If a player instance has already been created for this ID return it.
if (vjs.players[id]) {
return vjs.players[id];
// Otherwise get element for ID
} else {
tag = vjs.el(id);
}
// ID is a media element
} else {
tag = id;
}
// Check for a useable element
if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also
throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns
}
// Element may have a player attr referring to an already created player instance.
// If not, set up a new player and return the instance.
return tag['player'] || new vjs.Player(tag, options, ready);
};
// Extended name, also available externally, window.videojs
var videojs = window['videojs'] = vjs;
// CDN Version. Used to target right flash swf.
vjs.CDN_VERSION = '4.8';
vjs.ACCESS_PROTOCOL = ('https:' == document.location.protocol ? 'https://' : 'http://');
/**
* Global Player instance options, surfaced from vjs.Player.prototype.options_
* vjs.options = vjs.Player.prototype.options_
* All options should use string keys so they avoid
* renaming by closure compiler
* @type {Object}
*/
vjs.options = {
// Default order of fallback technology
'techOrder': ['html5','flash'],
// techOrder: ['flash','html5'],
'html5': {},
'flash': {},
// Default of web browser is 300x150. Should rely on source width/height.
'width': 300,
'height': 150,
// defaultVolume: 0.85,
'defaultVolume': 0.00, // The freakin seaguls are driving me crazy!
// default playback rates
'playbackRates': [],
// Add playback rate selection by adding rates
// 'playbackRates': [0.5, 1, 1.5, 2],
// default inactivity timeout
'inactivityTimeout': 2000,
// Included control sets
'children': {
'mediaLoader': {},
'posterImage': {},
'textTrackDisplay': {},
'loadingSpinner': {},
'bigPlayButton': {},
'controlBar': {},
'errorDisplay': {}
},
'language': document.getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en',
// locales and their language translations
'languages': {},
// Default message to show when a video cannot be played.
'notSupportedMessage': 'No compatible source was found for this video.'
};
// Set CDN Version of swf
// The added (+) blocks the replace from changing this 4.8 string
if (vjs.CDN_VERSION !== 'GENERATED'+'_CDN_VSN') {
videojs.options['flash']['swf'] = vjs.ACCESS_PROTOCOL + 'vjs.zencdn.net/'+vjs.CDN_VERSION+'/video-js.swf';
}
/**
* Utility function for adding languages to the default options. Useful for
* amending multiple language support at runtime.
*
* Example: vjs.addLanguage('es', {'Hello':'Hola'});
*
* @param {String} code The language code or dictionary property
* @param {Object} data The data values to be translated
* @return {Object} The resulting global languages dictionary object
*/
vjs.addLanguage = function(code, data){
if(vjs.options['languages'][code] !== undefined) {
vjs.options['languages'][code] = vjs.util.mergeOptions(vjs.options['languages'][code], data);
} else {
vjs.options['languages'][code] = data;
}
return vjs.options['languages'];
};
/**
* Global player list
* @type {Object}
*/
vjs.players = {};
/*!
* Custom Universal Module Definition (UMD)
*
* Video.js will never be a non-browser lib so we can simplify UMD a bunch and
* still support requirejs and browserify. This also needs to be closure
* compiler compatible, so string keys are used.
*/
if (typeof define === 'function' && define['amd']) {
define([], function(){ return videojs; });
// checking that module is an object too because of umdjs/umd#35
} else if (typeof exports === 'object' && typeof module === 'object') {
module['exports'] = videojs;
}
/**
* Core Object/Class for objects that use inheritance + contstructors
*
* To create a class that can be subclassed itself, extend the CoreObject class.
*
* var Animal = CoreObject.extend();
* var Horse = Animal.extend();
*
* The constructor can be defined through the init property of an object argument.
*
* var Animal = CoreObject.extend({
* init: function(name, sound){
* this.name = name;
* }
* });
*
* Other methods and properties can be added the same way, or directly to the
* prototype.
*
* var Animal = CoreObject.extend({
* init: function(name){
* this.name = name;
* },
* getName: function(){
* return this.name;
* },
* sound: '...'
* });
*
* Animal.prototype.makeSound = function(){
* alert(this.sound);
* };
*
* To create an instance of a class, use the create method.
*
* var fluffy = Animal.create('Fluffy');
* fluffy.getName(); // -> Fluffy
*
* Methods and properties can be overridden in subclasses.
*
* var Horse = Animal.extend({
* sound: 'Neighhhhh!'
* });
*
* var horsey = Horse.create('Horsey');
* horsey.getName(); // -> Horsey
* horsey.makeSound(); // -> Alert: Neighhhhh!
*
* @class
* @constructor
*/
vjs.CoreObject = vjs['CoreObject'] = function(){};
// Manually exporting vjs['CoreObject'] here for Closure Compiler
// because of the use of the extend/create class methods
// If we didn't do this, those functions would get flattend to something like
// `a = ...` and `this.prototype` would refer to the global object instead of
// CoreObject
/**
* Create a new object that inherits from this Object
*
* var Animal = CoreObject.extend();
* var Horse = Animal.extend();
*
* @param {Object} props Functions and properties to be applied to the
* new object's prototype
* @return {vjs.CoreObject} An object that inherits from CoreObject
* @this {*}
*/
vjs.CoreObject.extend = function(props){
var init, subObj;
props = props || {};
// Set up the constructor using the supplied init method
// or using the init of the parent object
// Make sure to check the unobfuscated version for external libs
init = props['init'] || props.init || this.prototype['init'] || this.prototype.init || function(){};
// In Resig's simple class inheritance (previously used) the constructor
// is a function that calls `this.init.apply(arguments)`
// However that would prevent us from using `ParentObject.call(this);`
// in a Child constuctor because the `this` in `this.init`
// would still refer to the Child and cause an inifinite loop.
// We would instead have to do
// `ParentObject.prototype.init.apply(this, argumnents);`
// Bleh. We're not creating a _super() function, so it's good to keep
// the parent constructor reference simple.
subObj = function(){
init.apply(this, arguments);
};
// Inherit from this object's prototype
subObj.prototype = vjs.obj.create(this.prototype);
// Reset the constructor property for subObj otherwise
// instances of subObj would have the constructor of the parent Object
subObj.prototype.constructor = subObj;
// Make the class extendable
subObj.extend = vjs.CoreObject.extend;
// Make a function for creating instances
subObj.create = vjs.CoreObject.create;
// Extend subObj's prototype with functions and other properties from props
for (var name in props) {
if (props.hasOwnProperty(name)) {
subObj.prototype[name] = props[name];
}
}
return subObj;
};
/**
* Create a new instace of this Object class
*
* var myAnimal = Animal.create();
*
* @return {vjs.CoreObject} An instance of a CoreObject subclass
* @this {*}
*/
vjs.CoreObject.create = function(){
// Create a new object that inherits from this object's prototype
var inst = vjs.obj.create(this.prototype);
// Apply this constructor function to the new object
this.apply(inst, arguments);
// Return the new object
return inst;
};
/**
* @fileoverview Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
* (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
* This should work very similarly to jQuery's events, however it's based off the book version which isn't as
* robust as jquery's, so there's probably some differences.
*/
/**
* Add an event listener to element
* It stores the handler function in a separate cache object
* and adds a generic handler to the element's event,
* along with a unique id (guid) to the element.
* @param {Element|Object} elem Element or object to bind listeners to
* @param {String|Array} type Type of event to bind to.
* @param {Function} fn Event listener.
* @private
*/
vjs.on = function(elem, type, fn){
if (vjs.obj.isArray(type)) {
return _handleMultipleEvents(vjs.on, elem, type, fn);
}
var data = vjs.getData(elem);
// We need a place to store all our handler data
if (!data.handlers) data.handlers = {};
if (!data.handlers[type]) data.handlers[type] = [];
if (!fn.guid) fn.guid = vjs.guid++;
data.handlers[type].push(fn);
if (!data.dispatcher) {
data.disabled = false;
data.dispatcher = function (event){
if (data.disabled) return;
event = vjs.fixEvent(event);
var handlers = data.handlers[event.type];
if (handlers) {
// Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
var handlersCopy = handlers.slice(0);
for (var m = 0, n = handlersCopy.length; m < n; m++) {
if (event.isImmediatePropagationStopped()) {
break;
} else {
handlersCopy[m].call(elem, event);
}
}
}
};
}
if (data.handlers[type].length == 1) {
if (elem.addEventListener) {
elem.addEventListener(type, data.dispatcher, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + type, data.dispatcher);
}
}
};
/**
* Removes event listeners from an element
* @param {Element|Object} elem Object to remove listeners from
* @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element.
* @param {Function} fn Specific listener to remove. Don't incldue to remove listeners for an event type.
* @private
*/
vjs.off = function(elem, type, fn) {
// Don't want to add a cache object through getData if not needed
if (!vjs.hasData(elem)) return;
var data = vjs.getData(elem);
// If no events exist, nothing to unbind
if (!data.handlers) { return; }
if (vjs.obj.isArray(type)) {
return _handleMultipleEvents(vjs.off, elem, type, fn);
}
// Utility function
var removeType = function(t){
data.handlers[t] = [];
vjs.cleanUpEvents(elem,t);
};
// Are we removing all bound events?
if (!type) {
for (var t in data.handlers) removeType(t);
return;
}
var handlers = data.handlers[type];
// If no handlers exist, nothing to unbind
if (!handlers) return;
// If no listener was provided, remove all listeners for type
if (!fn) {
removeType(type);
return;
}
// We're only removing a single handler
if (fn.guid) {
for (var n = 0; n < handlers.length; n++) {
if (handlers[n].guid === fn.guid) {
handlers.splice(n--, 1);
}
}
}
vjs.cleanUpEvents(elem, type);
};
/**
* Clean up the listener cache and dispatchers
* @param {Element|Object} elem Element to clean up
* @param {String} type Type of event to clean up
* @private
*/
vjs.cleanUpEvents = function(elem, type) {
var data = vjs.getData(elem);
// Remove the events of a particular type if there are none left
if (data.handlers[type].length === 0) {
delete data.handlers[type];
// data.handlers[type] = null;
// Setting to null was causing an error with data.handlers
// Remove the meta-handler from the element
if (elem.removeEventListener) {
elem.removeEventListener(type, data.dispatcher, false);
} else if (elem.detachEvent) {
elem.detachEvent('on' + type, data.dispatcher);
}
}
// Remove the events object if there are no types left
if (vjs.isEmpty(data.handlers)) {
delete data.handlers;
delete data.dispatcher;
delete data.disabled;
// data.handlers = null;
// data.dispatcher = null;
// data.disabled = null;
}
// Finally remove the expando if there is no data left
if (vjs.isEmpty(data)) {
vjs.removeData(elem);
}
};
/**
* Fix a native event to have standard property values
* @param {Object} event Event object to fix
* @return {Object}
* @private
*/
vjs.fixEvent = function(event) {
function returnTrue() { return true; }
function returnFalse() { return false; }
// Test if fixing up is needed
// Used to check if !event.stopPropagation instead of isPropagationStopped
// But native events return true for stopPropagation, but don't have
// other expected methods like isPropagationStopped. Seems to be a problem
// with the Javascript Ninja code. So we're just overriding all events now.
if (!event || !event.isPropagationStopped) {
var old = event || window.event;
event = {};
// Clone the old object so that we can modify the values event = {};
// IE8 Doesn't like when you mess with native event properties
// Firefox returns false for event.hasOwnProperty('type') and other props
// which makes copying more difficult.
// TODO: Probably best to create a whitelist of event props
for (var key in old) {
// Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
// Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
if (key !== 'layerX' && key !== 'layerY' && key !== 'keyboardEvent.keyLocation') {
// Chrome 32+ warns if you try to copy deprecated returnValue, but
// we still want to if preventDefault isn't supported (IE8).
if (!(key == 'returnValue' && old.preventDefault)) {
event[key] = old[key];
}
}
}
// The event occurred on this element
if (!event.target) {
event.target = event.srcElement || document;
}
// Handle which other element the event is related to
event.relatedTarget = event.fromElement === event.target ?
event.toElement :
event.fromElement;
// Stop the default browser action
event.preventDefault = function () {
if (old.preventDefault) {
old.preventDefault();
}
event.returnValue = false;
event.isDefaultPrevented = returnTrue;
event.defaultPrevented = true;
};
event.isDefaultPrevented = returnFalse;
event.defaultPrevented = false;
// Stop the event from bubbling
event.stopPropagation = function () {
if (old.stopPropagation) {
old.stopPropagation();
}
event.cancelBubble = true;
event.isPropagationStopped = returnTrue;
};
event.isPropagationStopped = returnFalse;
// Stop the event from bubbling and executing other handlers
event.stopImmediatePropagation = function () {
if (old.stopImmediatePropagation) {
old.stopImmediatePropagation();
}
event.isImmediatePropagationStopped = returnTrue;
event.stopPropagation();
};
event.isImmediatePropagationStopped = returnFalse;
// Handle mouse position
if (event.clientX != null) {
var doc = document.documentElement, body = document.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0);
}
// Handle key presses
event.which = event.charCode || event.keyCode;
// Fix button for mouse clicks:
// 0 == left; 1 == middle; 2 == right
if (event.button != null) {
event.button = (event.button & 1 ? 0 :
(event.button & 4 ? 1 :
(event.button & 2 ? 2 : 0)));
}
}
// Returns fixed-up instance
return event;
};
/**
* Trigger an event for an element
* @param {Element|Object} elem Element to trigger an event on
* @param {Event|Object|String} event A string (the type) or an event object with a type attribute
* @private
*/
vjs.trigger = function(elem, event) {
// Fetches element data and a reference to the parent (for bubbling).
// Don't want to add a data object to cache for every parent,
// so checking hasData first.
var elemData = (vjs.hasData(elem)) ? vjs.getData(elem) : {};
var parent = elem.parentNode || elem.ownerDocument;
// type = event.type || event,
// handler;
// If an event name was passed as a string, creates an event out of it
if (typeof event === 'string') {
event = { type:event, target:elem };
}
// Normalizes the event properties.
event = vjs.fixEvent(event);
// If the passed element has a dispatcher, executes the established handlers.
if (elemData.dispatcher) {
elemData.dispatcher.call(elem, event);
}
// Unless explicitly stopped or the event does not bubble (e.g. media events)
// recursively calls this function to bubble the event up the DOM.
if (parent && !event.isPropagationStopped() && event.bubbles !== false) {
vjs.trigger(parent, event);
// If at the top of the DOM, triggers the default action unless disabled.
} else if (!parent && !event.defaultPrevented) {
var targetData = vjs.getData(event.target);
// Checks if the target has a default action for this event.
if (event.target[event.type]) {
// Temporarily disables event dispatching on the target as we have already executed the handler.
targetData.disabled = true;
// Executes the default action.
if (typeof event.target[event.type] === 'function') {
event.target[event.type]();
}
// Re-enables event dispatching.
targetData.disabled = false;
}
}
// Inform the triggerer if the default was prevented by returning false
return !event.defaultPrevented;
/* Original version of js ninja events wasn't complete.
* We've since updated to the latest version, but keeping this around
* for now just in case.
*/
// // Added in attion to book. Book code was broke.
// event = typeof event === 'object' ?
// event[vjs.expando] ?
// event :
// new vjs.Event(type, event) :
// new vjs.Event(type);
// event.type = type;
// if (handler) {
// handler.call(elem, event);
// }
// // Clean up the event in case it is being reused
// event.result = undefined;
// event.target = elem;
};
/**
* Trigger a listener only once for an event
* @param {Element|Object} elem Element or object to
* @param {String|Array} type
* @param {Function} fn
* @private
*/
vjs.one = function(elem, type, fn) {
if (vjs.obj.isArray(type)) {
return _handleMultipleEvents(vjs.one, elem, type, fn);
}
var func = function(){
vjs.off(elem, type, func);
fn.apply(this, arguments);
};
// copy the guid to the new function so it can removed using the original function's ID
func.guid = fn.guid = fn.guid || vjs.guid++;
vjs.on(elem, type, func);
};
/**
* Loops through an array of event types and calls the requested method for each type.
* @param {Function} fn The event method we want to use.
* @param {Element|Object} elem Element or object to bind listeners to
* @param {String} type Type of event to bind to.
* @param {Function} callback Event listener.
* @private
*/
function _handleMultipleEvents(fn, elem, type, callback) {
vjs.arr.forEach(type, function(type) {
fn(elem, type, callback); //Call the event method for each one of the types
});
}
var hasOwnProp = Object.prototype.hasOwnProperty;
/**
* Creates an element and applies properties.
* @param {String=} tagName Name of tag to be created.
* @param {Object=} properties Element properties to be applied.
* @return {Element}
* @private
*/
vjs.createEl = function(tagName, properties){
var el;
tagName = tagName || 'div';
properties = properties || {};
el = document.createElement(tagName);
vjs.obj.each(properties, function(propName, val){
// Not remembering why we were checking for dash
// but using setAttribute means you have to use getAttribute
// The check for dash checks for the aria-* attributes, like aria-label, aria-valuemin.
// The additional check for "role" is because the default method for adding attributes does not
// add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although
// browsers handle the attribute just fine. The W3C allows for aria-* attributes to be used in pre-HTML5 docs.
// http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem.
if (propName.indexOf('aria-') !== -1 || propName == 'role') {
el.setAttribute(propName, val);
} else {
el[propName] = val;
}
});
return el;
};
/**
* Uppercase the first letter of a string
* @param {String} string String to be uppercased
* @return {String}
* @private
*/
vjs.capitalize = function(string){
return string.charAt(0).toUpperCase() + string.slice(1);
};
/**
* Object functions container
* @type {Object}
* @private
*/
vjs.obj = {};
/**
* Object.create shim for prototypal inheritance
*
* https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
*
* @function
* @param {Object} obj Object to use as prototype
* @private
*/
vjs.obj.create = Object.create || function(obj){
//Create a new function called 'F' which is just an empty object.
function F() {}
//the prototype of the 'F' function should point to the
//parameter of the anonymous function.
F.prototype = obj;
//create a new constructor function based off of the 'F' function.
return new F();
};
/**
* Loop through each property in an object and call a function
* whose arguments are (key,value)
* @param {Object} obj Object of properties
* @param {Function} fn Function to be called on each property.
* @this {*}
* @private
*/
vjs.obj.each = function(obj, fn, context){
for (var key in obj) {
if (hasOwnProp.call(obj, key)) {
fn.call(context || this, key, obj[key]);
}
}
};
/**
* Merge two objects together and return the original.
* @param {Object} obj1
* @param {Object} obj2
* @return {Object}
* @private
*/
vjs.obj.merge = function(obj1, obj2){
if (!obj2) { return obj1; }
for (var key in obj2){
if (hasOwnProp.call(obj2, key)) {
obj1[key] = obj2[key];
}
}
return obj1;
};
/**
* Merge two objects, and merge any properties that are objects
* instead of just overwriting one. Uses to merge options hashes
* where deeper default settings are important.
* @param {Object} obj1 Object to override
* @param {Object} obj2 Overriding object
* @return {Object} New object. Obj1 and Obj2 will be untouched.
* @private
*/
vjs.obj.deepMerge = function(obj1, obj2){
var key, val1, val2;
// make a copy of obj1 so we're not ovewriting original values.
// like prototype.options_ and all sub options objects
obj1 = vjs.obj.copy(obj1);
for (key in obj2){
if (hasOwnProp.call(obj2, key)) {
val1 = obj1[key];
val2 = obj2[key];
// Check if both properties are pure objects and do a deep merge if so
if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) {
obj1[key] = vjs.obj.deepMerge(val1, val2);
} else {
obj1[key] = obj2[key];
}
}
}
return obj1;
};
/**
* Make a copy of the supplied object
* @param {Object} obj Object to copy
* @return {Object} Copy of object
* @private
*/
vjs.obj.copy = function(obj){
return vjs.obj.merge({}, obj);
};
/**
* Check if an object is plain, and not a dom node or any object sub-instance
* @param {Object} obj Object to check
* @return {Boolean} True if plain, false otherwise
* @private
*/
vjs.obj.isPlain = function(obj){
return !!obj
&& typeof obj === 'object'
&& obj.toString() === '[object Object]'
&& obj.constructor === Object;
};
/**
* Check if an object is Array
* Since instanceof Array will not work on arrays created in another frame we need to use Array.isArray, but since IE8 does not support Array.isArray we need this shim
* @param {Object} obj Object to check
* @return {Boolean} True if plain, false otherwise
* @private
*/
vjs.obj.isArray = Array.isArray || function(arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
};
/**
* Check to see whether the input is NaN or not.
* NaN is the only JavaScript construct that isn't equal to itself
* @param {Number} num Number to check
* @return {Boolean} True if NaN, false otherwise
* @private
*/
vjs.isNaN = function(num) {
return num !== num;
};
/**
* Bind (a.k.a proxy or Context). A simple method for changing the context of a function
It also stores a unique id on the function so it can be easily removed from events
* @param {*} context The object to bind as scope
* @param {Function} fn The function to be bound to a scope
* @param {Number=} uid An optional unique ID for the function to be set
* @return {Function}
* @private
*/
vjs.bind = function(context, fn, uid) {
// Make sure the function has a unique ID
if (!fn.guid) { fn.guid = vjs.guid++; }
// Create the new function that changes the context
var ret = function() {
return fn.apply(context, arguments);
};
// Allow for the ability to individualize this function
// Needed in the case where multiple objects might share the same prototype
// IF both items add an event listener with the same function, then you try to remove just one
// it will remove both because they both have the same guid.
// when using this, you need to use the bind method when you remove the listener as well.
// currently used in text tracks
ret.guid = (uid) ? uid + '_' + fn.guid : fn.guid;
return ret;
};
/**
* Element Data Store. Allows for binding data to an element without putting it directly on the element.
* Ex. Event listneres are stored here.
* (also from jsninja.com, slightly modified and updated for closure compiler)
* @type {Object}
* @private
*/
vjs.cache = {};
/**
* Unique ID for an element or function
* @type {Number}
* @private
*/
vjs.guid = 1;
/**
* Unique attribute name to store an element's guid in
* @type {String}
* @constant
* @private
*/
vjs.expando = 'vdata' + (new Date()).getTime();
/**
* Returns the cache object where data for an element is stored
* @param {Element} el Element to store data for.
* @return {Object}
* @private
*/
vjs.getData = function(el){
var id = el[vjs.expando];
if (!id) {
id = el[vjs.expando] = vjs.guid++;
vjs.cache[id] = {};
}
return vjs.cache[id];
};
/**
* Returns the cache object where data for an element is stored
* @param {Element} el Element to store data for.
* @return {Object}
* @private
*/
vjs.hasData = function(el){
var id = el[vjs.expando];
return !(!id || vjs.isEmpty(vjs.cache[id]));
};
/**
* Delete data for the element from the cache and the guid attr from getElementById
* @param {Element} el Remove data for an element
* @private
*/
vjs.removeData = function(el){
var id = el[vjs.expando];
if (!id) { return; }
// Remove all stored data
// Changed to = null
// http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/
// vjs.cache[id] = null;
delete vjs.cache[id];
// Remove the expando property from the DOM node
try {
delete el[vjs.expando];
} catch(e) {
if (el.removeAttribute) {
el.removeAttribute(vjs.expando);
} else {
// IE doesn't appear to support removeAttribute on the document element
el[vjs.expando] = null;
}
}
};
/**
* Check if an object is empty
* @param {Object} obj The object to check for emptiness
* @return {Boolean}
* @private
*/
vjs.isEmpty = function(obj) {
for (var prop in obj) {
// Inlude null properties as empty.
if (obj[prop] !== null) {
return false;
}
}
return true;
};
/**
* Add a CSS class name to an element
* @param {Element} element Element to add class name to
* @param {String} classToAdd Classname to add
* @private
*/
vjs.addClass = function(element, classToAdd){
if ((' '+element.className+' ').indexOf(' '+classToAdd+' ') == -1) {
element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd;
}
};
/**
* Remove a CSS class name from an element
* @param {Element} element Element to remove from class name
* @param {String} classToAdd Classname to remove
* @private
*/
vjs.removeClass = function(element, classToRemove){
var classNames, i;
if (element.className.indexOf(classToRemove) == -1) { return; }
classNames = element.className.split(' ');
// no arr.indexOf in ie8, and we don't want to add a big shim
for (i = classNames.length - 1; i >= 0; i--) {
if (classNames[i] === classToRemove) {
classNames.splice(i,1);
}
}
element.className = classNames.join(' ');
};
/**
* Element for testing browser HTML5 video capabilities
* @type {Element}
* @constant
* @private
*/
vjs.TEST_VID = vjs.createEl('video');
/**
* Useragent for browser testing.
* @type {String}
* @constant
* @private
*/
vjs.USER_AGENT = navigator.userAgent;
/**
* Device is an iPhone
* @type {Boolean}
* @constant
* @private
*/
vjs.IS_IPHONE = (/iPhone/i).test(vjs.USER_AGENT);
vjs.IS_IPAD = (/iPad/i).test(vjs.USER_AGENT);
vjs.IS_IPOD = (/iPod/i).test(vjs.USER_AGENT);
vjs.IS_IOS = vjs.IS_IPHONE || vjs.IS_IPAD || vjs.IS_IPOD;
vjs.IOS_VERSION = (function(){
var match = vjs.USER_AGENT.match(/OS (\d+)_/i);
if (match && match[1]) { return match[1]; }
})();
vjs.IS_ANDROID = (/Android/i).test(vjs.USER_AGENT);
vjs.ANDROID_VERSION = (function() {
// This matches Android Major.Minor.Patch versions
// ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
var match = vjs.USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i),
major,
minor;
if (!match) {
return null;
}
major = match[1] && parseFloat(match[1]);
minor = match[2] && parseFloat(match[2]);
if (major && minor) {
return parseFloat(match[1] + '.' + match[2]);
} else if (major) {
return major;
} else {
return null;
}
})();
// Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser
vjs.IS_OLD_ANDROID = vjs.IS_ANDROID && (/webkit/i).test(vjs.USER_AGENT) && vjs.ANDROID_VERSION < 2.3;
vjs.IS_FIREFOX = (/Firefox/i).test(vjs.USER_AGENT);
vjs.IS_CHROME = (/Chrome/i).test(vjs.USER_AGENT);
vjs.TOUCH_ENABLED = !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch);
/**
* Apply attributes to an HTML element.
* @param {Element} el Target element.
* @param {Object=} attributes Element attributes to be applied.
* @private
*/
vjs.setElementAttributes = function(el, attributes){
vjs.obj.each(attributes, function(attrName, attrValue) {
if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
el.removeAttribute(attrName);
} else {
el.setAttribute(attrName, (attrValue === true ? '' : attrValue));
}
});
};
/**
* Get an element's attribute values, as defined on the HTML tag
* Attributs are not the same as properties. They're defined on the tag
* or with setAttribute (which shouldn't be used with HTML)
* This will return true or false for boolean attributes.
* @param {Element} tag Element from which to get tag attributes
* @return {Object}
* @private
*/
vjs.getElementAttributes = function(tag){
var obj, knownBooleans, attrs, attrName, attrVal;
obj = {};
// known boolean attributes
// we can check for matching boolean properties, but older browsers
// won't know about HTML5 boolean attributes that we still read from
knownBooleans = ','+'autoplay,controls,loop,muted,default'+',';
if (tag && tag.attributes && tag.attributes.length > 0) {
attrs = tag.attributes;
for (var i = attrs.length - 1; i >= 0; i--) {
attrName = attrs[i].name;
attrVal = attrs[i].value;
// check for known booleans
// the matching element property will return a value for typeof
if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(','+attrName+',') !== -1) {
// the value of an included boolean attribute is typically an empty
// string ('') which would equal false if we just check for a false value.
// we also don't want support bad code like autoplay='false'
attrVal = (attrVal !== null) ? true : false;
}
obj[attrName] = attrVal;
}
}
return obj;
};
/**
* Get the computed style value for an element
* From http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/
* @param {Element} el Element to get style value for
* @param {String} strCssRule Style name
* @return {String} Style value
* @private
*/
vjs.getComputedDimension = function(el, strCssRule){
var strValue = '';
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(el, '').getPropertyValue(strCssRule);
} else if(el.currentStyle){
// IE8 Width/Height support
strValue = el['client'+strCssRule.substr(0,1).toUpperCase() + strCssRule.substr(1)] + 'px';
}
return strValue;
};
/**
* Insert an element as the first child node of another
* @param {Element} child Element to insert
* @param {[type]} parent Element to insert child into
* @private
*/
vjs.insertFirst = function(child, parent){
if (parent.firstChild) {
parent.insertBefore(child, parent.firstChild);
} else {
parent.appendChild(child);
}
};
/**
* Object to hold browser support information
* @type {Object}
* @private
*/
vjs.browser = {};
/**
* Shorthand for document.getElementById()
* Also allows for CSS (jQuery) ID syntax. But nothing other than IDs.
* @param {String} id Element ID
* @return {Element} Element with supplied ID
* @private
*/
vjs.el = function(id){
if (id.indexOf('#') === 0) {
id = id.slice(1);
}
return document.getElementById(id);
};
/**
* Format seconds as a time string, H:MM:SS or M:SS
* Supplying a guide (in seconds) will force a number of leading zeros
* to cover the length of the guide
* @param {Number} seconds Number of seconds to be turned into a string
* @param {Number} guide Number (in seconds) to model the string after
* @return {String} Time formatted as H:MM:SS or M:SS
* @private
*/
vjs.formatTime = function(seconds, guide) {
// Default to using seconds as guide
guide = guide || seconds;
var s = Math.floor(seconds % 60),
m = Math.floor(seconds / 60 % 60),
h = Math.floor(seconds / 3600),
gm = Math.floor(guide / 60 % 60),
gh = Math.floor(guide / 3600);
// handle invalid times
if (isNaN(seconds) || seconds === Infinity) {
// '-' is false for all relational operators (e.g. <, >=) so this setting
// will add the minimum number of fields specified by the guide
h = m = s = '-';
}
// Check if we need to show hours
h = (h > 0 || gh > 0) ? h + ':' : '';
// If hours are showing, we may need to add a leading zero.
// Always show at least one digit of minutes.
m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':';
// Check if leading zero is need for seconds
s = (s < 10) ? '0' + s : s;
return h + m + s;
};
// Attempt to block the ability to select text while dragging controls
vjs.blockTextSelection = function(){
document.body.focus();
document.onselectstart = function () { return false; };
};
// Turn off text selection blocking
vjs.unblockTextSelection = function(){ document.onselectstart = function () { return true; }; };
/**
* Trim whitespace from the ends of a string.
* @param {String} string String to trim
* @return {String} Trimmed string
* @private
*/
vjs.trim = function(str){
return (str+'').replace(/^\s+|\s+$/g, '');
};
/**
* Should round off a number to a decimal place
* @param {Number} num Number to round
* @param {Number} dec Number of decimal places to round to
* @return {Number} Rounded number
* @private
*/
vjs.round = function(num, dec) {
if (!dec) { dec = 0; }
return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
};
/**
* Should create a fake TimeRange object
* Mimics an HTML5 time range instance, which has functions that
* return the start and end times for a range
* TimeRanges are returned by the buffered() method
* @param {Number} start Start time in seconds
* @param {Number} end End time in seconds
* @return {Object} Fake TimeRange object
* @private
*/
vjs.createTimeRange = function(start, end){
return {
length: 1,
start: function() { return start; },
end: function() { return end; }
};
};
/**
* Simple http request for retrieving external files (e.g. text tracks)
* @param {String} url URL of resource
* @param {Function} onSuccess Success callback
* @param {Function=} onError Error callback
* @param {Boolean=} withCredentials Flag which allow credentials
* @private
*/
vjs.get = function(url, onSuccess, onError, withCredentials){
var fileUrl, request, urlInfo, winLoc, crossOrigin;
onError = onError || function(){};
if (typeof XMLHttpRequest === 'undefined') {
// Shim XMLHttpRequest for older IEs
window.XMLHttpRequest = function () {
try { return new window.ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {}
try { return new window.ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {}
try { return new window.ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {}
throw new Error('This browser does not support XMLHttpRequest.');
};
}
request = new XMLHttpRequest();
urlInfo = vjs.parseUrl(url);
winLoc = window.location;
// check if url is for another domain/origin
// ie8 doesn't know location.origin, so we won't rely on it here
crossOrigin = (urlInfo.protocol + urlInfo.host) !== (winLoc.protocol + winLoc.host);
// Use XDomainRequest for IE if XMLHTTPRequest2 isn't available
// 'withCredentials' is only available in XMLHTTPRequest2
// Also XDomainRequest has a lot of gotchas, so only use if cross domain
if(crossOrigin && window.XDomainRequest && !('withCredentials' in request)) {
request = new window.XDomainRequest();
request.onload = function() {
onSuccess(request.responseText);
};
request.onerror = onError;
// these blank handlers need to be set to fix ie9 http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/
request.onprogress = function() {};
request.ontimeout = onError;
// XMLHTTPRequest
} else {
fileUrl = (urlInfo.protocol == 'file:' || winLoc.protocol == 'file:');
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200 || fileUrl && request.status === 0) {
onSuccess(request.responseText);
} else {
onError(request.responseText);
}
}
};
}
// open the connection
try {
// Third arg is async, or ignored by XDomainRequest
request.open('GET', url, true);
// withCredentials only supported by XMLHttpRequest2
if(withCredentials) {
request.withCredentials = true;
}
} catch(e) {
onError(e);
return;
}
// send the request
try {
request.send();
} catch(e) {
onError(e);
}
};
/**
* Add to local storage (may removeable)
* @private
*/
vjs.setLocalStorage = function(key, value){
try {
// IE was throwing errors referencing the var anywhere without this
var localStorage = window.localStorage || false;
if (!localStorage) { return; }
localStorage[key] = value;
} catch(e) {
if (e.code == 22 || e.code == 1014) { // Webkit == 22 / Firefox == 1014
vjs.log('LocalStorage Full (VideoJS)', e);
} else {
if (e.code == 18) {
vjs.log('LocalStorage not allowed (VideoJS)', e);
} else {
vjs.log('LocalStorage Error (VideoJS)', e);
}
}
}
};
/**
* Get abosolute version of relative URL. Used to tell flash correct URL.
* http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
* @param {String} url URL to make absolute
* @return {String} Absolute URL
* @private
*/
vjs.getAbsoluteURL = function(url){
// Check if absolute URL
if (!url.match(/^https?:\/\//)) {
// Convert to absolute URL. Flash hosted off-site needs an absolute URL.
url = vjs.createEl('div', {
innerHTML: '<a href="'+url+'">x</a>'
}).firstChild.href;
}
return url;
};
/**
* Resolve and parse the elements of a URL
* @param {String} url The url to parse
* @return {Object} An object of url details
*/
vjs.parseUrl = function(url) {
var div, a, addToBody, props, details;
props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
// add the url to an anchor and let the browser parse the URL
a = vjs.createEl('a', { href: url });
// IE8 (and 9?) Fix
// ie8 doesn't parse the URL correctly until the anchor is actually
// added to the body, and an innerHTML is needed to trigger the parsing
addToBody = (a.host === '' && a.protocol !== 'file:');
if (addToBody) {
div = vjs.createEl('div');
div.innerHTML = '<a href="'+url+'"></a>';
a = div.firstChild;
// prevent the div from affecting layout
div.setAttribute('style', 'display:none; position:absolute;');
document.body.appendChild(div);
}
// Copy the specific URL properties to a new object
// This is also needed for IE8 because the anchor loses its
// properties when it's removed from the dom
details = {};
for (var i = 0; i < props.length; i++) {
details[props[i]] = a[props[i]];
}
if (addToBody) {
document.body.removeChild(div);
}
return details;
};
/**
* Log messags to the console and history based on the type of message
*
* @param {String} type The type of message, or `null` for `log`
* @param {[type]} args The args to be passed to the log
* @private
*/
function _logType(type, args){
var argsArray, noop, console;
// convert args to an array to get array functions
argsArray = Array.prototype.slice.call(args);
// if there's no console then don't try to output messages
// they will still be stored in vjs.log.history
// Was setting these once outside of this function, but containing them
// in the function makes it easier to test cases where console doesn't exist
noop = function(){};
console = window['console'] || {
'log': noop,
'warn': noop,
'error': noop
};
if (type) {
// add the type to the front of the message
argsArray.unshift(type.toUpperCase()+':');
} else {
// default to log with no prefix
type = 'log';
}
// add to history
vjs.log.history.push(argsArray);
// add console prefix after adding to history
argsArray.unshift('VIDEOJS:');
// call appropriate log function
if (console[type].apply) {
console[type].apply(console, argsArray);
} else {
// ie8 doesn't allow error.apply, but it will just join() the array anyway
console[type](argsArray.join(' '));
}
}
/**
* Log plain debug messages
*/
vjs.log = function(){
_logType(null, arguments);
};
/**
* Keep a history of log messages
* @type {Array}
*/
vjs.log.history = [];
/**
* Log error messages
*/
vjs.log.error = function(){
_logType('error', arguments);
};
/**
* Log warning messages
*/
vjs.log.warn = function(){
_logType('warn', arguments);
};
// Offset Left
// getBoundingClientRect technique from John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/
vjs.findPosition = function(el) {
var box, docEl, body, clientLeft, scrollLeft, left, clientTop, scrollTop, top;
if (el.getBoundingClientRect && el.parentNode) {
box = el.getBoundingClientRect();
}
if (!box) {
return {
left: 0,
top: 0
};
}
docEl = document.documentElement;
body = document.body;
clientLeft = docEl.clientLeft || body.clientLeft || 0;
scrollLeft = window.pageXOffset || body.scrollLeft;
left = box.left + scrollLeft - clientLeft;
clientTop = docEl.clientTop || body.clientTop || 0;
scrollTop = window.pageYOffset || body.scrollTop;
top = box.top + scrollTop - clientTop;
// Android sometimes returns slightly off decimal values, so need to round
return {
left: vjs.round(left),
top: vjs.round(top)
};
};
/**
* Array functions container
* @type {Object}
* @private
*/
vjs.arr = {};
/*
* Loops through an array and runs a function for each item inside it.
* @param {Array} array The array
* @param {Function} callback The function to be run for each item
* @param {*} thisArg The `this` binding of callback
* @returns {Array} The array
* @private
*/
vjs.arr.forEach = function(array, callback, thisArg) {
if (vjs.obj.isArray(array) && callback instanceof Function) {
for (var i = 0, len = array.length; i < len; ++i) {
callback.call(thisArg || vjs, array[i], i, array);
}
}
return array;
};
/**
* Utility functions namespace
* @namespace
* @type {Object}
*/
vjs.util = {};
/**
* Merge two options objects, recursively merging any plain object properties as
* well. Previously `deepMerge`
*
* @param {Object} obj1 Object to override values in
* @param {Object} obj2 Overriding object
* @return {Object} New object -- obj1 and obj2 will be untouched
*/
vjs.util.mergeOptions = function(obj1, obj2){
var key, val1, val2;
// make a copy of obj1 so we're not overwriting original values.
// like prototype.options_ and all sub options objects
obj1 = vjs.obj.copy(obj1);
for (key in obj2){
if (obj2.hasOwnProperty(key)) {
val1 = obj1[key];
val2 = obj2[key];
// Check if both properties are pure objects and do a deep merge if so
if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) {
obj1[key] = vjs.util.mergeOptions(val1, val2);
} else {
obj1[key] = obj2[key];
}
}
}
return obj1;
};/**
* @fileoverview Player Component - Base class for all UI objects
*
*/
/**
* Base UI Component class
*
* Components are embeddable UI objects that are represented by both a
* javascript object and an element in the DOM. They can be children of other
* components, and can have many children themselves.
*
* // adding a button to the player
* var button = player.addChild('button');
* button.el(); // -> button element
*
* <div class="video-js">
* <div class="vjs-button">Button</div>
* </div>
*
* Components are also event emitters.
*
* button.on('click', function(){
* console.log('Button Clicked!');
* });
*
* button.trigger('customevent');
*
* @param {Object} player Main Player
* @param {Object=} options
* @class
* @constructor
* @extends vjs.CoreObject
*/
vjs.Component = vjs.CoreObject.extend({
/**
* the constructor function for the class
*
* @constructor
*/
init: function(player, options, ready){
this.player_ = player;
// Make a copy of prototype.options_ to protect against overriding global defaults
this.options_ = vjs.obj.copy(this.options_);
// Updated options with supplied options
options = this.options(options);
// Get ID from options, element, or create using player ID and unique ID
this.id_ = options['id'] || ((options['el'] && options['el']['id']) ? options['el']['id'] : player.id() + '_component_' + vjs.guid++ );
this.name_ = options['name'] || null;
// Create element if one wasn't provided in options
this.el_ = options['el'] || this.createEl();
this.children_ = [];
this.childIndex_ = {};
this.childNameIndex_ = {};
// Add any child components in options
this.initChildren();
this.ready(ready);
// Don't want to trigger ready here or it will before init is actually
// finished for all children that run this constructor
if (options.reportTouchActivity !== false) {
this.enableTouchActivity();
}
}
});
/**
* Dispose of the component and all child components
*/
vjs.Component.prototype.dispose = function(){
this.trigger({ type: 'dispose', 'bubbles': false });
// Dispose all children.
if (this.children_) {
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i].dispose) {
this.children_[i].dispose();
}
}
}
// Delete child references
this.children_ = null;
this.childIndex_ = null;
this.childNameIndex_ = null;
// Remove all event listeners.
this.off();
// Remove element from DOM
if (this.el_.parentNode) {
this.el_.parentNode.removeChild(this.el_);
}
vjs.removeData(this.el_);
this.el_ = null;
};
/**
* Reference to main player instance
*
* @type {vjs.Player}
* @private
*/
vjs.Component.prototype.player_ = true;
/**
* Return the component's player
*
* @return {vjs.Player}
*/
vjs.Component.prototype.player = function(){
return this.player_;
};
/**
* The component's options object
*
* @type {Object}
* @private
*/
vjs.Component.prototype.options_;
/**
* Deep merge of options objects
*
* Whenever a property is an object on both options objects
* the two properties will be merged using vjs.obj.deepMerge.
*
* This is used for merging options for child components. We
* want it to be easy to override individual options on a child
* component without having to rewrite all the other default options.
*
* Parent.prototype.options_ = {
* children: {
* 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' },
* 'childTwo': {},
* 'childThree': {}
* }
* }
* newOptions = {
* children: {
* 'childOne': { 'foo': 'baz', 'abc': '123' }
* 'childTwo': null,
* 'childFour': {}
* }
* }
*
* this.options(newOptions);
*
* RESULT
*
* {
* children: {
* 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' },
* 'childTwo': null, // Disabled. Won't be initialized.
* 'childThree': {},
* 'childFour': {}
* }
* }
*
* @param {Object} obj Object of new option values
* @return {Object} A NEW object of this.options_ and obj merged
*/
vjs.Component.prototype.options = function(obj){
if (obj === undefined) return this.options_;
return this.options_ = vjs.util.mergeOptions(this.options_, obj);
};
/**
* The DOM element for the component
*
* @type {Element}
* @private
*/
vjs.Component.prototype.el_;
/**
* Create the component's DOM element
*
* @param {String=} tagName Element's node type. e.g. 'div'
* @param {Object=} attributes An object of element attributes that should be set on the element
* @return {Element}
*/
vjs.Component.prototype.createEl = function(tagName, attributes){
return vjs.createEl(tagName, attributes);
};
vjs.Component.prototype.localize = function(string){
var lang = this.player_.language(),
languages = this.player_.languages();
if (languages && languages[lang] && languages[lang][string]) {
return languages[lang][string];
}
return string;
};
/**
* Get the component's DOM element
*
* var domEl = myComponent.el();
*
* @return {Element}
*/
vjs.Component.prototype.el = function(){
return this.el_;
};
/**
* An optional element where, if defined, children will be inserted instead of
* directly in `el_`
*
* @type {Element}
* @private
*/
vjs.Component.prototype.contentEl_;
/**
* Return the component's DOM element for embedding content.
* Will either be el_ or a new element defined in createEl.
*
* @return {Element}
*/
vjs.Component.prototype.contentEl = function(){
return this.contentEl_ || this.el_;
};
/**
* The ID for the component
*
* @type {String}
* @private
*/
vjs.Component.prototype.id_;
/**
* Get the component's ID
*
* var id = myComponent.id();
*
* @return {String}
*/
vjs.Component.prototype.id = function(){
return this.id_;
};
/**
* The name for the component. Often used to reference the component.
*
* @type {String}
* @private
*/
vjs.Component.prototype.name_;
/**
* Get the component's name. The name is often used to reference the component.
*
* var name = myComponent.name();
*
* @return {String}
*/
vjs.Component.prototype.name = function(){
return this.name_;
};
/**
* Array of child components
*
* @type {Array}
* @private
*/
vjs.Component.prototype.children_;
/**
* Get an array of all child components
*
* var kids = myComponent.children();
*
* @return {Array} The children
*/
vjs.Component.prototype.children = function(){
return this.children_;
};
/**
* Object of child components by ID
*
* @type {Object}
* @private
*/
vjs.Component.prototype.childIndex_;
/**
* Returns a child component with the provided ID
*
* @return {vjs.Component}
*/
vjs.Component.prototype.getChildById = function(id){
return this.childIndex_[id];
};
/**
* Object of child components by name
*
* @type {Object}
* @private
*/
vjs.Component.prototype.childNameIndex_;
/**
* Returns a child component with the provided name
*
* @return {vjs.Component}
*/
vjs.Component.prototype.getChild = function(name){
return this.childNameIndex_[name];
};
/**
* Adds a child component inside this component
*
* myComponent.el();
* // -> <div class='my-component'></div>
* myComonent.children();
* // [empty array]
*
* var myButton = myComponent.addChild('MyButton');
* // -> <div class='my-component'><div class="my-button">myButton<div></div>
* // -> myButton === myComonent.children()[0];
*
* Pass in options for child constructors and options for children of the child
*
* var myButton = myComponent.addChild('MyButton', {
* text: 'Press Me',
* children: {
* buttonChildExample: {
* buttonChildOption: true
* }
* }
* });
*
* @param {String|vjs.Component} child The class name or instance of a child to add
* @param {Object=} options Options, including options to be passed to children of the child.
* @return {vjs.Component} The child component (created by this process if a string was used)
* @suppress {accessControls|checkRegExp|checkTypes|checkVars|const|constantProperty|deprecated|duplicate|es5Strict|fileoverviewTags|globalThis|invalidCasts|missingProperties|nonStandardJsDocs|strictModuleDepCheck|undefinedNames|undefinedVars|unknownDefines|uselessCode|visibility}
*/
vjs.Component.prototype.addChild = function(child, options){
var component, componentClass, componentName, componentId;
// If string, create new component with options
if (typeof child === 'string') {
componentName = child;
// Make sure options is at least an empty object to protect against errors
options = options || {};
// Assume name of set is a lowercased name of the UI Class (PlayButton, etc.)
componentClass = options['componentClass'] || vjs.capitalize(componentName);
// Set name through options
options['name'] = componentName;
// Create a new object & element for this controls set
// If there's no .player_, this is a player
// Closure Compiler throws an 'incomplete alias' warning if we use the vjs variable directly.
// Every class should be exported, so this should never be a problem here.
component = new window['videojs'][componentClass](this.player_ || this, options);
// child is a component instance
} else {
component = child;
}
this.children_.push(component);
if (typeof component.id === 'function') {
this.childIndex_[component.id()] = component;
}
// If a name wasn't used to create the component, check if we can use the
// name function of the component
componentName = componentName || (component.name && component.name());
if (componentName) {
this.childNameIndex_[componentName] = component;
}
// Add the UI object's element to the container div (box)
// Having an element is not required
if (typeof component['el'] === 'function' && component['el']()) {
this.contentEl().appendChild(component['el']());
}
// Return so it can stored on parent object if desired.
return component;
};
/**
* Remove a child component from this component's list of children, and the
* child component's element from this component's element
*
* @param {vjs.Component} component Component to remove
*/
vjs.Component.prototype.removeChild = function(component){
if (typeof component === 'string') {
component = this.getChild(component);
}
if (!component || !this.children_) return;
var childFound = false;
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i] === component) {
childFound = true;
this.children_.splice(i,1);
break;
}
}
if (!childFound) return;
this.childIndex_[component.id] = null;
this.childNameIndex_[component.name] = null;
var compEl = component.el();
if (compEl && compEl.parentNode === this.contentEl()) {
this.contentEl().removeChild(component.el());
}
};
/**
* Add and initialize default child components from options
*
* // when an instance of MyComponent is created, all children in options
* // will be added to the instance by their name strings and options
* MyComponent.prototype.options_.children = {
* myChildComponent: {
* myChildOption: true
* }
* }
*
* // Or when creating the component
* var myComp = new MyComponent(player, {
* children: {
* myChildComponent: {
* myChildOption: true
* }
* }
* });
*
* The children option can also be an Array of child names or
* child options objects (that also include a 'name' key).
*
* var myComp = new MyComponent(player, {
* children: [
* 'button',
* {
* name: 'button',
* someOtherOption: true
* }
* ]
* });
*
*/
vjs.Component.prototype.initChildren = function(){
var parent, children, child, name, opts;
parent = this;
children = this.options()['children'];
if (children) {
// Allow for an array of children details to passed in the options
if (vjs.obj.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
if (typeof child == 'string') {
name = child;
opts = {};
} else {
name = child.name;
opts = child;
}
parent[name] = parent.addChild(name, opts);
}
} else {
vjs.obj.each(children, function(name, opts){
// Allow for disabling default components
// e.g. vjs.options['children']['posterImage'] = false
if (opts === false) return;
// Set property name on player. Could cause conflicts with other prop names, but it's worth making refs easy.
parent[name] = parent.addChild(name, opts);
});
}
}
};
/**
* Allows sub components to stack CSS class names
*
* @return {String} The constructed class name
*/
vjs.Component.prototype.buildCSSClass = function(){
// Child classes can include a function that does:
// return 'CLASS NAME' + this._super();
return '';
};
/* Events
============================================================================= */
/**
* Add an event listener to this component's element
*
* var myFunc = function(){
* var myPlayer = this;
* // Do something when the event is fired
* };
*
* myPlayer.on("eventName", myFunc);
*
* The context will be the component.
*
* @param {String} type The event type e.g. 'click'
* @param {Function} fn The event listener
* @return {vjs.Component} self
*/
vjs.Component.prototype.on = function(type, fn){
vjs.on(this.el_, type, vjs.bind(this, fn));
return this;
};
/**
* Remove an event listener from the component's element
*
* myComponent.off("eventName", myFunc);
*
* @param {String=} type Event type. Without type it will remove all listeners.
* @param {Function=} fn Event listener. Without fn it will remove all listeners for a type.
* @return {vjs.Component}
*/
vjs.Component.prototype.off = function(type, fn){
vjs.off(this.el_, type, fn);
return this;
};
/**
* Add an event listener to be triggered only once and then removed
*
* @param {String} type Event type
* @param {Function} fn Event listener
* @return {vjs.Component}
*/
vjs.Component.prototype.one = function(type, fn) {
vjs.one(this.el_, type, vjs.bind(this, fn));
return this;
};
/**
* Trigger an event on an element
*
* myComponent.trigger('eventName');
* myComponent.trigger({'type':'eventName'});
*
* @param {Event|Object|String} event A string (the type) or an event object with a type attribute
* @return {vjs.Component} self
*/
vjs.Component.prototype.trigger = function(event){
vjs.trigger(this.el_, event);
return this;
};
/* Ready
================================================================================ */
/**
* Is the component loaded
* This can mean different things depending on the component.
*
* @private
* @type {Boolean}
*/
vjs.Component.prototype.isReady_;
/**
* Trigger ready as soon as initialization is finished
*
* Allows for delaying ready. Override on a sub class prototype.
* If you set this.isReadyOnInitFinish_ it will affect all components.
* Specially used when waiting for the Flash player to asynchrnously load.
*
* @type {Boolean}
* @private
*/
vjs.Component.prototype.isReadyOnInitFinish_ = true;
/**
* List of ready listeners
*
* @type {Array}
* @private
*/
vjs.Component.prototype.readyQueue_;
/**
* Bind a listener to the component's ready state
*
* Different from event listeners in that if the ready event has already happend
* it will trigger the function immediately.
*
* @param {Function} fn Ready listener
* @return {vjs.Component}
*/
vjs.Component.prototype.ready = function(fn){
if (fn) {
if (this.isReady_) {
fn.call(this);
} else {
if (this.readyQueue_ === undefined) {
this.readyQueue_ = [];
}
this.readyQueue_.push(fn);
}
}
return this;
};
/**
* Trigger the ready listeners
*
* @return {vjs.Component}
*/
vjs.Component.prototype.triggerReady = function(){
this.isReady_ = true;
var readyQueue = this.readyQueue_;
if (readyQueue && readyQueue.length > 0) {
for (var i = 0, j = readyQueue.length; i < j; i++) {
readyQueue[i].call(this);
}
// Reset Ready Queue
this.readyQueue_ = [];
// Allow for using event listeners also, in case you want to do something everytime a source is ready.
this.trigger('ready');
}
};
/* Display
============================================================================= */
/**
* Add a CSS class name to the component's element
*
* @param {String} classToAdd Classname to add
* @return {vjs.Component}
*/
vjs.Component.prototype.addClass = function(classToAdd){
vjs.addClass(this.el_, classToAdd);
return this;
};
/**
* Remove a CSS class name from the component's element
*
* @param {String} classToRemove Classname to remove
* @return {vjs.Component}
*/
vjs.Component.prototype.removeClass = function(classToRemove){
vjs.removeClass(this.el_, classToRemove);
return this;
};
/**
* Show the component element if hidden
*
* @return {vjs.Component}
*/
vjs.Component.prototype.show = function(){
this.el_.style.display = 'block';
return this;
};
/**
* Hide the component element if currently showing
*
* @return {vjs.Component}
*/
vjs.Component.prototype.hide = function(){
this.el_.style.display = 'none';
return this;
};
/**
* Lock an item in its visible state
* To be used with fadeIn/fadeOut.
*
* @return {vjs.Component}
* @private
*/
vjs.Component.prototype.lockShowing = function(){
this.addClass('vjs-lock-showing');
return this;
};
/**
* Unlock an item to be hidden
* To be used with fadeIn/fadeOut.
*
* @return {vjs.Component}
* @private
*/
vjs.Component.prototype.unlockShowing = function(){
this.removeClass('vjs-lock-showing');
return this;
};
/**
* Disable component by making it unshowable
*
* Currently private because we're movign towards more css-based states.
* @private
*/
vjs.Component.prototype.disable = function(){
this.hide();
this.show = function(){};
};
/**
* Set or get the width of the component (CSS values)
*
* Setting the video tag dimension values only works with values in pixels.
* Percent values will not work.
* Some percents can be used, but width()/height() will return the number + %,
* not the actual computed width/height.
*
* @param {Number|String=} num Optional width number
* @param {Boolean} skipListeners Skip the 'resize' event trigger
* @return {vjs.Component} This component, when setting the width
* @return {Number|String} The width, when getting
*/
vjs.Component.prototype.width = function(num, skipListeners){
return this.dimension('width', num, skipListeners);
};
/**
* Get or set the height of the component (CSS values)
*
* Setting the video tag dimension values only works with values in pixels.
* Percent values will not work.
* Some percents can be used, but width()/height() will return the number + %,
* not the actual computed width/height.
*
* @param {Number|String=} num New component height
* @param {Boolean=} skipListeners Skip the resize event trigger
* @return {vjs.Component} This component, when setting the height
* @return {Number|String} The height, when getting
*/
vjs.Component.prototype.height = function(num, skipListeners){
return this.dimension('height', num, skipListeners);
};
/**
* Set both width and height at the same time
*
* @param {Number|String} width
* @param {Number|String} height
* @return {vjs.Component} The component
*/
vjs.Component.prototype.dimensions = function(width, height){
// Skip resize listeners on width for optimization
return this.width(width, true).height(height);
};
/**
* Get or set width or height
*
* This is the shared code for the width() and height() methods.
* All for an integer, integer + 'px' or integer + '%';
*
* Known issue: Hidden elements officially have a width of 0. We're defaulting
* to the style.width value and falling back to computedStyle which has the
* hidden element issue. Info, but probably not an efficient fix:
* http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/
*
* @param {String} widthOrHeight 'width' or 'height'
* @param {Number|String=} num New dimension
* @param {Boolean=} skipListeners Skip resize event trigger
* @return {vjs.Component} The component if a dimension was set
* @return {Number|String} The dimension if nothing was set
* @private
*/
vjs.Component.prototype.dimension = function(widthOrHeight, num, skipListeners){
if (num !== undefined) {
if (num === null || vjs.isNaN(num)) {
num = 0;
}
// Check if using css width/height (% or px) and adjust
if ((''+num).indexOf('%') !== -1 || (''+num).indexOf('px') !== -1) {
this.el_.style[widthOrHeight] = num;
} else if (num === 'auto') {
this.el_.style[widthOrHeight] = '';
} else {
this.el_.style[widthOrHeight] = num+'px';
}
// skipListeners allows us to avoid triggering the resize event when setting both width and height
if (!skipListeners) { this.trigger('resize'); }
// Return component
return this;
}
// Not setting a value, so getting it
// Make sure element exists
if (!this.el_) return 0;
// Get dimension value from style
var val = this.el_.style[widthOrHeight];
var pxIndex = val.indexOf('px');
if (pxIndex !== -1) {
// Return the pixel value with no 'px'
return parseInt(val.slice(0,pxIndex), 10);
// No px so using % or no style was set, so falling back to offsetWidth/height
// If component has display:none, offset will return 0
// TODO: handle display:none and no dimension style using px
} else {
return parseInt(this.el_['offset'+vjs.capitalize(widthOrHeight)], 10);
// ComputedStyle version.
// Only difference is if the element is hidden it will return
// the percent value (e.g. '100%'')
// instead of zero like offsetWidth returns.
// var val = vjs.getComputedStyleValue(this.el_, widthOrHeight);
// var pxIndex = val.indexOf('px');
// if (pxIndex !== -1) {
// return val.slice(0, pxIndex);
// } else {
// return val;
// }
}
};
/**
* Fired when the width and/or height of the component changes
* @event resize
*/
vjs.Component.prototype.onResize;
/**
* Emit 'tap' events when touch events are supported
*
* This is used to support toggling the controls through a tap on the video.
*
* We're requireing them to be enabled because otherwise every component would
* have this extra overhead unnecessarily, on mobile devices where extra
* overhead is especially bad.
* @private
*/
vjs.Component.prototype.emitTapEvents = function(){
var touchStart, firstTouch, touchTime, couldBeTap, noTap,
xdiff, ydiff, touchDistance, tapMovementThreshold;
// Track the start time so we can determine how long the touch lasted
touchStart = 0;
firstTouch = null;
// Maximum movement allowed during a touch event to still be considered a tap
tapMovementThreshold = 22;
this.on('touchstart', function(event) {
// If more than one finger, don't consider treating this as a click
if (event.touches.length === 1) {
firstTouch = event.touches[0];
// Record start time so we can detect a tap vs. "touch and hold"
touchStart = new Date().getTime();
// Reset couldBeTap tracking
couldBeTap = true;
}
});
this.on('touchmove', function(event) {
// If more than one finger, don't consider treating this as a click
if (event.touches.length > 1) {
couldBeTap = false;
} else if (firstTouch) {
// Some devices will throw touchmoves for all but the slightest of taps.
// So, if we moved only a small distance, this could still be a tap
xdiff = event.touches[0].pageX - firstTouch.pageX;
ydiff = event.touches[0].pageY - firstTouch.pageY;
touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
if (touchDistance > tapMovementThreshold) {
couldBeTap = false;
}
}
});
noTap = function(){
couldBeTap = false;
};
// TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
this.on('touchleave', noTap);
this.on('touchcancel', noTap);
// When the touch ends, measure how long it took and trigger the appropriate
// event
this.on('touchend', function(event) {
firstTouch = null;
// Proceed only if the touchmove/leave/cancel event didn't happen
if (couldBeTap === true) {
// Measure how long the touch lasted
touchTime = new Date().getTime() - touchStart;
// The touch needs to be quick in order to consider it a tap
if (touchTime < 250) {
event.preventDefault(); // Don't let browser turn this into a click
this.trigger('tap');
// It may be good to copy the touchend event object and change the
// type to tap, if the other event properties aren't exact after
// vjs.fixEvent runs (e.g. event.target)
}
}
});
};
/**
* Report user touch activity when touch events occur
*
* User activity is used to determine when controls should show/hide. It's
* relatively simple when it comes to mouse events, because any mouse event
* should show the controls. So we capture mouse events that bubble up to the
* player and report activity when that happens.
*
* With touch events it isn't as easy. We can't rely on touch events at the
* player level, because a tap (touchstart + touchend) on the video itself on
* mobile devices is meant to turn controls off (and on). User activity is
* checked asynchronously, so what could happen is a tap event on the video
* turns the controls off, then the touchend event bubbles up to the player,
* which if it reported user activity, would turn the controls right back on.
* (We also don't want to completely block touch events from bubbling up)
*
* Also a touchmove, touch+hold, and anything other than a tap is not supposed
* to turn the controls back on on a mobile device.
*
* Here we're setting the default component behavior to report user activity
* whenever touch events happen, and this can be turned off by components that
* want touch events to act differently.
*/
vjs.Component.prototype.enableTouchActivity = function() {
var report, touchHolding, touchEnd;
// listener for reporting that the user is active
report = vjs.bind(this.player(), this.player().reportUserActivity);
this.on('touchstart', function() {
report();
// For as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// So we want to continue to update that they are active
clearInterval(touchHolding);
// report at the same interval as activityCheck
touchHolding = setInterval(report, 250);
});
touchEnd = function(event) {
report();
// stop the interval that maintains activity if the touch is holding
clearInterval(touchHolding);
};
this.on('touchmove', report);
this.on('touchend', touchEnd);
this.on('touchcancel', touchEnd);
};
/* Button - Base class for all buttons
================================================================================ */
/**
* Base class for all buttons
* @param {vjs.Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
vjs.Button = vjs.Component.extend({
/**
* @constructor
* @inheritDoc
*/
init: function(player, options){
vjs.Component.call(this, player, options);
this.emitTapEvents();
this.on('tap', this.onClick);
this.on('click', this.onClick);
this.on('focus', this.onFocus);
this.on('blur', this.onBlur);
}
});
vjs.Button.prototype.createEl = function(type, props){
var el;
// Add standard Aria and Tabindex info
props = vjs.obj.merge({
className: this.buildCSSClass(),
'role': 'button',
'aria-live': 'polite', // let the screen reader user know that the text of the button may change
tabIndex: 0
}, props);
el = vjs.Component.prototype.createEl.call(this, type, props);
// if innerHTML hasn't been overridden (bigPlayButton), add content elements
if (!props.innerHTML) {
this.contentEl_ = vjs.createEl('div', {
className: 'vjs-control-content'
});
this.controlText_ = vjs.createEl('span', {
className: 'vjs-control-text',
innerHTML: this.localize(this.buttonText) || 'Need Text'
});
this.contentEl_.appendChild(this.controlText_);
el.appendChild(this.contentEl_);
}
return el;
};
vjs.Button.prototype.buildCSSClass = function(){
// TODO: Change vjs-control to vjs-button?
return 'vjs-control ' + vjs.Component.prototype.buildCSSClass.call(this);
};
// Click - Override with specific functionality for button
vjs.Button.prototype.onClick = function(){};
// Focus - Add keyboard functionality to element
vjs.Button.prototype.onFocus = function(){
vjs.on(document, 'keydown', vjs.bind(this, this.onKeyPress));
};
// KeyPress (document level) - Trigger click when keys are pressed
vjs.Button.prototype.onKeyPress = function(event){
// Check for space bar (32) or enter (13) keys
if (event.which == 32 || event.which == 13) {
event.preventDefault();
this.onClick();
}
};
// Blur - Remove keyboard triggers
vjs.Button.prototype.onBlur = function(){
vjs.off(document, 'keydown', vjs.bind(this, this.onKeyPress));
};
/* Slider
================================================================================ */
/**
* The base functionality for sliders like the volume bar and seek bar
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.Slider = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
// Set property names to bar and handle to match with the child Slider class is looking for
this.bar = this.getChild(this.options_['barName']);
this.handle = this.getChild(this.options_['handleName']);
this.on('mousedown', this.onMouseDown);
this.on('touchstart', this.onMouseDown);
this.on('focus', this.onFocus);
this.on('blur', this.onBlur);
this.on('click', this.onClick);
this.player_.on('controlsvisible', vjs.bind(this, this.update));
player.on(this.playerEvent, vjs.bind(this, this.update));
this.boundEvents = {};
this.boundEvents.move = vjs.bind(this, this.onMouseMove);
this.boundEvents.end = vjs.bind(this, this.onMouseUp);
}
});
vjs.Slider.prototype.createEl = function(type, props) {
props = props || {};
// Add the slider element class to all sub classes
props.className = props.className + ' vjs-slider';
props = vjs.obj.merge({
'role': 'slider',
'aria-valuenow': 0,
'aria-valuemin': 0,
'aria-valuemax': 100,
tabIndex: 0
}, props);
return vjs.Component.prototype.createEl.call(this, type, props);
};
vjs.Slider.prototype.onMouseDown = function(event){
event.preventDefault();
vjs.blockTextSelection();
this.addClass('vjs-sliding');
vjs.on(document, 'mousemove', this.boundEvents.move);
vjs.on(document, 'mouseup', this.boundEvents.end);
vjs.on(document, 'touchmove', this.boundEvents.move);
vjs.on(document, 'touchend', this.boundEvents.end);
this.onMouseMove(event);
};
// To be overridden by a subclass
vjs.Slider.prototype.onMouseMove = function(){};
vjs.Slider.prototype.onMouseUp = function() {
vjs.unblockTextSelection();
this.removeClass('vjs-sliding');
vjs.off(document, 'mousemove', this.boundEvents.move, false);
vjs.off(document, 'mouseup', this.boundEvents.end, false);
vjs.off(document, 'touchmove', this.boundEvents.move, false);
vjs.off(document, 'touchend', this.boundEvents.end, false);
this.update();
};
vjs.Slider.prototype.update = function(){
// In VolumeBar init we have a setTimeout for update that pops and update to the end of the
// execution stack. The player is destroyed before then update will cause an error
if (!this.el_) return;
// If scrubbing, we could use a cached value to make the handle keep up with the user's mouse.
// On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later.
// var progress = (this.player_.scrubbing) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration();
var barProgress,
progress = this.getPercent(),
handle = this.handle,
bar = this.bar;
// Protect against no duration and other division issues
if (isNaN(progress)) { progress = 0; }
barProgress = progress;
// If there is a handle, we need to account for the handle in our calculation for progress bar
// so that it doesn't fall short of or extend past the handle.
if (handle) {
var box = this.el_,
boxWidth = box.offsetWidth,
handleWidth = handle.el().offsetWidth,
// The width of the handle in percent of the containing box
// In IE, widths may not be ready yet causing NaN
handlePercent = (handleWidth) ? handleWidth / boxWidth : 0,
// Get the adjusted size of the box, considering that the handle's center never touches the left or right side.
// There is a margin of half the handle's width on both sides.
boxAdjustedPercent = 1 - handlePercent,
// Adjust the progress that we'll use to set widths to the new adjusted box width
adjustedProgress = progress * boxAdjustedPercent;
// The bar does reach the left side, so we need to account for this in the bar's width
barProgress = adjustedProgress + (handlePercent / 2);
// Move the handle from the left based on the adjected progress
handle.el().style.left = vjs.round(adjustedProgress * 100, 2) + '%';
}
// Set the new bar width
if (bar) {
bar.el().style.width = vjs.round(barProgress * 100, 2) + '%';
}
};
vjs.Slider.prototype.calculateDistance = function(event){
var el, box, boxX, boxY, boxW, boxH, handle, pageX, pageY;
el = this.el_;
box = vjs.findPosition(el);
boxW = boxH = el.offsetWidth;
handle = this.handle;
if (this.options()['vertical']) {
boxY = box.top;
if (event.changedTouches) {
pageY = event.changedTouches[0].pageY;
} else {
pageY = event.pageY;
}
if (handle) {
var handleH = handle.el().offsetHeight;
// Adjusted X and Width, so handle doesn't go outside the bar
boxY = boxY + (handleH / 2);
boxH = boxH - handleH;
}
// Percent that the click is through the adjusted area
return Math.max(0, Math.min(1, ((boxY - pageY) + boxH) / boxH));
} else {
boxX = box.left;
if (event.changedTouches) {
pageX = event.changedTouches[0].pageX;
} else {
pageX = event.pageX;
}
if (handle) {
var handleW = handle.el().offsetWidth;
// Adjusted X and Width, so handle doesn't go outside the bar
boxX = boxX + (handleW / 2);
boxW = boxW - handleW;
}
// Percent that the click is through the adjusted area
return Math.max(0, Math.min(1, (pageX - boxX) / boxW));
}
};
vjs.Slider.prototype.onFocus = function(){
vjs.on(document, 'keyup', vjs.bind(this, this.onKeyPress));
};
vjs.Slider.prototype.onKeyPress = function(event){
if (event.which == 37 || event.which == 40) { // Left and Down Arrows
event.preventDefault();
this.stepBack();
} else if (event.which == 38 || event.which == 39) { // Up and Right Arrows
event.preventDefault();
this.stepForward();
}
};
vjs.Slider.prototype.onBlur = function(){
vjs.off(document, 'keyup', vjs.bind(this, this.onKeyPress));
};
/**
* Listener for click events on slider, used to prevent clicks
* from bubbling up to parent elements like button menus.
* @param {Object} event Event object
*/
vjs.Slider.prototype.onClick = function(event){
event.stopImmediatePropagation();
event.preventDefault();
};
/**
* SeekBar Behavior includes play progress bar, and seek handle
* Needed so it can determine seek position based on handle position/size
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.SliderHandle = vjs.Component.extend();
/**
* Default value of the slider
*
* @type {Number}
* @private
*/
vjs.SliderHandle.prototype.defaultValue = 0;
/** @inheritDoc */
vjs.SliderHandle.prototype.createEl = function(type, props) {
props = props || {};
// Add the slider element class to all sub classes
props.className = props.className + ' vjs-slider-handle';
props = vjs.obj.merge({
innerHTML: '<span class="vjs-control-text">'+this.defaultValue+'</span>'
}, props);
return vjs.Component.prototype.createEl.call(this, 'div', props);
};
/* Menu
================================================================================ */
/**
* The Menu component is used to build pop up menus, including subtitle and
* captions selection menus.
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
vjs.Menu = vjs.Component.extend();
/**
* Add a menu item to the menu
* @param {Object|String} component Component or component type to add
*/
vjs.Menu.prototype.addItem = function(component){
this.addChild(component);
component.on('click', vjs.bind(this, function(){
this.unlockShowing();
}));
};
/** @inheritDoc */
vjs.Menu.prototype.createEl = function(){
var contentElType = this.options().contentElType || 'ul';
this.contentEl_ = vjs.createEl(contentElType, {
className: 'vjs-menu-content'
});
var el = vjs.Component.prototype.createEl.call(this, 'div', {
append: this.contentEl_,
className: 'vjs-menu'
});
el.appendChild(this.contentEl_);
// Prevent clicks from bubbling up. Needed for Menu Buttons,
// where a click on the parent is significant
vjs.on(el, 'click', function(event){
event.preventDefault();
event.stopImmediatePropagation();
});
return el;
};
/**
* The component for a menu item. `<li>`
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
vjs.MenuItem = vjs.Button.extend({
/** @constructor */
init: function(player, options){
vjs.Button.call(this, player, options);
this.selected(options['selected']);
}
});
/** @inheritDoc */
vjs.MenuItem.prototype.createEl = function(type, props){
return vjs.Button.prototype.createEl.call(this, 'li', vjs.obj.merge({
className: 'vjs-menu-item',
innerHTML: this.options_['label']
}, props));
};
/**
* Handle a click on the menu item, and set it to selected
*/
vjs.MenuItem.prototype.onClick = function(){
this.selected(true);
};
/**
* Set this menu item as selected or not
* @param {Boolean} selected
*/
vjs.MenuItem.prototype.selected = function(selected){
if (selected) {
this.addClass('vjs-selected');
this.el_.setAttribute('aria-selected',true);
} else {
this.removeClass('vjs-selected');
this.el_.setAttribute('aria-selected',false);
}
};
/**
* A button class with a popup menu
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.MenuButton = vjs.Button.extend({
/** @constructor */
init: function(player, options){
vjs.Button.call(this, player, options);
this.menu = this.createMenu();
// Add list to element
this.addChild(this.menu);
// Automatically hide empty menu buttons
if (this.items && this.items.length === 0) {
this.hide();
}
this.on('keyup', this.onKeyPress);
this.el_.setAttribute('aria-haspopup', true);
this.el_.setAttribute('role', 'button');
}
});
/**
* Track the state of the menu button
* @type {Boolean}
* @private
*/
vjs.MenuButton.prototype.buttonPressed_ = false;
vjs.MenuButton.prototype.createMenu = function(){
var menu = new vjs.Menu(this.player_);
// Add a title list item to the top
if (this.options().title) {
menu.contentEl().appendChild(vjs.createEl('li', {
className: 'vjs-menu-title',
innerHTML: vjs.capitalize(this.options().title),
tabindex: -1
}));
}
this.items = this['createItems']();
if (this.items) {
// Add menu items to the menu
for (var i = 0; i < this.items.length; i++) {
menu.addItem(this.items[i]);
}
}
return menu;
};
/**
* Create the list of menu items. Specific to each subclass.
*/
vjs.MenuButton.prototype.createItems = function(){};
/** @inheritDoc */
vjs.MenuButton.prototype.buildCSSClass = function(){
return this.className + ' vjs-menu-button ' + vjs.Button.prototype.buildCSSClass.call(this);
};
// Focus - Add keyboard functionality to element
// This function is not needed anymore. Instead, the keyboard functionality is handled by
// treating the button as triggering a submenu. When the button is pressed, the submenu
// appears. Pressing the button again makes the submenu disappear.
vjs.MenuButton.prototype.onFocus = function(){};
// Can't turn off list display that we turned on with focus, because list would go away.
vjs.MenuButton.prototype.onBlur = function(){};
vjs.MenuButton.prototype.onClick = function(){
// When you click the button it adds focus, which will show the menu indefinitely.
// So we'll remove focus when the mouse leaves the button.
// Focus is needed for tab navigation.
this.one('mouseout', vjs.bind(this, function(){
this.menu.unlockShowing();
this.el_.blur();
}));
if (this.buttonPressed_){
this.unpressButton();
} else {
this.pressButton();
}
};
vjs.MenuButton.prototype.onKeyPress = function(event){
event.preventDefault();
// Check for space bar (32) or enter (13) keys
if (event.which == 32 || event.which == 13) {
if (this.buttonPressed_){
this.unpressButton();
} else {
this.pressButton();
}
// Check for escape (27) key
} else if (event.which == 27){
if (this.buttonPressed_){
this.unpressButton();
}
}
};
vjs.MenuButton.prototype.pressButton = function(){
this.buttonPressed_ = true;
this.menu.lockShowing();
this.el_.setAttribute('aria-pressed', true);
if (this.items && this.items.length > 0) {
this.items[0].el().focus(); // set the focus to the title of the submenu
}
};
vjs.MenuButton.prototype.unpressButton = function(){
this.buttonPressed_ = false;
this.menu.unlockShowing();
this.el_.setAttribute('aria-pressed', false);
};
/**
* Custom MediaError to mimic the HTML5 MediaError
* @param {Number} code The media error code
*/
vjs.MediaError = function(code){
if (typeof code === 'number') {
this.code = code;
} else if (typeof code === 'string') {
// default code is zero, so this is a custom error
this.message = code;
} else if (typeof code === 'object') { // object
vjs.obj.merge(this, code);
}
if (!this.message) {
this.message = vjs.MediaError.defaultMessages[this.code] || '';
}
};
/**
* The error code that refers two one of the defined
* MediaError types
* @type {Number}
*/
vjs.MediaError.prototype.code = 0;
/**
* An optional message to be shown with the error.
* Message is not part of the HTML5 video spec
* but allows for more informative custom errors.
* @type {String}
*/
vjs.MediaError.prototype.message = '';
/**
* An optional status code that can be set by plugins
* to allow even more detail about the error.
* For example the HLS plugin might provide the specific
* HTTP status code that was returned when the error
* occurred, then allowing a custom error overlay
* to display more information.
* @type {[type]}
*/
vjs.MediaError.prototype.status = null;
vjs.MediaError.errorTypes = [
'MEDIA_ERR_CUSTOM', // = 0
'MEDIA_ERR_ABORTED', // = 1
'MEDIA_ERR_NETWORK', // = 2
'MEDIA_ERR_DECODE', // = 3
'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4
'MEDIA_ERR_ENCRYPTED' // = 5
];
vjs.MediaError.defaultMessages = {
1: 'You aborted the video playback',
2: 'A network error caused the video download to fail part-way.',
3: 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support.',
4: 'The video could not be loaded, either because the server or network failed or because the format is not supported.',
5: 'The video is encrypted and we do not have the keys to decrypt it.'
};
// Add types as properties on MediaError
// e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
for (var errNum = 0; errNum < vjs.MediaError.errorTypes.length; errNum++) {
vjs.MediaError[vjs.MediaError.errorTypes[errNum]] = errNum;
// values should be accessible on both the class and instance
vjs.MediaError.prototype[vjs.MediaError.errorTypes[errNum]] = errNum;
}
(function(){
var apiMap, specApi, browserApi, i;
/**
* Store the browser-specifc methods for the fullscreen API
* @type {Object|undefined}
* @private
*/
vjs.browser.fullscreenAPI;
// browser API methods
// map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js
apiMap = [
// Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// Old WebKit (Safari 5.1)
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// Mozilla
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
// Microsoft
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
specApi = apiMap[0];
// determine the supported set of functions
for (i=0; i<apiMap.length; i++) {
// check for exitFullscreen function
if (apiMap[i][1] in document) {
browserApi = apiMap[i];
break;
}
}
// map the browser API names to the spec API names
// or leave vjs.browser.fullscreenAPI undefined
if (browserApi) {
vjs.browser.fullscreenAPI = {};
for (i=0; i<browserApi.length; i++) {
vjs.browser.fullscreenAPI[specApi[i]] = browserApi[i];
}
}
})();
/**
* An instance of the `vjs.Player` class is created when any of the Video.js setup methods are used to initialize a video.
*
* ```js
* var myPlayer = videojs('example_video_1');
* ```
*
* In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready.
*
* ```html
* <video id="example_video_1" data-setup='{}' controls>
* <source src="my-source.mp4" type="video/mp4">
* </video>
* ```
*
* After an instance has been created it can be accessed globally using `Video('example_video_1')`.
*
* @class
* @extends vjs.Component
*/
vjs.Player = vjs.Component.extend({
/**
* player's constructor function
*
* @constructs
* @method init
* @param {Element} tag The original video tag used for configuring options
* @param {Object=} options Player options
* @param {Function=} ready Ready callback function
*/
init: function(tag, options, ready){
this.tag = tag; // Store the original tag used to set options
// Make sure tag ID exists
tag.id = tag.id || 'vjs_video_' + vjs.guid++;
// Store the tag attributes used to restore html5 element
this.tagAttributes = tag && vjs.getElementAttributes(tag);
// Set Options
// The options argument overrides options set in the video tag
// which overrides globally set options.
// This latter part coincides with the load order
// (tag must exist before Player)
options = vjs.obj.merge(this.getTagSettings(tag), options);
// Update Current Language
this.language_ = options['language'] || vjs.options['language'];
// Update Supported Languages
this.languages_ = options['languages'] || vjs.options['languages'];
// Cache for video property values.
this.cache_ = {};
// Set poster
this.poster_ = options['poster'];
// Set controls
this.controls_ = options['controls'];
// Original tag settings stored in options
// now remove immediately so native controls don't flash.
// May be turned back on by HTML5 tech if nativeControlsForTouch is true
tag.controls = false;
// we don't want the player to report touch activity on itself
// see enableTouchActivity in Component
options.reportTouchActivity = false;
// Run base component initializing with new options.
// Builds the element through createEl()
// Inits and embeds any child components in opts
vjs.Component.call(this, this, options, ready);
// Update controls className. Can't do this when the controls are initially
// set because the element doesn't exist yet.
if (this.controls()) {
this.addClass('vjs-controls-enabled');
} else {
this.addClass('vjs-controls-disabled');
}
// TODO: Make this smarter. Toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// if (vjs.TOUCH_ENABLED) {
// this.addClass('vjs-touch-enabled');
// }
// Make player easily findable by ID
vjs.players[this.id_] = this;
if (options['plugins']) {
vjs.obj.each(options['plugins'], function(key, val){
this[key](val);
}, this);
}
this.listenForUserActivity();
}
});
/**
* The players's stored language code
*
* @type {String}
* @private
*/
vjs.Player.prototype.language_;
/**
* The player's language code
* @param {String} languageCode The locale string
* @return {String} The locale string when getting
* @return {vjs.Player} self, when setting
*/
vjs.Player.prototype.language = function (languageCode) {
if (languageCode === undefined) {
return this.language_;
}
this.language_ = languageCode;
return this;
};
/**
* The players's stored language dictionary
*
* @type {Object}
* @private
*/
vjs.Player.prototype.languages_;
vjs.Player.prototype.languages = function(){
return this.languages_;
};
/**
* Player instance options, surfaced using vjs.options
* vjs.options = vjs.Player.prototype.options_
* Make changes in vjs.options, not here.
* All options should use string keys so they avoid
* renaming by closure compiler
* @type {Object}
* @private
*/
vjs.Player.prototype.options_ = vjs.options;
/**
* Destroys the video player and does any necessary cleanup
*
* myPlayer.dispose();
*
* This is especially helpful if you are dynamically adding and removing videos
* to/from the DOM.
*/
vjs.Player.prototype.dispose = function(){
this.trigger('dispose');
// prevent dispose from being called twice
this.off('dispose');
// Kill reference to this player
vjs.players[this.id_] = null;
if (this.tag && this.tag['player']) { this.tag['player'] = null; }
if (this.el_ && this.el_['player']) { this.el_['player'] = null; }
if (this.tech) { this.tech.dispose(); }
// Component dispose
vjs.Component.prototype.dispose.call(this);
};
vjs.Player.prototype.getTagSettings = function(tag){
var options = {
'sources': [],
'tracks': []
};
vjs.obj.merge(options, vjs.getElementAttributes(tag));
// Get tag children settings
if (tag.hasChildNodes()) {
var children, child, childName, i, j;
children = tag.childNodes;
for (i=0,j=children.length; i<j; i++) {
child = children[i];
// Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
childName = child.nodeName.toLowerCase();
if (childName === 'source') {
options['sources'].push(vjs.getElementAttributes(child));
} else if (childName === 'track') {
options['tracks'].push(vjs.getElementAttributes(child));
}
}
}
return options;
};
vjs.Player.prototype.createEl = function(){
var
el = this.el_ = vjs.Component.prototype.createEl.call(this, 'div'),
tag = this.tag,
attrs;
// Remove width/height attrs from tag so CSS can make it 100% width/height
tag.removeAttribute('width');
tag.removeAttribute('height');
// Empty video tag tracks so the built-in player doesn't use them also.
// This may not be fast enough to stop HTML5 browsers from reading the tags
// so we'll need to turn off any default tracks if we're manually doing
// captions and subtitles. videoElement.textTracks
if (tag.hasChildNodes()) {
var nodes, nodesLength, i, node, nodeName, removeNodes;
nodes = tag.childNodes;
nodesLength = nodes.length;
removeNodes = [];
while (nodesLength--) {
node = nodes[nodesLength];
nodeName = node.nodeName.toLowerCase();
if (nodeName === 'track') {
removeNodes.push(node);
}
}
for (i=0; i<removeNodes.length; i++) {
tag.removeChild(removeNodes[i]);
}
}
// Copy over all the attributes from the tag, including ID and class
// ID will now reference player box, not the video tag
attrs = vjs.getElementAttributes(tag);
vjs.obj.each(attrs, function(attr) {
el.setAttribute(attr, attrs[attr]);
});
// Update tag id/class for use as HTML5 playback tech
// Might think we should do this after embedding in container so .vjs-tech class
// doesn't flash 100% width/height, but class only applies with .video-js parent
tag.id += '_html5_api';
tag.className = 'vjs-tech';
// Make player findable on elements
tag['player'] = el['player'] = this;
// Default state of video is paused
this.addClass('vjs-paused');
// Make box use width/height of tag, or rely on default implementation
// Enforce with CSS since width/height attrs don't work on divs
this.width(this.options_['width'], true); // (true) Skip resize listener on load
this.height(this.options_['height'], true);
// Wrap video tag in div (el/box) container
if (tag.parentNode) {
tag.parentNode.insertBefore(el, tag);
}
vjs.insertFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup.
// The event listeners need to be added before the children are added
// in the component init because the tech (loaded with mediaLoader) may
// fire events, like loadstart, that these events need to capture.
// Long term it might be better to expose a way to do this in component.init
// like component.initEventListeners() that runs between el creation and
// adding children
this.el_ = el;
this.on('loadstart', this.onLoadStart);
this.on('waiting', this.onWaiting);
this.on(['canplay', 'canplaythrough', 'playing', 'ended'], this.onWaitEnd);
this.on('seeking', this.onSeeking);
this.on('seeked', this.onSeeked);
this.on('ended', this.onEnded);
this.on('play', this.onPlay);
this.on('firstplay', this.onFirstPlay);
this.on('pause', this.onPause);
this.on('progress', this.onProgress);
this.on('durationchange', this.onDurationChange);
this.on('fullscreenchange', this.onFullscreenChange);
return el;
};
// /* Media Technology (tech)
// ================================================================================ */
// Load/Create an instance of playback technlogy including element and API methods
// And append playback element in player div.
vjs.Player.prototype.loadTech = function(techName, source){
// Pause and remove current playback technology
if (this.tech) {
this.unloadTech();
}
// get rid of the HTML5 video tag as soon as we are using another tech
if (techName !== 'Html5' && this.tag) {
vjs.Html5.disposeMediaElement(this.tag);
this.tag = null;
}
this.techName = techName;
// Turn off API access because we're loading a new tech that might load asynchronously
this.isReady_ = false;
var techReady = function(){
this.player_.triggerReady();
};
// Grab tech-specific options from player options and add source and parent element to use.
var techOptions = vjs.obj.merge({ 'source': source, 'parentEl': this.el_ }, this.options_[techName.toLowerCase()]);
if (source) {
this.currentType_ = source.type;
if (source.src == this.cache_.src && this.cache_.currentTime > 0) {
techOptions['startTime'] = this.cache_.currentTime;
}
this.cache_.src = source.src;
}
// Initialize tech instance
this.tech = new window['videojs'][techName](this, techOptions);
this.tech.ready(techReady);
};
vjs.Player.prototype.unloadTech = function(){
this.isReady_ = false;
this.tech.dispose();
this.tech = false;
};
// There's many issues around changing the size of a Flash (or other plugin) object.
// First is a plugin reload issue in Firefox that has been around for 11 years: https://bugzilla.mozilla.org/show_bug.cgi?id=90268
// Then with the new fullscreen API, Mozilla and webkit browsers will reload the flash object after going to fullscreen.
// To get around this, we're unloading the tech, caching source and currentTime values, and reloading the tech once the plugin is resized.
// reloadTech: function(betweenFn){
// vjs.log('unloadingTech')
// this.unloadTech();
// vjs.log('unloadedTech')
// if (betweenFn) { betweenFn.call(); }
// vjs.log('LoadingTech')
// this.loadTech(this.techName, { src: this.cache_.src })
// vjs.log('loadedTech')
// },
// /* Player event handlers (how the player reacts to certain events)
// ================================================================================ */
/**
* Fired when the user agent begins looking for media data
* @event loadstart
*/
vjs.Player.prototype.onLoadStart = function() {
// TODO: Update to use `emptied` event instead. See #1277.
// reset the error state
this.error(null);
// If it's already playing we want to trigger a firstplay event now.
// The firstplay event relies on both the play and loadstart events
// which can happen in any order for a new source
if (!this.paused()) {
this.trigger('firstplay');
} else {
// reset the hasStarted state
this.hasStarted(false);
this.one('play', function(){
this.hasStarted(true);
});
}
};
vjs.Player.prototype.hasStarted_ = false;
vjs.Player.prototype.hasStarted = function(hasStarted){
if (hasStarted !== undefined) {
// only update if this is a new value
if (this.hasStarted_ !== hasStarted) {
this.hasStarted_ = hasStarted;
if (hasStarted) {
this.addClass('vjs-has-started');
// trigger the firstplay event if this newly has played
this.trigger('firstplay');
} else {
this.removeClass('vjs-has-started');
}
}
return this;
}
return this.hasStarted_;
};
/**
* Fired when the player has initial duration and dimension information
* @event loadedmetadata
*/
vjs.Player.prototype.onLoadedMetaData;
/**
* Fired when the player has downloaded data at the current playback position
* @event loadeddata
*/
vjs.Player.prototype.onLoadedData;
/**
* Fired when the player has finished downloading the source data
* @event loadedalldata
*/
vjs.Player.prototype.onLoadedAllData;
/**
* Fired whenever the media begins or resumes playback
* @event play
*/
vjs.Player.prototype.onPlay = function(){
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
};
/**
* Fired whenever the media begins wating
* @event waiting
*/
vjs.Player.prototype.onWaiting = function(){
this.addClass('vjs-waiting');
};
/**
* A handler for events that signal that waiting has eneded
* which is not consistent between browsers. See #1351
*/
vjs.Player.prototype.onWaitEnd = function(){
this.removeClass('vjs-waiting');
};
/**
* Fired whenever the player is jumping to a new time
* @event seeking
*/
vjs.Player.prototype.onSeeking = function(){
this.addClass('vjs-seeking');
};
/**
* Fired when the player has finished jumping to a new time
* @event seeked
*/
vjs.Player.prototype.onSeeked = function(){
this.removeClass('vjs-seeking');
};
/**
* Fired the first time a video is played
*
* Not part of the HLS spec, and we're not sure if this is the best
* implementation yet, so use sparingly. If you don't have a reason to
* prevent playback, use `myPlayer.one('play');` instead.
*
* @event firstplay
*/
vjs.Player.prototype.onFirstPlay = function(){
//If the first starttime attribute is specified
//then we will start at the given offset in seconds
if(this.options_['starttime']){
this.currentTime(this.options_['starttime']);
}
this.addClass('vjs-has-started');
};
/**
* Fired whenever the media has been paused
* @event pause
*/
vjs.Player.prototype.onPause = function(){
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
};
/**
* Fired when the current playback position has changed
*
* During playback this is fired every 15-250 milliseconds, depnding on the
* playback technology in use.
* @event timeupdate
*/
vjs.Player.prototype.onTimeUpdate;
/**
* Fired while the user agent is downloading media data
* @event progress
*/
vjs.Player.prototype.onProgress = function(){
// Add custom event for when source is finished downloading.
if (this.bufferedPercent() == 1) {
this.trigger('loadedalldata');
}
};
/**
* Fired when the end of the media resource is reached (currentTime == duration)
* @event ended
*/
vjs.Player.prototype.onEnded = function(){
if (this.options_['loop']) {
this.currentTime(0);
this.play();
} else if (!this.paused()) {
this.pause();
}
};
/**
* Fired when the duration of the media resource is first known or changed
* @event durationchange
*/
vjs.Player.prototype.onDurationChange = function(){
// Allows for cacheing value instead of asking player each time.
// We need to get the techGet response and check for a value so we don't
// accidentally cause the stack to blow up.
var duration = this.techGet('duration');
if (duration) {
if (duration < 0) {
duration = Infinity;
}
this.duration(duration);
// Determine if the stream is live and propagate styles down to UI.
if (duration === Infinity) {
this.addClass('vjs-live');
} else {
this.removeClass('vjs-live');
}
}
};
/**
* Fired when the volume changes
* @event volumechange
*/
vjs.Player.prototype.onVolumeChange;
/**
* Fired when the player switches in or out of fullscreen mode
* @event fullscreenchange
*/
vjs.Player.prototype.onFullscreenChange = function() {
if (this.isFullscreen()) {
this.addClass('vjs-fullscreen');
} else {
this.removeClass('vjs-fullscreen');
}
};
// /* Player API
// ================================================================================ */
/**
* Object for cached values.
* @private
*/
vjs.Player.prototype.cache_;
vjs.Player.prototype.getCache = function(){
return this.cache_;
};
// Pass values to the playback tech
vjs.Player.prototype.techCall = function(method, arg){
// If it's not ready yet, call method when it is
if (this.tech && !this.tech.isReady_) {
this.tech.ready(function(){
this[method](arg);
});
// Otherwise call method now
} else {
try {
this.tech[method](arg);
} catch(e) {
vjs.log(e);
throw e;
}
}
};
// Get calls can't wait for the tech, and sometimes don't need to.
vjs.Player.prototype.techGet = function(method){
if (this.tech && this.tech.isReady_) {
// Flash likes to die and reload when you hide or reposition it.
// In these cases the object methods go away and we get errors.
// When that happens we'll catch the errors and inform tech that it's not ready any more.
try {
return this.tech[method]();
} catch(e) {
// When building additional tech libs, an expected method may not be defined yet
if (this.tech[method] === undefined) {
vjs.log('Video.js: ' + method + ' method not defined for '+this.techName+' playback technology.', e);
} else {
// When a method isn't available on the object it throws a TypeError
if (e.name == 'TypeError') {
vjs.log('Video.js: ' + method + ' unavailable on '+this.techName+' playback technology element.', e);
this.tech.isReady_ = false;
} else {
vjs.log(e);
}
}
throw e;
}
}
return;
};
/**
* start media playback
*
* myPlayer.play();
*
* @return {vjs.Player} self
*/
vjs.Player.prototype.play = function(){
this.techCall('play');
return this;
};
/**
* Pause the video playback
*
* myPlayer.pause();
*
* @return {vjs.Player} self
*/
vjs.Player.prototype.pause = function(){
this.techCall('pause');
return this;
};
/**
* Check if the player is paused
*
* var isPaused = myPlayer.paused();
* var isPlaying = !myPlayer.paused();
*
* @return {Boolean} false if the media is currently playing, or true otherwise
*/
vjs.Player.prototype.paused = function(){
// The initial state of paused should be true (in Safari it's actually false)
return (this.techGet('paused') === false) ? false : true;
};
/**
* Get or set the current time (in seconds)
*
* // get
* var whereYouAt = myPlayer.currentTime();
*
* // set
* myPlayer.currentTime(120); // 2 minutes into the video
*
* @param {Number|String=} seconds The time to seek to
* @return {Number} The time in seconds, when not setting
* @return {vjs.Player} self, when the current time is set
*/
vjs.Player.prototype.currentTime = function(seconds){
if (seconds !== undefined) {
this.techCall('setCurrentTime', seconds);
return this;
}
// cache last currentTime and return. default to 0 seconds
//
// Caching the currentTime is meant to prevent a massive amount of reads on the tech's
// currentTime when scrubbing, but may not provide much performace benefit afterall.
// Should be tested. Also something has to read the actual current time or the cache will
// never get updated.
return this.cache_.currentTime = (this.techGet('currentTime') || 0);
};
/**
* Get the length in time of the video in seconds
*
* var lengthOfVideo = myPlayer.duration();
*
* **NOTE**: The video must have started loading before the duration can be
* known, and in the case of Flash, may not be known until the video starts
* playing.
*
* @return {Number} The duration of the video in seconds
*/
vjs.Player.prototype.duration = function(seconds){
if (seconds !== undefined) {
// cache the last set value for optimiized scrubbing (esp. Flash)
this.cache_.duration = parseFloat(seconds);
return this;
}
if (this.cache_.duration === undefined) {
this.onDurationChange();
}
return this.cache_.duration || 0;
};
// Calculates how much time is left. Not in spec, but useful.
vjs.Player.prototype.remainingTime = function(){
return this.duration() - this.currentTime();
};
// http://dev.w3.org/html5/spec/video.html#dom-media-buffered
// Buffered returns a timerange object.
// Kind of like an array of portions of the video that have been downloaded.
/**
* Get a TimeRange object with the times of the video that have been downloaded
*
* If you just want the percent of the video that's been downloaded,
* use bufferedPercent.
*
* // Number of different ranges of time have been buffered. Usually 1.
* numberOfRanges = bufferedTimeRange.length,
*
* // Time in seconds when the first range starts. Usually 0.
* firstRangeStart = bufferedTimeRange.start(0),
*
* // Time in seconds when the first range ends
* firstRangeEnd = bufferedTimeRange.end(0),
*
* // Length in seconds of the first time range
* firstRangeLength = firstRangeEnd - firstRangeStart;
*
* @return {Object} A mock TimeRange object (following HTML spec)
*/
vjs.Player.prototype.buffered = function(){
var buffered = this.techGet('buffered');
if (!buffered || !buffered.length) {
buffered = vjs.createTimeRange(0,0);
}
return buffered;
};
/**
* Get the percent (as a decimal) of the video that's been downloaded
*
* var howMuchIsDownloaded = myPlayer.bufferedPercent();
*
* 0 means none, 1 means all.
* (This method isn't in the HTML5 spec, but it's very convenient)
*
* @return {Number} A decimal between 0 and 1 representing the percent
*/
vjs.Player.prototype.bufferedPercent = function(){
var duration = this.duration(),
buffered = this.buffered(),
bufferedDuration = 0,
start, end;
if (!duration) {
return 0;
}
for (var i=0; i<buffered.length; i++){
start = buffered.start(i);
end = buffered.end(i);
// buffered end can be bigger than duration by a very small fraction
if (end > duration) {
end = duration;
}
bufferedDuration += end - start;
}
return bufferedDuration / duration;
};
/**
* Get the ending time of the last buffered time range
*
* This is used in the progress bar to encapsulate all time ranges.
* @return {Number} The end of the last buffered time range
*/
vjs.Player.prototype.bufferedEnd = function(){
var buffered = this.buffered(),
duration = this.duration(),
end = buffered.end(buffered.length-1);
if (end > duration) {
end = duration;
}
return end;
};
/**
* Get or set the current volume of the media
*
* // get
* var howLoudIsIt = myPlayer.volume();
*
* // set
* myPlayer.volume(0.5); // Set volume to half
*
* 0 is off (muted), 1.0 is all the way up, 0.5 is half way.
*
* @param {Number} percentAsDecimal The new volume as a decimal percent
* @return {Number} The current volume, when getting
* @return {vjs.Player} self, when setting
*/
vjs.Player.prototype.volume = function(percentAsDecimal){
var vol;
if (percentAsDecimal !== undefined) {
vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1
this.cache_.volume = vol;
this.techCall('setVolume', vol);
vjs.setLocalStorage('volume', vol);
return this;
}
// Default to 1 when returning current volume.
vol = parseFloat(this.techGet('volume'));
return (isNaN(vol)) ? 1 : vol;
};
/**
* Get the current muted state, or turn mute on or off
*
* // get
* var isVolumeMuted = myPlayer.muted();
*
* // set
* myPlayer.muted(true); // mute the volume
*
* @param {Boolean=} muted True to mute, false to unmute
* @return {Boolean} True if mute is on, false if not, when getting
* @return {vjs.Player} self, when setting mute
*/
vjs.Player.prototype.muted = function(muted){
if (muted !== undefined) {
this.techCall('setMuted', muted);
return this;
}
return this.techGet('muted') || false; // Default to false
};
// Check if current tech can support native fullscreen
// (e.g. with built in controls lik iOS, so not our flash swf)
vjs.Player.prototype.supportsFullScreen = function(){
return this.techGet('supportsFullScreen') || false;
};
/**
* is the player in fullscreen
* @type {Boolean}
* @private
*/
vjs.Player.prototype.isFullscreen_ = false;
/**
* Check if the player is in fullscreen mode
*
* // get
* var fullscreenOrNot = myPlayer.isFullscreen();
*
* // set
* myPlayer.isFullscreen(true); // tell the player it's in fullscreen
*
* NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
* property and instead document.fullscreenElement is used. But isFullscreen is
* still a valuable property for internal player workings.
*
* @param {Boolean=} isFS Update the player's fullscreen state
* @return {Boolean} true if fullscreen, false if not
* @return {vjs.Player} self, when setting
*/
vjs.Player.prototype.isFullscreen = function(isFS){
if (isFS !== undefined) {
this.isFullscreen_ = !!isFS;
return this;
}
return this.isFullscreen_;
};
/**
* Old naming for isFullscreen()
* @deprecated for lowercase 's' version
*/
vjs.Player.prototype.isFullScreen = function(isFS){
vjs.log.warn('player.isFullScreen() has been deprecated, use player.isFullscreen() with a lowercase "s")');
return this.isFullscreen(isFS);
};
/**
* Increase the size of the video to full screen
*
* myPlayer.requestFullscreen();
*
* In some browsers, full screen is not supported natively, so it enters
* "full window mode", where the video fills the browser window.
* In browsers and devices that support native full screen, sometimes the
* browser's default controls will be shown, and not the Video.js custom skin.
* This includes most mobile devices (iOS, Android) and older versions of
* Safari.
*
* @return {vjs.Player} self
*/
vjs.Player.prototype.requestFullscreen = function(){
var fsApi = vjs.browser.fullscreenAPI;
this.isFullscreen(true);
if (fsApi) {
// the browser supports going fullscreen at the element level so we can
// take the controls fullscreen as well as the video
// Trigger fullscreenchange event after change
// We have to specifically add this each time, and remove
// when cancelling fullscreen. Otherwise if there's multiple
// players on a page, they would all be reacting to the same fullscreen
// events
vjs.on(document, fsApi['fullscreenchange'], vjs.bind(this, function(e){
this.isFullscreen(document[fsApi.fullscreenElement]);
// If cancelling fullscreen, remove event listener.
if (this.isFullscreen() === false) {
vjs.off(document, fsApi['fullscreenchange'], arguments.callee);
}
this.trigger('fullscreenchange');
}));
this.el_[fsApi.requestFullscreen]();
} else if (this.tech.supportsFullScreen()) {
// we can't take the video.js controls fullscreen but we can go fullscreen
// with native controls
this.techCall('enterFullScreen');
} else {
// fullscreen isn't supported so we'll just stretch the video element to
// fill the viewport
this.enterFullWindow();
this.trigger('fullscreenchange');
}
return this;
};
/**
* Old naming for requestFullscreen
* @deprecated for lower case 's' version
*/
vjs.Player.prototype.requestFullScreen = function(){
vjs.log.warn('player.requestFullScreen() has been deprecated, use player.requestFullscreen() with a lowercase "s")');
return this.requestFullscreen();
};
/**
* Return the video to its normal size after having been in full screen mode
*
* myPlayer.exitFullscreen();
*
* @return {vjs.Player} self
*/
vjs.Player.prototype.exitFullscreen = function(){
var fsApi = vjs.browser.fullscreenAPI;
this.isFullscreen(false);
// Check for browser element fullscreen support
if (fsApi) {
document[fsApi.exitFullscreen]();
} else if (this.tech.supportsFullScreen()) {
this.techCall('exitFullScreen');
} else {
this.exitFullWindow();
this.trigger('fullscreenchange');
}
return this;
};
/**
* Old naming for exitFullscreen
* @deprecated for exitFullscreen
*/
vjs.Player.prototype.cancelFullScreen = function(){
vjs.log.warn('player.cancelFullScreen() has been deprecated, use player.exitFullscreen()');
return this.exitFullscreen();
};
// When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us.
vjs.Player.prototype.enterFullWindow = function(){
this.isFullWindow = true;
// Storing original doc overflow value to return to when fullscreen is off
this.docOrigOverflow = document.documentElement.style.overflow;
// Add listener for esc key to exit fullscreen
vjs.on(document, 'keydown', vjs.bind(this, this.fullWindowOnEscKey));
// Hide any scroll bars
document.documentElement.style.overflow = 'hidden';
// Apply fullscreen styles
vjs.addClass(document.body, 'vjs-full-window');
this.trigger('enterFullWindow');
};
vjs.Player.prototype.fullWindowOnEscKey = function(event){
if (event.keyCode === 27) {
if (this.isFullscreen() === true) {
this.exitFullscreen();
} else {
this.exitFullWindow();
}
}
};
vjs.Player.prototype.exitFullWindow = function(){
this.isFullWindow = false;
vjs.off(document, 'keydown', this.fullWindowOnEscKey);
// Unhide scroll bars.
document.documentElement.style.overflow = this.docOrigOverflow;
// Remove fullscreen styles
vjs.removeClass(document.body, 'vjs-full-window');
// Resize the box, controller, and poster to original sizes
// this.positionAll();
this.trigger('exitFullWindow');
};
vjs.Player.prototype.selectSource = function(sources){
// Loop through each playback technology in the options order
for (var i=0,j=this.options_['techOrder'];i<j.length;i++) {
var techName = vjs.capitalize(j[i]),
tech = window['videojs'][techName];
// Check if the current tech is defined before continuing
if (!tech) {
vjs.log.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.');
continue;
}
// Check if the browser supports this technology
if (tech.isSupported()) {
// Loop through each source object
for (var a=0,b=sources;a<b.length;a++) {
var source = b[a];
// Check if source can be played with this technology
if (tech['canPlaySource'](source)) {
return { source: source, tech: techName };
}
}
}
}
return false;
};
/**
* The source function updates the video source
*
* There are three types of variables you can pass as the argument.
*
* **URL String**: A URL to the the video file. Use this method if you are sure
* the current playback technology (HTML5/Flash) can support the source you
* provide. Currently only MP4 files can be used in both HTML5 and Flash.
*
* myPlayer.src("http://www.example.com/path/to/video.mp4");
*
* **Source Object (or element):** A javascript object containing information
* about the source file. Use this method if you want the player to determine if
* it can support the file using the type information.
*
* myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" });
*
* **Array of Source Objects:** To provide multiple versions of the source so
* that it can be played using HTML5 across browsers you can use an array of
* source objects. Video.js will detect which version is supported and load that
* file.
*
* myPlayer.src([
* { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" },
* { type: "video/webm", src: "http://www.example.com/path/to/video.webm" },
* { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" }
* ]);
*
* @param {String|Object|Array=} source The source URL, object, or array of sources
* @return {String} The current video source when getting
* @return {String} The player when setting
*/
vjs.Player.prototype.src = function(source){
if (source === undefined) {
return this.techGet('src');
}
// case: Array of source objects to choose from and pick the best to play
if (vjs.obj.isArray(source)) {
this.sourceList_(source);
// case: URL String (http://myvideo...)
} else if (typeof source === 'string') {
// create a source object from the string
this.src({ src: source });
// case: Source object { src: '', type: '' ... }
} else if (source instanceof Object) {
// check if the source has a type and the loaded tech cannot play the source
// if there's no type we'll just try the current tech
if (source.type && !window['videojs'][this.techName]['canPlaySource'](source)) {
// create a source list with the current source and send through
// the tech loop to check for a compatible technology
this.sourceList_([source]);
} else {
this.cache_.src = source.src;
this.currentType_ = source.type || '';
// wait until the tech is ready to set the source
this.ready(function(){
this.techCall('src', source.src);
if (this.options_['preload'] == 'auto') {
this.load();
}
if (this.options_['autoplay']) {
this.play();
}
});
}
}
return this;
};
/**
* Handle an array of source objects
* @param {[type]} sources Array of source objects
* @private
*/
vjs.Player.prototype.sourceList_ = function(sources){
var sourceTech = this.selectSource(sources),
errorTimeout;
if (sourceTech) {
if (sourceTech.tech === this.techName) {
// if this technology is already loaded, set the source
this.src(sourceTech.source);
} else {
// load this technology with the chosen source
this.loadTech(sourceTech.tech, sourceTech.source);
}
} else {
// We need to wrap this in a timeout to give folks a chance to add error event handlers
errorTimeout = setTimeout(vjs.bind(this, function() {
this.error({ code: 4, message: this.localize(this.options()['notSupportedMessage']) });
}), 0);
// we could not find an appropriate tech, but let's still notify the delegate that this is it
// this needs a better comment about why this is needed
this.triggerReady();
this.on('dispose', function() {
clearTimeout(errorTimeout);
});
}
};
// Begin loading the src data
// http://dev.w3.org/html5/spec/video.html#dom-media-load
vjs.Player.prototype.load = function(){
this.techCall('load');
return this;
};
// http://dev.w3.org/html5/spec/video.html#dom-media-currentsrc
vjs.Player.prototype.currentSrc = function(){
return this.techGet('currentSrc') || this.cache_.src || '';
};
/**
* Get the current source type e.g. video/mp4
* This can allow you rebuild the current source object so that you could load the same
* source and tech later
* @return {String} The source MIME type
*/
vjs.Player.prototype.currentType = function(){
return this.currentType_ || '';
};
// Attributes/Options
vjs.Player.prototype.preload = function(value){
if (value !== undefined) {
this.techCall('setPreload', value);
this.options_['preload'] = value;
return this;
}
return this.techGet('preload');
};
vjs.Player.prototype.autoplay = function(value){
if (value !== undefined) {
this.techCall('setAutoplay', value);
this.options_['autoplay'] = value;
return this;
}
return this.techGet('autoplay', value);
};
vjs.Player.prototype.loop = function(value){
if (value !== undefined) {
this.techCall('setLoop', value);
this.options_['loop'] = value;
return this;
}
return this.techGet('loop');
};
/**
* the url of the poster image source
* @type {String}
* @private
*/
vjs.Player.prototype.poster_;
/**
* get or set the poster image source url
*
* ##### EXAMPLE:
*
* // getting
* var currentPoster = myPlayer.poster();
*
* // setting
* myPlayer.poster('http://example.com/myImage.jpg');
*
* @param {String=} [src] Poster image source URL
* @return {String} poster URL when getting
* @return {vjs.Player} self when setting
*/
vjs.Player.prototype.poster = function(src){
if (src === undefined) {
return this.poster_;
}
// update the internal poster variable
this.poster_ = src;
// update the tech's poster
this.techCall('setPoster', src);
// alert components that the poster has been set
this.trigger('posterchange');
};
/**
* Whether or not the controls are showing
* @type {Boolean}
* @private
*/
vjs.Player.prototype.controls_;
/**
* Get or set whether or not the controls are showing.
* @param {Boolean} controls Set controls to showing or not
* @return {Boolean} Controls are showing
*/
vjs.Player.prototype.controls = function(bool){
if (bool !== undefined) {
bool = !!bool; // force boolean
// Don't trigger a change event unless it actually changed
if (this.controls_ !== bool) {
this.controls_ = bool;
if (bool) {
this.removeClass('vjs-controls-disabled');
this.addClass('vjs-controls-enabled');
this.trigger('controlsenabled');
} else {
this.removeClass('vjs-controls-enabled');
this.addClass('vjs-controls-disabled');
this.trigger('controlsdisabled');
}
}
return this;
}
return this.controls_;
};
vjs.Player.prototype.usingNativeControls_;
/**
* Toggle native controls on/off. Native controls are the controls built into
* devices (e.g. default iPhone controls), Flash, or other techs
* (e.g. Vimeo Controls)
*
* **This should only be set by the current tech, because only the tech knows
* if it can support native controls**
*
* @param {Boolean} bool True signals that native controls are on
* @return {vjs.Player} Returns the player
* @private
*/
vjs.Player.prototype.usingNativeControls = function(bool){
if (bool !== undefined) {
bool = !!bool; // force boolean
// Don't trigger a change event unless it actually changed
if (this.usingNativeControls_ !== bool) {
this.usingNativeControls_ = bool;
if (bool) {
this.addClass('vjs-using-native-controls');
/**
* player is using the native device controls
*
* @event usingnativecontrols
* @memberof vjs.Player
* @instance
* @private
*/
this.trigger('usingnativecontrols');
} else {
this.removeClass('vjs-using-native-controls');
/**
* player is using the custom HTML controls
*
* @event usingcustomcontrols
* @memberof vjs.Player
* @instance
* @private
*/
this.trigger('usingcustomcontrols');
}
}
return this;
}
return this.usingNativeControls_;
};
/**
* Store the current media error
* @type {Object}
* @private
*/
vjs.Player.prototype.error_ = null;
/**
* Set or get the current MediaError
* @param {*} err A MediaError or a String/Number to be turned into a MediaError
* @return {vjs.MediaError|null} when getting
* @return {vjs.Player} when setting
*/
vjs.Player.prototype.error = function(err){
if (err === undefined) {
return this.error_;
}
// restoring to default
if (err === null) {
this.error_ = err;
this.removeClass('vjs-error');
return this;
}
// error instance
if (err instanceof vjs.MediaError) {
this.error_ = err;
} else {
this.error_ = new vjs.MediaError(err);
}
// fire an error event on the player
this.trigger('error');
// add the vjs-error classname to the player
this.addClass('vjs-error');
// log the name of the error type and any message
// ie8 just logs "[object object]" if you just log the error object
vjs.log.error('(CODE:'+this.error_.code+' '+vjs.MediaError.errorTypes[this.error_.code]+')', this.error_.message, this.error_);
return this;
};
vjs.Player.prototype.ended = function(){ return this.techGet('ended'); };
vjs.Player.prototype.seeking = function(){ return this.techGet('seeking'); };
// When the player is first initialized, trigger activity so components
// like the control bar show themselves if needed
vjs.Player.prototype.userActivity_ = true;
vjs.Player.prototype.reportUserActivity = function(event){
this.userActivity_ = true;
};
vjs.Player.prototype.userActive_ = true;
vjs.Player.prototype.userActive = function(bool){
if (bool !== undefined) {
bool = !!bool;
if (bool !== this.userActive_) {
this.userActive_ = bool;
if (bool) {
// If the user was inactive and is now active we want to reset the
// inactivity timer
this.userActivity_ = true;
this.removeClass('vjs-user-inactive');
this.addClass('vjs-user-active');
this.trigger('useractive');
} else {
// We're switching the state to inactive manually, so erase any other
// activity
this.userActivity_ = false;
// Chrome/Safari/IE have bugs where when you change the cursor it can
// trigger a mousemove event. This causes an issue when you're hiding
// the cursor when the user is inactive, and a mousemove signals user
// activity. Making it impossible to go into inactive mode. Specifically
// this happens in fullscreen when we really need to hide the cursor.
//
// When this gets resolved in ALL browsers it can be removed
// https://code.google.com/p/chromium/issues/detail?id=103041
if(this.tech) {
this.tech.one('mousemove', function(e){
e.stopPropagation();
e.preventDefault();
});
}
this.removeClass('vjs-user-active');
this.addClass('vjs-user-inactive');
this.trigger('userinactive');
}
}
return this;
}
return this.userActive_;
};
vjs.Player.prototype.listenForUserActivity = function(){
var onActivity, onMouseMove, onMouseDown, mouseInProgress, onMouseUp,
activityCheck, inactivityTimeout, lastMoveX, lastMoveY;
onActivity = vjs.bind(this, this.reportUserActivity);
onMouseMove = function(e) {
// #1068 - Prevent mousemove spamming
// Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
if(e.screenX != lastMoveX || e.screenY != lastMoveY) {
lastMoveX = e.screenX;
lastMoveY = e.screenY;
onActivity();
}
};
onMouseDown = function() {
onActivity();
// For as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// So we want to continue to update that they are active
clearInterval(mouseInProgress);
// Setting userActivity=true now and setting the interval to the same time
// as the activityCheck interval (250) should ensure we never miss the
// next activityCheck
mouseInProgress = setInterval(onActivity, 250);
};
onMouseUp = function(event) {
onActivity();
// Stop the interval that maintains activity if the mouse/touch is down
clearInterval(mouseInProgress);
};
// Any mouse movement will be considered user activity
this.on('mousedown', onMouseDown);
this.on('mousemove', onMouseMove);
this.on('mouseup', onMouseUp);
// Listen for keyboard navigation
// Shouldn't need to use inProgress interval because of key repeat
this.on('keydown', onActivity);
this.on('keyup', onActivity);
// Run an interval every 250 milliseconds instead of stuffing everything into
// the mousemove/touchmove function itself, to prevent performance degradation.
// `this.reportUserActivity` simply sets this.userActivity_ to true, which
// then gets picked up by this loop
// http://ejohn.org/blog/learning-from-twitter/
activityCheck = setInterval(vjs.bind(this, function() {
// Check to see if mouse/touch activity has happened
if (this.userActivity_) {
// Reset the activity tracker
this.userActivity_ = false;
// If the user state was inactive, set the state to active
this.userActive(true);
// Clear any existing inactivity timeout to start the timer over
clearTimeout(inactivityTimeout);
var timeout = this.options()['inactivityTimeout'];
if (timeout > 0) {
// In <timeout> milliseconds, if no more activity has occurred the
// user will be considered inactive
inactivityTimeout = setTimeout(vjs.bind(this, function () {
// Protect against the case where the inactivityTimeout can trigger just
// before the next user activity is picked up by the activityCheck loop
// causing a flicker
if (!this.userActivity_) {
this.userActive(false);
}
}), timeout);
}
}
}), 250);
// Clean up the intervals when we kill the player
this.on('dispose', function(){
clearInterval(activityCheck);
clearTimeout(inactivityTimeout);
});
};
vjs.Player.prototype.playbackRate = function(rate) {
if (rate !== undefined) {
this.techCall('setPlaybackRate', rate);
return this;
}
if (this.tech && this.tech['featuresPlaybackRate']) {
return this.techGet('playbackRate');
} else {
return 1.0;
}
};
// Methods to add support for
// networkState: function(){ return this.techCall('networkState'); },
// readyState: function(){ return this.techCall('readyState'); },
// initialTime: function(){ return this.techCall('initialTime'); },
// startOffsetTime: function(){ return this.techCall('startOffsetTime'); },
// played: function(){ return this.techCall('played'); },
// seekable: function(){ return this.techCall('seekable'); },
// videoTracks: function(){ return this.techCall('videoTracks'); },
// audioTracks: function(){ return this.techCall('audioTracks'); },
// videoWidth: function(){ return this.techCall('videoWidth'); },
// videoHeight: function(){ return this.techCall('videoHeight'); },
// defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); },
// mediaGroup: function(){ return this.techCall('mediaGroup'); },
// controller: function(){ return this.techCall('controller'); },
// defaultMuted: function(){ return this.techCall('defaultMuted'); }
// TODO
// currentSrcList: the array of sources including other formats and bitrates
// playList: array of source lists in order of playback
/**
* Container of main controls
* @param {vjs.Player|Object} player
* @param {Object=} options
* @class
* @constructor
* @extends vjs.Component
*/
vjs.ControlBar = vjs.Component.extend();
vjs.ControlBar.prototype.options_ = {
loadEvent: 'play',
children: {
'playToggle': {},
'currentTimeDisplay': {},
'timeDivider': {},
'durationDisplay': {},
'remainingTimeDisplay': {},
'liveDisplay': {},
'progressControl': {},
'fullscreenToggle': {},
'volumeControl': {},
'muteToggle': {},
// 'volumeMenuButton': {},
'playbackRateMenuButton': {}
}
};
vjs.ControlBar.prototype.createEl = function(){
return vjs.createEl('div', {
className: 'vjs-control-bar'
});
};
/**
* Displays the live indicator
* TODO - Future make it click to snap to live
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.LiveDisplay = vjs.Component.extend({
init: function(player, options){
vjs.Component.call(this, player, options);
}
});
vjs.LiveDisplay.prototype.createEl = function(){
var el = vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-live-controls vjs-control'
});
this.contentEl_ = vjs.createEl('div', {
className: 'vjs-live-display',
innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE'),
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Button to toggle between play and pause
* @param {vjs.Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
vjs.PlayToggle = vjs.Button.extend({
/** @constructor */
init: function(player, options){
vjs.Button.call(this, player, options);
player.on('play', vjs.bind(this, this.onPlay));
player.on('pause', vjs.bind(this, this.onPause));
}
});
vjs.PlayToggle.prototype.buttonText = 'Play';
vjs.PlayToggle.prototype.buildCSSClass = function(){
return 'vjs-play-control ' + vjs.Button.prototype.buildCSSClass.call(this);
};
// OnClick - Toggle between play and pause
vjs.PlayToggle.prototype.onClick = function(){
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
};
// OnPlay - Add the vjs-playing class to the element so it can change appearance
vjs.PlayToggle.prototype.onPlay = function(){
vjs.removeClass(this.el_, 'vjs-paused');
vjs.addClass(this.el_, 'vjs-playing');
this.el_.children[0].children[0].innerHTML = this.localize('Pause'); // change the button text to "Pause"
};
// OnPause - Add the vjs-paused class to the element so it can change appearance
vjs.PlayToggle.prototype.onPause = function(){
vjs.removeClass(this.el_, 'vjs-playing');
vjs.addClass(this.el_, 'vjs-paused');
this.el_.children[0].children[0].innerHTML = this.localize('Play'); // change the button text to "Play"
};
/**
* Displays the current time
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.CurrentTimeDisplay = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
player.on('timeupdate', vjs.bind(this, this.updateContent));
}
});
vjs.CurrentTimeDisplay.prototype.createEl = function(){
var el = vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-current-time vjs-time-controls vjs-control'
});
this.contentEl_ = vjs.createEl('div', {
className: 'vjs-current-time-display',
innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users
'aria-live': 'off' // tell screen readers not to automatically read the time as it changes
});
el.appendChild(this.contentEl_);
return el;
};
vjs.CurrentTimeDisplay.prototype.updateContent = function(){
// Allows for smooth scrubbing, when player can't keep up.
var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime();
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Current Time') + '</span> ' + vjs.formatTime(time, this.player_.duration());
};
/**
* Displays the duration
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.DurationDisplay = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
// this might need to be changed to 'durationchange' instead of 'timeupdate' eventually,
// however the durationchange event fires before this.player_.duration() is set,
// so the value cannot be written out using this method.
// Once the order of durationchange and this.player_.duration() being set is figured out,
// this can be updated.
player.on('timeupdate', vjs.bind(this, this.updateContent));
}
});
vjs.DurationDisplay.prototype.createEl = function(){
var el = vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-duration vjs-time-controls vjs-control'
});
this.contentEl_ = vjs.createEl('div', {
className: 'vjs-duration-display',
innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> ' + '0:00', // label the duration time for screen reader users
'aria-live': 'off' // tell screen readers not to automatically read the time as it changes
});
el.appendChild(this.contentEl_);
return el;
};
vjs.DurationDisplay.prototype.updateContent = function(){
var duration = this.player_.duration();
if (duration) {
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> ' + vjs.formatTime(duration); // label the duration time for screen reader users
}
};
/**
* The separator between the current time and duration
*
* Can be hidden if it's not needed in the design.
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.TimeDivider = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
}
});
vjs.TimeDivider.prototype.createEl = function(){
return vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-time-divider',
innerHTML: '<div><span>/</span></div>'
});
};
/**
* Displays the time left in the video
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.RemainingTimeDisplay = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
player.on('timeupdate', vjs.bind(this, this.updateContent));
}
});
vjs.RemainingTimeDisplay.prototype.createEl = function(){
var el = vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-remaining-time vjs-time-controls vjs-control'
});
this.contentEl_ = vjs.createEl('div', {
className: 'vjs-remaining-time-display',
innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> ' + '-0:00', // label the remaining time for screen reader users
'aria-live': 'off' // tell screen readers not to automatically read the time as it changes
});
el.appendChild(this.contentEl_);
return el;
};
vjs.RemainingTimeDisplay.prototype.updateContent = function(){
if (this.player_.duration()) {
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> ' + '-'+ vjs.formatTime(this.player_.remainingTime());
}
// Allows for smooth scrubbing, when player can't keep up.
// var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime();
// this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration());
};
/**
* Toggle fullscreen video
* @param {vjs.Player|Object} player
* @param {Object=} options
* @class
* @extends vjs.Button
*/
vjs.FullscreenToggle = vjs.Button.extend({
/**
* @constructor
* @memberof vjs.FullscreenToggle
* @instance
*/
init: function(player, options){
vjs.Button.call(this, player, options);
}
});
vjs.FullscreenToggle.prototype.buttonText = 'Fullscreen';
vjs.FullscreenToggle.prototype.buildCSSClass = function(){
return 'vjs-fullscreen-control ' + vjs.Button.prototype.buildCSSClass.call(this);
};
vjs.FullscreenToggle.prototype.onClick = function(){
if (!this.player_.isFullscreen()) {
this.player_.requestFullscreen();
this.controlText_.innerHTML = this.localize('Non-Fullscreen');
} else {
this.player_.exitFullscreen();
this.controlText_.innerHTML = this.localize('Fullscreen');
}
};
/**
* The Progress Control component contains the seek bar, load progress,
* and play progress
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.ProgressControl = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
}
});
vjs.ProgressControl.prototype.options_ = {
children: {
'seekBar': {}
}
};
vjs.ProgressControl.prototype.createEl = function(){
return vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-control vjs-control'
});
};
/**
* Seek Bar and holder for the progress bars
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.SeekBar = vjs.Slider.extend({
/** @constructor */
init: function(player, options){
vjs.Slider.call(this, player, options);
player.on('timeupdate', vjs.bind(this, this.updateARIAAttributes));
player.ready(vjs.bind(this, this.updateARIAAttributes));
}
});
vjs.SeekBar.prototype.options_ = {
children: {
'loadProgressBar': {},
'playProgressBar': {},
'seekHandle': {}
},
'barName': 'playProgressBar',
'handleName': 'seekHandle'
};
vjs.SeekBar.prototype.playerEvent = 'timeupdate';
vjs.SeekBar.prototype.createEl = function(){
return vjs.Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-holder',
'aria-label': 'video progress bar'
});
};
vjs.SeekBar.prototype.updateARIAAttributes = function(){
// Allows for smooth scrubbing, when player can't keep up.
var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime();
this.el_.setAttribute('aria-valuenow',vjs.round(this.getPercent()*100, 2)); // machine readable value of progress bar (percentage complete)
this.el_.setAttribute('aria-valuetext',vjs.formatTime(time, this.player_.duration())); // human readable value of progress bar (time complete)
};
vjs.SeekBar.prototype.getPercent = function(){
return this.player_.currentTime() / this.player_.duration();
};
vjs.SeekBar.prototype.onMouseDown = function(event){
vjs.Slider.prototype.onMouseDown.call(this, event);
this.player_.scrubbing = true;
this.videoWasPlaying = !this.player_.paused();
this.player_.pause();
};
vjs.SeekBar.prototype.onMouseMove = function(event){
var newTime = this.calculateDistance(event) * this.player_.duration();
// Don't let video end while scrubbing.
if (newTime == this.player_.duration()) { newTime = newTime - 0.1; }
// Set new time (tell player to seek to new time)
this.player_.currentTime(newTime);
};
vjs.SeekBar.prototype.onMouseUp = function(event){
vjs.Slider.prototype.onMouseUp.call(this, event);
this.player_.scrubbing = false;
if (this.videoWasPlaying) {
this.player_.play();
}
};
vjs.SeekBar.prototype.stepForward = function(){
this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users
};
vjs.SeekBar.prototype.stepBack = function(){
this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users
};
/**
* Shows load progress
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.LoadProgressBar = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
player.on('progress', vjs.bind(this, this.update));
}
});
vjs.LoadProgressBar.prototype.createEl = function(){
return vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-load-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>'
});
};
vjs.LoadProgressBar.prototype.update = function(){
var i, start, end, part,
buffered = this.player_.buffered(),
duration = this.player_.duration(),
bufferedEnd = this.player_.bufferedEnd(),
children = this.el_.children,
// get the percent width of a time compared to the total end
percentify = function (time, end){
var percent = (time / end) || 0; // no NaN
return (percent * 100) + '%';
};
// update the width of the progress bar
this.el_.style.width = percentify(bufferedEnd, duration);
// add child elements to represent the individual buffered time ranges
for (i = 0; i < buffered.length; i++) {
start = buffered.start(i),
end = buffered.end(i),
part = children[i];
if (!part) {
part = this.el_.appendChild(vjs.createEl())
};
// set the percent based on the width of the progress bar (bufferedEnd)
part.style.left = percentify(start, bufferedEnd);
part.style.width = percentify(end - start, bufferedEnd);
};
// remove unused buffered range elements
for (i = children.length; i > buffered.length; i--) {
this.el_.removeChild(children[i-1]);
}
};
/**
* Shows play progress
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.PlayProgressBar = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
}
});
vjs.PlayProgressBar.prototype.createEl = function(){
return vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-play-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>'
});
};
/**
* The Seek Handle shows the current position of the playhead during playback,
* and can be dragged to adjust the playhead.
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.SeekHandle = vjs.SliderHandle.extend({
init: function(player, options) {
vjs.SliderHandle.call(this, player, options);
player.on('timeupdate', vjs.bind(this, this.updateContent));
}
});
/**
* The default value for the handle content, which may be read by screen readers
*
* @type {String}
* @private
*/
vjs.SeekHandle.prototype.defaultValue = '00:00';
/** @inheritDoc */
vjs.SeekHandle.prototype.createEl = function() {
return vjs.SliderHandle.prototype.createEl.call(this, 'div', {
className: 'vjs-seek-handle',
'aria-live': 'off'
});
};
vjs.SeekHandle.prototype.updateContent = function() {
var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime();
this.el_.innerHTML = '<span class="vjs-control-text">' + vjs.formatTime(time, this.player_.duration()) + '</span>';
};
/**
* The component for controlling the volume level
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.VolumeControl = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
// hide volume controls when they're not supported by the current tech
if (player.tech && player.tech['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
}
player.on('loadstart', vjs.bind(this, function(){
if (player.tech['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
}));
}
});
vjs.VolumeControl.prototype.options_ = {
children: {
'volumeBar': {}
}
};
vjs.VolumeControl.prototype.createEl = function(){
return vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-control vjs-control'
});
};
/**
* The bar that contains the volume level and can be clicked on to adjust the level
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.VolumeBar = vjs.Slider.extend({
/** @constructor */
init: function(player, options){
vjs.Slider.call(this, player, options);
player.on('volumechange', vjs.bind(this, this.updateARIAAttributes));
player.ready(vjs.bind(this, this.updateARIAAttributes));
}
});
vjs.VolumeBar.prototype.updateARIAAttributes = function(){
// Current value of volume bar as a percentage
this.el_.setAttribute('aria-valuenow',vjs.round(this.player_.volume()*100, 2));
this.el_.setAttribute('aria-valuetext',vjs.round(this.player_.volume()*100, 2)+'%');
};
vjs.VolumeBar.prototype.options_ = {
children: {
'volumeLevel': {},
'volumeHandle': {}
},
'barName': 'volumeLevel',
'handleName': 'volumeHandle'
};
vjs.VolumeBar.prototype.playerEvent = 'volumechange';
vjs.VolumeBar.prototype.createEl = function(){
return vjs.Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-bar',
'aria-label': 'volume level'
});
};
vjs.VolumeBar.prototype.onMouseMove = function(event) {
if (this.player_.muted()) {
this.player_.muted(false);
}
this.player_.volume(this.calculateDistance(event));
};
vjs.VolumeBar.prototype.getPercent = function(){
if (this.player_.muted()) {
return 0;
} else {
return this.player_.volume();
}
};
vjs.VolumeBar.prototype.stepForward = function(){
this.player_.volume(this.player_.volume() + 0.1);
};
vjs.VolumeBar.prototype.stepBack = function(){
this.player_.volume(this.player_.volume() - 0.1);
};
/**
* Shows volume level
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.VolumeLevel = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
}
});
vjs.VolumeLevel.prototype.createEl = function(){
return vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-level',
innerHTML: '<span class="vjs-control-text"></span>'
});
};
/**
* The volume handle can be dragged to adjust the volume level
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.VolumeHandle = vjs.SliderHandle.extend();
vjs.VolumeHandle.prototype.defaultValue = '00:00';
/** @inheritDoc */
vjs.VolumeHandle.prototype.createEl = function(){
return vjs.SliderHandle.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-handle'
});
};
/**
* A button component for muting the audio
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.MuteToggle = vjs.Button.extend({
/** @constructor */
init: function(player, options){
vjs.Button.call(this, player, options);
player.on('volumechange', vjs.bind(this, this.update));
// hide mute toggle if the current tech doesn't support volume control
if (player.tech && player.tech['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
}
player.on('loadstart', vjs.bind(this, function(){
if (player.tech['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
}));
}
});
vjs.MuteToggle.prototype.createEl = function(){
return vjs.Button.prototype.createEl.call(this, 'div', {
className: 'vjs-mute-control vjs-control',
innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>'
});
};
vjs.MuteToggle.prototype.onClick = function(){
this.player_.muted( this.player_.muted() ? false : true );
};
vjs.MuteToggle.prototype.update = function(){
var vol = this.player_.volume(),
level = 3;
if (vol === 0 || this.player_.muted()) {
level = 0;
} else if (vol < 0.33) {
level = 1;
} else if (vol < 0.67) {
level = 2;
}
// Don't rewrite the button text if the actual text doesn't change.
// This causes unnecessary and confusing information for screen reader users.
// This check is needed because this function gets called every time the volume level is changed.
if(this.player_.muted()){
if(this.el_.children[0].children[0].innerHTML!=this.localize('Unmute')){
this.el_.children[0].children[0].innerHTML = this.localize('Unmute'); // change the button text to "Unmute"
}
} else {
if(this.el_.children[0].children[0].innerHTML!=this.localize('Mute')){
this.el_.children[0].children[0].innerHTML = this.localize('Mute'); // change the button text to "Mute"
}
}
/* TODO improve muted icon classes */
for (var i = 0; i < 4; i++) {
vjs.removeClass(this.el_, 'vjs-vol-'+i);
}
vjs.addClass(this.el_, 'vjs-vol-'+level);
};
/**
* Menu button with a popup for showing the volume slider.
* @constructor
*/
vjs.VolumeMenuButton = vjs.MenuButton.extend({
/** @constructor */
init: function(player, options){
vjs.MenuButton.call(this, player, options);
// Same listeners as MuteToggle
player.on('volumechange', vjs.bind(this, this.update));
// hide mute toggle if the current tech doesn't support volume control
if (player.tech && player.tech['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
}
player.on('loadstart', vjs.bind(this, function(){
if (player.tech['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
}));
this.addClass('vjs-menu-button');
}
});
vjs.VolumeMenuButton.prototype.createMenu = function(){
var menu = new vjs.Menu(this.player_, {
contentElType: 'div'
});
var vc = new vjs.VolumeBar(this.player_, vjs.obj.merge({'vertical': true}, this.options_.volumeBar));
menu.addChild(vc);
return menu;
};
vjs.VolumeMenuButton.prototype.onClick = function(){
vjs.MuteToggle.prototype.onClick.call(this);
vjs.MenuButton.prototype.onClick.call(this);
};
vjs.VolumeMenuButton.prototype.createEl = function(){
return vjs.Button.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-menu-button vjs-menu-button vjs-control',
innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>'
});
};
vjs.VolumeMenuButton.prototype.update = vjs.MuteToggle.prototype.update;
/**
* The component for controlling the playback rate
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.PlaybackRateMenuButton = vjs.MenuButton.extend({
/** @constructor */
init: function(player, options){
vjs.MenuButton.call(this, player, options);
this.updateVisibility();
this.updateLabel();
player.on('loadstart', vjs.bind(this, this.updateVisibility));
player.on('ratechange', vjs.bind(this, this.updateLabel));
}
});
vjs.PlaybackRateMenuButton.prototype.createEl = function(){
var el = vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-playback-rate vjs-menu-button vjs-control',
innerHTML: '<div class="vjs-control-content"><span class="vjs-control-text">' + this.localize('Playback Rate') + '</span></div>'
});
this.labelEl_ = vjs.createEl('div', {
className: 'vjs-playback-rate-value',
innerHTML: 1.0
});
el.appendChild(this.labelEl_);
return el;
};
// Menu creation
vjs.PlaybackRateMenuButton.prototype.createMenu = function(){
var menu = new vjs.Menu(this.player());
var rates = this.player().options()['playbackRates'];
if (rates) {
for (var i = rates.length - 1; i >= 0; i--) {
menu.addChild(
new vjs.PlaybackRateMenuItem(this.player(), { 'rate': rates[i] + 'x'})
);
};
}
return menu;
};
vjs.PlaybackRateMenuButton.prototype.updateARIAAttributes = function(){
// Current playback rate
this.el().setAttribute('aria-valuenow', this.player().playbackRate());
};
vjs.PlaybackRateMenuButton.prototype.onClick = function(){
// select next rate option
var currentRate = this.player().playbackRate();
var rates = this.player().options()['playbackRates'];
// this will select first one if the last one currently selected
var newRate = rates[0];
for (var i = 0; i <rates.length ; i++) {
if (rates[i] > currentRate) {
newRate = rates[i];
break;
}
};
this.player().playbackRate(newRate);
};
vjs.PlaybackRateMenuButton.prototype.playbackRateSupported = function(){
return this.player().tech
&& this.player().tech['featuresPlaybackRate']
&& this.player().options()['playbackRates']
&& this.player().options()['playbackRates'].length > 0
;
};
/**
* Hide playback rate controls when they're no playback rate options to select
*/
vjs.PlaybackRateMenuButton.prototype.updateVisibility = function(){
if (this.playbackRateSupported()) {
this.removeClass('vjs-hidden');
} else {
this.addClass('vjs-hidden');
}
};
/**
* Update button label when rate changed
*/
vjs.PlaybackRateMenuButton.prototype.updateLabel = function(){
if (this.playbackRateSupported()) {
this.labelEl_.innerHTML = this.player().playbackRate() + 'x';
}
};
/**
* The specific menu item type for selecting a playback rate
*
* @constructor
*/
vjs.PlaybackRateMenuItem = vjs.MenuItem.extend({
contentElType: 'button',
/** @constructor */
init: function(player, options){
var label = this.label = options['rate'];
var rate = this.rate = parseFloat(label, 10);
// Modify options for parent MenuItem class's init.
options['label'] = label;
options['selected'] = rate === 1;
vjs.MenuItem.call(this, player, options);
this.player().on('ratechange', vjs.bind(this, this.update));
}
});
vjs.PlaybackRateMenuItem.prototype.onClick = function(){
vjs.MenuItem.prototype.onClick.call(this);
this.player().playbackRate(this.rate);
};
vjs.PlaybackRateMenuItem.prototype.update = function(){
this.selected(this.player().playbackRate() == this.rate);
};
/* Poster Image
================================================================================ */
/**
* The component that handles showing the poster image.
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.PosterImage = vjs.Button.extend({
/** @constructor */
init: function(player, options){
vjs.Button.call(this, player, options);
if (player.poster()) {
this.src(player.poster());
}
if (!player.poster() || !player.controls()) {
this.hide();
}
player.on('posterchange', vjs.bind(this, function(){
this.src(player.poster());
}));
player.on('play', vjs.bind(this, this.hide));
}
});
// use the test el to check for backgroundSize style support
var _backgroundSizeSupported = 'backgroundSize' in vjs.TEST_VID.style;
vjs.PosterImage.prototype.createEl = function(){
var el = vjs.createEl('div', {
className: 'vjs-poster',
// Don't want poster to be tabbable.
tabIndex: -1
});
if (!_backgroundSizeSupported) {
// setup an img element as a fallback for IE8
el.appendChild(vjs.createEl('img'));
}
return el;
};
vjs.PosterImage.prototype.src = function(url){
var el = this.el();
// getter
// can't think of a need for a getter here
// see #838 if on is needed in the future
// still don't want a getter to set src as undefined
if (url === undefined) {
return;
}
// setter
// To ensure the poster image resizes while maintaining its original aspect
// ratio, use a div with `background-size` when available. For browsers that
// do not support `background-size` (e.g. IE8), fall back on using a regular
// img element.
if (_backgroundSizeSupported) {
el.style.backgroundImage = 'url("' + url + '")';
} else {
el.firstChild.src = url;
}
};
vjs.PosterImage.prototype.onClick = function(){
// Only accept clicks when controls are enabled
if (this.player().controls()) {
this.player_.play();
}
};
/* Loading Spinner
================================================================================ */
/**
* Loading spinner for waiting events
* @param {vjs.Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
vjs.LoadingSpinner = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
// MOVING DISPLAY HANDLING TO CSS
// player.on('canplay', vjs.bind(this, this.hide));
// player.on('canplaythrough', vjs.bind(this, this.hide));
// player.on('playing', vjs.bind(this, this.hide));
// player.on('seeking', vjs.bind(this, this.show));
// in some browsers seeking does not trigger the 'playing' event,
// so we also need to trap 'seeked' if we are going to set a
// 'seeking' event
// player.on('seeked', vjs.bind(this, this.hide));
// player.on('ended', vjs.bind(this, this.hide));
// Not showing spinner on stalled any more. Browsers may stall and then not trigger any events that would remove the spinner.
// Checked in Chrome 16 and Safari 5.1.2. http://help.videojs.com/discussions/problems/883-why-is-the-download-progress-showing
// player.on('stalled', vjs.bind(this, this.show));
// player.on('waiting', vjs.bind(this, this.show));
}
});
vjs.LoadingSpinner.prototype.createEl = function(){
return vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-loading-spinner'
});
};
/* Big Play Button
================================================================================ */
/**
* Initial play button. Shows before the video has played. The hiding of the
* big play button is done via CSS and player states.
* @param {vjs.Player|Object} player
* @param {Object=} options
* @class
* @constructor
*/
vjs.BigPlayButton = vjs.Button.extend();
vjs.BigPlayButton.prototype.createEl = function(){
return vjs.Button.prototype.createEl.call(this, 'div', {
className: 'vjs-big-play-button',
innerHTML: '<span aria-hidden="true"></span>',
'aria-label': 'play video'
});
};
vjs.BigPlayButton.prototype.onClick = function(){
this.player_.play();
};
/**
* Display that an error has occurred making the video unplayable
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.ErrorDisplay = vjs.Component.extend({
init: function(player, options){
vjs.Component.call(this, player, options);
this.update();
player.on('error', vjs.bind(this, this.update));
}
});
vjs.ErrorDisplay.prototype.createEl = function(){
var el = vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-error-display'
});
this.contentEl_ = vjs.createEl('div');
el.appendChild(this.contentEl_);
return el;
};
vjs.ErrorDisplay.prototype.update = function(){
if (this.player().error()) {
this.contentEl_.innerHTML = this.localize(this.player().error().message);
}
};
/**
* @fileoverview Media Technology Controller - Base class for media playback
* technology controllers like Flash and HTML5
*/
/**
* Base class for media (HTML5 Video, Flash) controllers
* @param {vjs.Player|Object} player Central player instance
* @param {Object=} options Options object
* @constructor
*/
vjs.MediaTechController = vjs.Component.extend({
/** @constructor */
init: function(player, options, ready){
options = options || {};
// we don't want the tech to report user activity automatically.
// This is done manually in addControlsListeners
options.reportTouchActivity = false;
vjs.Component.call(this, player, options, ready);
// Manually track progress in cases where the browser/flash player doesn't report it.
if (!this['featuresProgressEvents']) {
this.manualProgressOn();
}
// Manually track timeudpates in cases where the browser/flash player doesn't report it.
if (!this['featuresTimeupdateEvents']) {
this.manualTimeUpdatesOn();
}
this.initControlsListeners();
}
});
/**
* Set up click and touch listeners for the playback element
* On desktops, a click on the video itself will toggle playback,
* on a mobile device a click on the video toggles controls.
* (toggling controls is done by toggling the user state between active and
* inactive)
*
* A tap can signal that a user has become active, or has become inactive
* e.g. a quick tap on an iPhone movie should reveal the controls. Another
* quick tap should hide them again (signaling the user is in an inactive
* viewing state)
*
* In addition to this, we still want the user to be considered inactive after
* a few seconds of inactivity.
*
* Note: the only part of iOS interaction we can't mimic with this setup
* is a touch and hold on the video element counting as activity in order to
* keep the controls showing, but that shouldn't be an issue. A touch and hold on
* any controls will still keep the user active
*/
vjs.MediaTechController.prototype.initControlsListeners = function(){
var player, tech, activateControls, deactivateControls;
tech = this;
player = this.player();
var activateControls = function(){
if (player.controls() && !player.usingNativeControls()) {
tech.addControlsListeners();
}
};
deactivateControls = vjs.bind(tech, tech.removeControlsListeners);
// Set up event listeners once the tech is ready and has an element to apply
// listeners to
this.ready(activateControls);
player.on('controlsenabled', activateControls);
player.on('controlsdisabled', deactivateControls);
// if we're loading the playback object after it has started loading or playing the
// video (often with autoplay on) then the loadstart event has already fired and we
// need to fire it manually because many things rely on it.
// Long term we might consider how we would do this for other events like 'canplay'
// that may also have fired.
this.ready(function(){
if (this.networkState && this.networkState() > 0) {
this.player().trigger('loadstart');
}
});
};
vjs.MediaTechController.prototype.addControlsListeners = function(){
var userWasActive;
// Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do
// trigger mousedown/up.
// http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object
// Any touch events are set to block the mousedown event from happening
this.on('mousedown', this.onClick);
// If the controls were hidden we don't want that to change without a tap event
// so we'll check if the controls were already showing before reporting user
// activity
this.on('touchstart', function(event) {
userWasActive = this.player_.userActive();
});
this.on('touchmove', function(event) {
if (userWasActive){
this.player().reportUserActivity();
}
});
this.on('touchend', function(event) {
// Stop the mouse events from also happening
event.preventDefault();
});
// Turn on component tap events
this.emitTapEvents();
// The tap listener needs to come after the touchend listener because the tap
// listener cancels out any reportedUserActivity when setting userActive(false)
this.on('tap', this.onTap);
};
/**
* Remove the listeners used for click and tap controls. This is needed for
* toggling to controls disabled, where a tap/touch should do nothing.
*/
vjs.MediaTechController.prototype.removeControlsListeners = function(){
// We don't want to just use `this.off()` because there might be other needed
// listeners added by techs that extend this.
this.off('tap');
this.off('touchstart');
this.off('touchmove');
this.off('touchleave');
this.off('touchcancel');
this.off('touchend');
this.off('click');
this.off('mousedown');
};
/**
* Handle a click on the media element. By default will play/pause the media.
*/
vjs.MediaTechController.prototype.onClick = function(event){
// We're using mousedown to detect clicks thanks to Flash, but mousedown
// will also be triggered with right-clicks, so we need to prevent that
if (event.button !== 0) return;
// When controls are disabled a click should not toggle playback because
// the click is considered a control
if (this.player().controls()) {
if (this.player().paused()) {
this.player().play();
} else {
this.player().pause();
}
}
};
/**
* Handle a tap on the media element. By default it will toggle the user
* activity state, which hides and shows the controls.
*/
vjs.MediaTechController.prototype.onTap = function(){
this.player().userActive(!this.player().userActive());
};
/* Fallbacks for unsupported event types
================================================================================ */
// Manually trigger progress events based on changes to the buffered amount
// Many flash players and older HTML5 browsers don't send progress or progress-like events
vjs.MediaTechController.prototype.manualProgressOn = function(){
this.manualProgress = true;
// Trigger progress watching when a source begins loading
this.trackProgress();
};
vjs.MediaTechController.prototype.manualProgressOff = function(){
this.manualProgress = false;
this.stopTrackingProgress();
};
vjs.MediaTechController.prototype.trackProgress = function(){
this.progressInterval = setInterval(vjs.bind(this, function(){
// Don't trigger unless buffered amount is greater than last time
var bufferedPercent = this.player().bufferedPercent();
if (this.bufferedPercent_ != bufferedPercent) {
this.player().trigger('progress');
}
this.bufferedPercent_ = bufferedPercent;
if (bufferedPercent === 1) {
this.stopTrackingProgress();
}
}), 500);
};
vjs.MediaTechController.prototype.stopTrackingProgress = function(){ clearInterval(this.progressInterval); };
/*! Time Tracking -------------------------------------------------------------- */
vjs.MediaTechController.prototype.manualTimeUpdatesOn = function(){
this.manualTimeUpdates = true;
this.player().on('play', vjs.bind(this, this.trackCurrentTime));
this.player().on('pause', vjs.bind(this, this.stopTrackingCurrentTime));
// timeupdate is also called by .currentTime whenever current time is set
// Watch for native timeupdate event
this.one('timeupdate', function(){
// Update known progress support for this playback technology
this['featuresTimeupdateEvents'] = true;
// Turn off manual progress tracking
this.manualTimeUpdatesOff();
});
};
vjs.MediaTechController.prototype.manualTimeUpdatesOff = function(){
this.manualTimeUpdates = false;
this.stopTrackingCurrentTime();
this.off('play', this.trackCurrentTime);
this.off('pause', this.stopTrackingCurrentTime);
};
vjs.MediaTechController.prototype.trackCurrentTime = function(){
if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); }
this.currentTimeInterval = setInterval(vjs.bind(this, function(){
this.player().trigger('timeupdate');
}), 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
};
// Turn off play progress tracking (when paused or dragging)
vjs.MediaTechController.prototype.stopTrackingCurrentTime = function(){
clearInterval(this.currentTimeInterval);
// #1002 - if the video ends right before the next timeupdate would happen,
// the progress bar won't make it all the way to the end
this.player().trigger('timeupdate');
};
vjs.MediaTechController.prototype.dispose = function() {
// Turn off any manual progress or timeupdate tracking
if (this.manualProgress) { this.manualProgressOff(); }
if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); }
vjs.Component.prototype.dispose.call(this);
};
vjs.MediaTechController.prototype.setCurrentTime = function() {
// improve the accuracy of manual timeupdates
if (this.manualTimeUpdates) { this.player().trigger('timeupdate'); }
};
/**
* Provide a default setPoster method for techs
*
* Poster support for techs should be optional, so we don't want techs to
* break if they don't have a way to set a poster.
*/
vjs.MediaTechController.prototype.setPoster = function(){};
vjs.MediaTechController.prototype['featuresVolumeControl'] = true;
// Resizing plugins using request fullscreen reloads the plugin
vjs.MediaTechController.prototype['featuresFullscreenResize'] = false;
vjs.MediaTechController.prototype['featuresPlaybackRate'] = false;
// Optional events that we can manually mimic with timers
// currently not triggered by video-js-swf
vjs.MediaTechController.prototype['featuresProgressEvents'] = false;
vjs.MediaTechController.prototype['featuresTimeupdateEvents'] = false;
vjs.media = {};
/**
* @fileoverview HTML5 Media Controller - Wrapper for HTML5 Media API
*/
/**
* HTML5 Media Controller - Wrapper for HTML5 Media API
* @param {vjs.Player|Object} player
* @param {Object=} options
* @param {Function=} ready
* @constructor
*/
vjs.Html5 = vjs.MediaTechController.extend({
/** @constructor */
init: function(player, options, ready){
// volume cannot be changed from 1 on iOS
this['featuresVolumeControl'] = vjs.Html5.canControlVolume();
// just in case; or is it excessively...
this['featuresPlaybackRate'] = vjs.Html5.canControlPlaybackRate();
// In iOS, if you move a video element in the DOM, it breaks video playback.
this['movingMediaElementInDOM'] = !vjs.IS_IOS;
// HTML video is able to automatically resize when going to fullscreen
this['featuresFullscreenResize'] = true;
// HTML video supports progress events
this['featuresProgressEvents'] = true;
vjs.MediaTechController.call(this, player, options, ready);
this.setupTriggers();
var source = options['source'];
// set the source if one was provided
if (source && this.el_.currentSrc !== source.src) {
this.el_.src = source.src;
}
// Determine if native controls should be used
// Our goal should be to get the custom controls on mobile solid everywhere
// so we can remove this all together. Right now this will block custom
// controls on touch enabled laptops like the Chrome Pixel
if (vjs.TOUCH_ENABLED && player.options()['nativeControlsForTouch'] !== false) {
this.useNativeControls();
}
// Chrome and Safari both have issues with autoplay.
// In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work.
// In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays)
// This fixes both issues. Need to wait for API, so it updates displays correctly
player.ready(function(){
if (this.tag && this.options_['autoplay'] && this.paused()) {
delete this.tag['poster']; // Chrome Fix. Fixed in Chrome v16.
this.play();
}
});
this.triggerReady();
}
});
vjs.Html5.prototype.dispose = function(){
vjs.Html5.disposeMediaElement(this.el_);
vjs.MediaTechController.prototype.dispose.call(this);
};
vjs.Html5.prototype.createEl = function(){
var player = this.player_,
// If possible, reuse original tag for HTML5 playback technology element
el = player.tag,
newEl,
clone;
// Check if this browser supports moving the element into the box.
// On the iPhone video will break if you move the element,
// So we have to create a brand new element.
if (!el || this['movingMediaElementInDOM'] === false) {
// If the original tag is still there, clone and remove it.
if (el) {
clone = el.cloneNode(false);
vjs.Html5.disposeMediaElement(el);
el = clone;
player.tag = null;
} else {
el = vjs.createEl('video');
vjs.setElementAttributes(el,
vjs.obj.merge(player.tagAttributes || {}, {
id:player.id() + '_html5_api',
'class':'vjs-tech'
})
);
}
// associate the player with the new tag
el['player'] = player;
vjs.insertFirst(el, player.el());
}
// Update specific tag settings, in case they were overridden
var settingsAttrs = ['autoplay','preload','loop','muted'];
for (var i = settingsAttrs.length - 1; i >= 0; i--) {
var attr = settingsAttrs[i];
var overwriteAttrs = {};
if (typeof player.options_[attr] !== 'undefined') {
overwriteAttrs[attr] = player.options_[attr];
}
vjs.setElementAttributes(el, overwriteAttrs);
}
return el;
// jenniisawesome = true;
};
// Make video events trigger player events
// May seem verbose here, but makes other APIs possible.
// Triggers removed using this.off when disposed
vjs.Html5.prototype.setupTriggers = function(){
for (var i = vjs.Html5.Events.length - 1; i >= 0; i--) {
vjs.on(this.el_, vjs.Html5.Events[i], vjs.bind(this, this.eventHandler));
}
};
vjs.Html5.prototype.eventHandler = function(evt){
// In the case of an error on the video element, set the error prop
// on the player and let the player handle triggering the event. On
// some platforms, error events fire that do not cause the error
// property on the video element to be set. See #1465 for an example.
if (evt.type == 'error' && this.error()) {
this.player().error(this.error().code);
// in some cases we pass the event directly to the player
} else {
// No need for media events to bubble up.
evt.bubbles = false;
this.player().trigger(evt);
}
};
vjs.Html5.prototype.useNativeControls = function(){
var tech, player, controlsOn, controlsOff, cleanUp;
tech = this;
player = this.player();
// If the player controls are enabled turn on the native controls
tech.setControls(player.controls());
// Update the native controls when player controls state is updated
controlsOn = function(){
tech.setControls(true);
};
controlsOff = function(){
tech.setControls(false);
};
player.on('controlsenabled', controlsOn);
player.on('controlsdisabled', controlsOff);
// Clean up when not using native controls anymore
cleanUp = function(){
player.off('controlsenabled', controlsOn);
player.off('controlsdisabled', controlsOff);
};
tech.on('dispose', cleanUp);
player.on('usingcustomcontrols', cleanUp);
// Update the state of the player to using native controls
player.usingNativeControls(true);
};
vjs.Html5.prototype.play = function(){ this.el_.play(); };
vjs.Html5.prototype.pause = function(){ this.el_.pause(); };
vjs.Html5.prototype.paused = function(){ return this.el_.paused; };
vjs.Html5.prototype.currentTime = function(){ return this.el_.currentTime; };
vjs.Html5.prototype.setCurrentTime = function(seconds){
try {
this.el_.currentTime = seconds;
} catch(e) {
vjs.log(e, 'Video is not ready. (Video.js)');
// this.warning(VideoJS.warnings.videoNotReady);
}
};
vjs.Html5.prototype.duration = function(){ return this.el_.duration || 0; };
vjs.Html5.prototype.buffered = function(){ return this.el_.buffered; };
vjs.Html5.prototype.volume = function(){ return this.el_.volume; };
vjs.Html5.prototype.setVolume = function(percentAsDecimal){ this.el_.volume = percentAsDecimal; };
vjs.Html5.prototype.muted = function(){ return this.el_.muted; };
vjs.Html5.prototype.setMuted = function(muted){ this.el_.muted = muted; };
vjs.Html5.prototype.width = function(){ return this.el_.offsetWidth; };
vjs.Html5.prototype.height = function(){ return this.el_.offsetHeight; };
vjs.Html5.prototype.supportsFullScreen = function(){
if (typeof this.el_.webkitEnterFullScreen == 'function') {
// Seems to be broken in Chromium/Chrome && Safari in Leopard
if (/Android/.test(vjs.USER_AGENT) || !/Chrome|Mac OS X 10.5/.test(vjs.USER_AGENT)) {
return true;
}
}
return false;
};
vjs.Html5.prototype.enterFullScreen = function(){
var video = this.el_;
if (video.paused && video.networkState <= video.HAVE_METADATA) {
// attempt to prime the video element for programmatic access
// this isn't necessary on the desktop but shouldn't hurt
this.el_.play();
// playing and pausing synchronously during the transition to fullscreen
// can get iOS ~6.1 devices into a play/pause loop
setTimeout(function(){
video.pause();
video.webkitEnterFullScreen();
}, 0);
} else {
video.webkitEnterFullScreen();
}
};
vjs.Html5.prototype.exitFullScreen = function(){
this.el_.webkitExitFullScreen();
};
vjs.Html5.prototype.src = function(src) {
if (src === undefined) {
return this.el_.src;
} else {
this.el_.src = src;
}
};
vjs.Html5.prototype.load = function(){ this.el_.load(); };
vjs.Html5.prototype.currentSrc = function(){ return this.el_.currentSrc; };
vjs.Html5.prototype.poster = function(){ return this.el_.poster; };
vjs.Html5.prototype.setPoster = function(val){ this.el_.poster = val; };
vjs.Html5.prototype.preload = function(){ return this.el_.preload; };
vjs.Html5.prototype.setPreload = function(val){ this.el_.preload = val; };
vjs.Html5.prototype.autoplay = function(){ return this.el_.autoplay; };
vjs.Html5.prototype.setAutoplay = function(val){ this.el_.autoplay = val; };
vjs.Html5.prototype.controls = function(){ return this.el_.controls; };
vjs.Html5.prototype.setControls = function(val){ this.el_.controls = !!val; };
vjs.Html5.prototype.loop = function(){ return this.el_.loop; };
vjs.Html5.prototype.setLoop = function(val){ this.el_.loop = val; };
vjs.Html5.prototype.error = function(){ return this.el_.error; };
vjs.Html5.prototype.seeking = function(){ return this.el_.seeking; };
vjs.Html5.prototype.ended = function(){ return this.el_.ended; };
vjs.Html5.prototype.defaultMuted = function(){ return this.el_.defaultMuted; };
vjs.Html5.prototype.playbackRate = function(){ return this.el_.playbackRate; };
vjs.Html5.prototype.setPlaybackRate = function(val){ this.el_.playbackRate = val; };
vjs.Html5.prototype.networkState = function(){ return this.el_.networkState; };
/* HTML5 Support Testing ---------------------------------------------------- */
vjs.Html5.isSupported = function(){
// ie9 with no Media Player is a LIAR! (#984)
try {
vjs.TEST_VID['volume'] = 0.5;
} catch (e) {
return false;
}
return !!vjs.TEST_VID.canPlayType;
};
vjs.Html5.canPlaySource = function(srcObj){
// IE9 on Windows 7 without MediaPlayer throws an error here
// https://github.com/videojs/video.js/issues/519
try {
return !!vjs.TEST_VID.canPlayType(srcObj.type);
} catch(e) {
return '';
}
// TODO: Check Type
// If no Type, check ext
// Check Media Type
};
vjs.Html5.canControlVolume = function(){
var volume = vjs.TEST_VID.volume;
vjs.TEST_VID.volume = (volume / 2) + 0.1;
return volume !== vjs.TEST_VID.volume;
};
vjs.Html5.canControlPlaybackRate = function(){
var playbackRate = vjs.TEST_VID.playbackRate;
vjs.TEST_VID.playbackRate = (playbackRate / 2) + 0.1;
return playbackRate !== vjs.TEST_VID.playbackRate;
};
// HTML5 Feature detection and Device Fixes --------------------------------- //
(function() {
var canPlayType,
mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i,
mp4RE = /^video\/mp4/i;
vjs.Html5.patchCanPlayType = function() {
// Android 4.0 and above can play HLS to some extent but it reports being unable to do so
if (vjs.ANDROID_VERSION >= 4.0) {
if (!canPlayType) {
canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType;
}
vjs.TEST_VID.constructor.prototype.canPlayType = function(type) {
if (type && mpegurlRE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
}
// Override Android 2.2 and less canPlayType method which is broken
if (vjs.IS_OLD_ANDROID) {
if (!canPlayType) {
canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType;
}
vjs.TEST_VID.constructor.prototype.canPlayType = function(type){
if (type && mp4RE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
}
};
vjs.Html5.unpatchCanPlayType = function() {
var r = vjs.TEST_VID.constructor.prototype.canPlayType;
vjs.TEST_VID.constructor.prototype.canPlayType = canPlayType;
canPlayType = null;
return r;
};
// by default, patch the video element
vjs.Html5.patchCanPlayType();
})();
// List of all HTML5 events (various uses).
vjs.Html5.Events = 'loadstart,suspend,abort,error,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,playing,waiting,seeking,seeked,ended,durationchange,timeupdate,progress,play,pause,ratechange,volumechange'.split(',');
vjs.Html5.disposeMediaElement = function(el){
if (!el) { return; }
el['player'] = null;
if (el.parentNode) {
el.parentNode.removeChild(el);
}
// remove any child track or source nodes to prevent their loading
while(el.hasChildNodes()) {
el.removeChild(el.firstChild);
}
// remove any src reference. not setting `src=''` because that causes a warning
// in firefox
el.removeAttribute('src');
// force the media element to update its loading state by calling load()
// however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
if (typeof el.load === 'function') {
// wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
(function() {
try {
el.load();
} catch (e) {
// not supported
}
})();
}
};
/**
* @fileoverview VideoJS-SWF - Custom Flash Player with HTML5-ish API
* https://github.com/zencoder/video-js-swf
* Not using setupTriggers. Using global onEvent func to distribute events
*/
/**
* Flash Media Controller - Wrapper for fallback SWF API
*
* @param {vjs.Player} player
* @param {Object=} options
* @param {Function=} ready
* @constructor
*/
vjs.Flash = vjs.MediaTechController.extend({
/** @constructor */
init: function(player, options, ready){
vjs.MediaTechController.call(this, player, options, ready);
var source = options['source'],
// Which element to embed in
parentEl = options['parentEl'],
// Create a temporary element to be replaced by swf object
placeHolder = this.el_ = vjs.createEl('div', { id: player.id() + '_temp_flash' }),
// Generate ID for swf object
objId = player.id()+'_flash_api',
// Store player options in local var for optimization
// TODO: switch to using player methods instead of options
// e.g. player.autoplay();
playerOptions = player.options_,
// Merge default flashvars with ones passed in to init
flashVars = vjs.obj.merge({
// SWF Callback Functions
'readyFunction': 'videojs.Flash.onReady',
'eventProxyFunction': 'videojs.Flash.onEvent',
'errorEventProxyFunction': 'videojs.Flash.onError',
// Player Settings
'autoplay': playerOptions.autoplay,
'preload': playerOptions.preload,
'loop': playerOptions.loop,
'muted': playerOptions.muted
}, options['flashVars']),
// Merge default parames with ones passed in
params = vjs.obj.merge({
'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance
'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading
}, options['params']),
// Merge default attributes with ones passed in
attributes = vjs.obj.merge({
'id': objId,
'name': objId, // Both ID and Name needed or swf to identifty itself
'class': 'vjs-tech'
}, options['attributes'])
;
// If source was supplied pass as a flash var.
if (source) {
if (source.type && vjs.Flash.isStreamingType(source.type)) {
var parts = vjs.Flash.streamToParts(source.src);
flashVars['rtmpConnection'] = encodeURIComponent(parts.connection);
flashVars['rtmpStream'] = encodeURIComponent(parts.stream);
}
else {
flashVars['src'] = encodeURIComponent(vjs.getAbsoluteURL(source.src));
}
}
// Add placeholder to player div
vjs.insertFirst(placeHolder, parentEl);
// Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers
// This allows resetting the playhead when we catch the reload
if (options['startTime']) {
this.ready(function(){
this.load();
this.play();
this['currentTime'](options['startTime']);
});
}
// firefox doesn't bubble mousemove events to parent. videojs/video-js-swf#37
// bugzilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=836786
if (vjs.IS_FIREFOX) {
this.ready(function(){
vjs.on(this.el(), 'mousemove', vjs.bind(this, function(){
// since it's a custom event, don't bubble higher than the player
this.player().trigger({ 'type':'mousemove', 'bubbles': false });
}));
});
}
// native click events on the SWF aren't triggered on IE11, Win8.1RT
// use stageclick events triggered from inside the SWF instead
player.on('stageclick', player.reportUserActivity);
this.el_ = vjs.Flash.embed(options['swf'], placeHolder, flashVars, params, attributes);
}
});
vjs.Flash.prototype.dispose = function(){
vjs.MediaTechController.prototype.dispose.call(this);
};
vjs.Flash.prototype.play = function(){
this.el_.vjs_play();
};
vjs.Flash.prototype.pause = function(){
this.el_.vjs_pause();
};
vjs.Flash.prototype.src = function(src){
if (src === undefined) {
return this['currentSrc']();
}
if (vjs.Flash.isStreamingSrc(src)) {
src = vjs.Flash.streamToParts(src);
this.setRtmpConnection(src.connection);
this.setRtmpStream(src.stream);
} else {
// Make sure source URL is abosolute.
src = vjs.getAbsoluteURL(src);
this.el_.vjs_src(src);
}
// Currently the SWF doesn't autoplay if you load a source later.
// e.g. Load player w/ no source, wait 2s, set src.
if (this.player_.autoplay()) {
var tech = this;
setTimeout(function(){ tech.play(); }, 0);
}
};
vjs.Flash.prototype['setCurrentTime'] = function(time){
this.lastSeekTarget_ = time;
this.el_.vjs_setProperty('currentTime', time);
vjs.MediaTechController.prototype.setCurrentTime.call(this);
};
vjs.Flash.prototype['currentTime'] = function(time){
// when seeking make the reported time keep up with the requested time
// by reading the time we're seeking to
if (this.seeking()) {
return this.lastSeekTarget_ || 0;
}
return this.el_.vjs_getProperty('currentTime');
};
vjs.Flash.prototype['currentSrc'] = function(){
var src = this.el_.vjs_getProperty('currentSrc');
// no src, check and see if RTMP
if (src == null) {
var connection = this['rtmpConnection'](),
stream = this['rtmpStream']();
if (connection && stream) {
src = vjs.Flash.streamFromParts(connection, stream);
}
}
return src;
};
vjs.Flash.prototype.load = function(){
this.el_.vjs_load();
};
vjs.Flash.prototype.poster = function(){
this.el_.vjs_getProperty('poster');
};
vjs.Flash.prototype['setPoster'] = function(){
// poster images are not handled by the Flash tech so make this a no-op
};
vjs.Flash.prototype.buffered = function(){
return vjs.createTimeRange(0, this.el_.vjs_getProperty('buffered'));
};
vjs.Flash.prototype.supportsFullScreen = function(){
return false; // Flash does not allow fullscreen through javascript
};
vjs.Flash.prototype.enterFullScreen = function(){
return false;
};
(function(){
// Create setters and getters for attributes
var api = vjs.Flash.prototype,
readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','),
readOnly = 'error,networkState,readyState,seeking,initialTime,duration,startOffsetTime,paused,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight,textTracks'.split(','),
// Overridden: buffered, currentTime, currentSrc
i;
function createSetter(attr){
var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1);
api['set'+attrUpper] = function(val){ return this.el_.vjs_setProperty(attr, val); };
};
function createGetter(attr) {
api[attr] = function(){ return this.el_.vjs_getProperty(attr); };
};
// Create getter and setters for all read/write attributes
for (i = 0; i < readWrite.length; i++) {
createGetter(readWrite[i]);
createSetter(readWrite[i]);
}
// Create getters for read-only attributes
for (i = 0; i < readOnly.length; i++) {
createGetter(readOnly[i]);
}
})();
/* Flash Support Testing -------------------------------------------------------- */
vjs.Flash.isSupported = function(){
return vjs.Flash.version()[0] >= 10;
// return swfobject.hasFlashPlayerVersion('10');
};
vjs.Flash.canPlaySource = function(srcObj){
var type;
if (!srcObj.type) {
return '';
}
type = srcObj.type.replace(/;.*/,'').toLowerCase();
if (type in vjs.Flash.formats || type in vjs.Flash.streamingFormats) {
return 'maybe';
}
};
vjs.Flash.formats = {
'video/flv': 'FLV',
'video/x-flv': 'FLV',
'video/mp4': 'MP4',
'video/m4v': 'MP4'
};
vjs.Flash.streamingFormats = {
'rtmp/mp4': 'MP4',
'rtmp/flv': 'FLV'
};
vjs.Flash['onReady'] = function(currSwf){
var el, player;
el = vjs.el(currSwf);
// get player from the player div property
player = el && el.parentNode && el.parentNode['player'];
// if there is no el or player then the tech has been disposed
// and the tech element was removed from the player div
if (player) {
// reference player on tech element
el['player'] = player;
// check that the flash object is really ready
vjs.Flash['checkReady'](player.tech);
}
};
// The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object.
// If it's not ready, we set a timeout to check again shortly.
vjs.Flash['checkReady'] = function(tech){
// stop worrying if the tech has been disposed
if (!tech.el()) {
return;
}
// check if API property exists
if (tech.el().vjs_getProperty) {
// tell tech it's ready
tech.triggerReady();
} else {
// wait longer
setTimeout(function(){
vjs.Flash['checkReady'](tech);
}, 50);
}
};
// Trigger events from the swf on the player
vjs.Flash['onEvent'] = function(swfID, eventName){
var player = vjs.el(swfID)['player'];
player.trigger(eventName);
};
// Log errors from the swf
vjs.Flash['onError'] = function(swfID, err){
var player = vjs.el(swfID)['player'];
var msg = 'FLASH: '+err;
if (err == 'srcnotfound') {
player.error({ code: 4, message: msg });
// errors we haven't categorized into the media errors
} else {
player.error(msg);
}
};
// Flash Version Check
vjs.Flash.version = function(){
var version = '0,0,0';
// IE
try {
version = new window.ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
// other browsers
} catch(e) {
try {
if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin){
version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
}
} catch(err) {}
}
return version.split(',');
};
// Flash embedding method. Only used in non-iframe mode
vjs.Flash.embed = function(swf, placeHolder, flashVars, params, attributes){
var code = vjs.Flash.getEmbedCode(swf, flashVars, params, attributes),
// Get element by embedding code and retrieving created element
obj = vjs.createEl('div', { innerHTML: code }).childNodes[0],
par = placeHolder.parentNode
;
placeHolder.parentNode.replaceChild(obj, placeHolder);
// IE6 seems to have an issue where it won't initialize the swf object after injecting it.
// This is a dumb fix
var newObj = par.childNodes[0];
setTimeout(function(){
newObj.style.display = 'block';
}, 1000);
return obj;
};
vjs.Flash.getEmbedCode = function(swf, flashVars, params, attributes){
var objTag = '<object type="application/x-shockwave-flash"',
flashVarsString = '',
paramsString = '',
attrsString = '';
// Convert flash vars to string
if (flashVars) {
vjs.obj.each(flashVars, function(key, val){
flashVarsString += (key + '=' + val + '&');
});
}
// Add swf, flashVars, and other default params
params = vjs.obj.merge({
'movie': swf,
'flashvars': flashVarsString,
'allowScriptAccess': 'always', // Required to talk to swf
'allowNetworking': 'all' // All should be default, but having security issues.
}, params);
// Create param tags string
vjs.obj.each(params, function(key, val){
paramsString += '<param name="'+key+'" value="'+val+'" />';
});
attributes = vjs.obj.merge({
// Add swf to attributes (need both for IE and Others to work)
'data': swf,
// Default to 100% width/height
'width': '100%',
'height': '100%'
}, attributes);
// Create Attributes string
vjs.obj.each(attributes, function(key, val){
attrsString += (key + '="' + val + '" ');
});
return objTag + attrsString + '>' + paramsString + '</object>';
};
vjs.Flash.streamFromParts = function(connection, stream) {
return connection + '&' + stream;
};
vjs.Flash.streamToParts = function(src) {
var parts = {
connection: '',
stream: ''
};
if (! src) {
return parts;
}
// Look for the normal URL separator we expect, '&'.
// If found, we split the URL into two pieces around the
// first '&'.
var connEnd = src.indexOf('&');
var streamBegin;
if (connEnd !== -1) {
streamBegin = connEnd + 1;
}
else {
// If there's not a '&', we use the last '/' as the delimiter.
connEnd = streamBegin = src.lastIndexOf('/') + 1;
if (connEnd === 0) {
// really, there's not a '/'?
connEnd = streamBegin = src.length;
}
}
parts.connection = src.substring(0, connEnd);
parts.stream = src.substring(streamBegin, src.length);
return parts;
};
vjs.Flash.isStreamingType = function(srcType) {
return srcType in vjs.Flash.streamingFormats;
};
// RTMP has four variations, any string starting
// with one of these protocols should be valid
vjs.Flash.RTMP_RE = /^rtmp[set]?:\/\//i;
vjs.Flash.isStreamingSrc = function(src) {
return vjs.Flash.RTMP_RE.test(src);
};
/**
* The Media Loader is the component that decides which playback technology to load
* when the player is initialized.
*
* @constructor
*/
vjs.MediaLoader = vjs.Component.extend({
/** @constructor */
init: function(player, options, ready){
vjs.Component.call(this, player, options, ready);
// If there are no sources when the player is initialized,
// load the first supported playback technology.
if (!player.options_['sources'] || player.options_['sources'].length === 0) {
for (var i=0,j=player.options_['techOrder']; i<j.length; i++) {
var techName = vjs.capitalize(j[i]),
tech = window['videojs'][techName];
// Check if the browser supports this technology
if (tech && tech.isSupported()) {
player.loadTech(techName);
break;
}
}
} else {
// // Loop through playback technologies (HTML5, Flash) and check for support.
// // Then load the best source.
// // A few assumptions here:
// // All playback technologies respect preload false.
player.src(player.options_['sources']);
}
}
});
/**
* @fileoverview Text Tracks
* Text tracks are tracks of timed text events.
* Captions - text displayed over the video for the hearing impared
* Subtitles - text displayed over the video for those who don't understand langauge in the video
* Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video
* Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device
*/
// Player Additions - Functions add to the player object for easier access to tracks
/**
* List of associated text tracks
* @type {Array}
* @private
*/
vjs.Player.prototype.textTracks_;
/**
* Get an array of associated text tracks. captions, subtitles, chapters, descriptions
* http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
* @return {Array} Array of track objects
* @private
*/
vjs.Player.prototype.textTracks = function(){
this.textTracks_ = this.textTracks_ || [];
return this.textTracks_;
};
/**
* Add a text track
* In addition to the W3C settings we allow adding additional info through options.
* http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
* @param {String} kind Captions, subtitles, chapters, descriptions, or metadata
* @param {String=} label Optional label
* @param {String=} language Optional language
* @param {Object=} options Additional track options, like src
* @private
*/
vjs.Player.prototype.addTextTrack = function(kind, label, language, options){
var tracks = this.textTracks_ = this.textTracks_ || [];
options = options || {};
options['kind'] = kind;
options['label'] = label;
options['language'] = language;
// HTML5 Spec says default to subtitles.
// Uppercase first letter to match class names
var Kind = vjs.capitalize(kind || 'subtitles');
// Create correct texttrack class. CaptionsTrack, etc.
var track = new window['videojs'][Kind + 'Track'](this, options);
tracks.push(track);
// If track.dflt() is set, start showing immediately
// TODO: Add a process to deterime the best track to show for the specific kind
// Incase there are mulitple defaulted tracks of the same kind
// Or the user has a set preference of a specific language that should override the default
// Note: The setTimeout is a workaround because with the html5 tech, the player is 'ready'
// before it's child components (including the textTrackDisplay) have finished loading.
if (track.dflt()) {
this.ready(function(){
setTimeout(function(){
track.player().showTextTrack(track.id());
}, 0);
});
}
return track;
};
/**
* Add an array of text tracks. captions, subtitles, chapters, descriptions
* Track objects will be stored in the player.textTracks() array
* @param {Array} trackList Array of track elements or objects (fake track elements)
* @private
*/
vjs.Player.prototype.addTextTracks = function(trackList){
var trackObj;
for (var i = 0; i < trackList.length; i++) {
trackObj = trackList[i];
this.addTextTrack(trackObj['kind'], trackObj['label'], trackObj['language'], trackObj);
}
return this;
};
// Show a text track
// disableSameKind: disable all other tracks of the same kind. Value should be a track kind (captions, etc.)
vjs.Player.prototype.showTextTrack = function(id, disableSameKind){
var tracks = this.textTracks_,
i = 0,
j = tracks.length,
track, showTrack, kind;
// Find Track with same ID
for (;i<j;i++) {
track = tracks[i];
if (track.id() === id) {
track.show();
showTrack = track;
// Disable tracks of the same kind
} else if (disableSameKind && track.kind() == disableSameKind && track.mode() > 0) {
track.disable();
}
}
// Get track kind from shown track or disableSameKind
kind = (showTrack) ? showTrack.kind() : ((disableSameKind) ? disableSameKind : false);
// Trigger trackchange event, captionstrackchange, subtitlestrackchange, etc.
if (kind) {
this.trigger(kind+'trackchange');
}
return this;
};
/**
* The base class for all text tracks
*
* Handles the parsing, hiding, and showing of text track cues
*
* @param {vjs.Player|Object} player
* @param {Object=} options
* @constructor
*/
vjs.TextTrack = vjs.Component.extend({
/** @constructor */
init: function(player, options){
vjs.Component.call(this, player, options);
// Apply track info to track object
// Options will often be a track element
// Build ID if one doesn't exist
this.id_ = options['id'] || ('vjs_' + options['kind'] + '_' + options['language'] + '_' + vjs.guid++);
this.src_ = options['src'];
// 'default' is a reserved keyword in js so we use an abbreviated version
this.dflt_ = options['default'] || options['dflt'];
this.title_ = options['title'];
this.language_ = options['srclang'];
this.label_ = options['label'];
this.cues_ = [];
this.activeCues_ = [];
this.readyState_ = 0;
this.mode_ = 0;
this.player_.on('fullscreenchange', vjs.bind(this, this.adjustFontSize));
}
});
/**
* Track kind value. Captions, subtitles, etc.
* @private
*/
vjs.TextTrack.prototype.kind_;
/**
* Get the track kind value
* @return {String}
*/
vjs.TextTrack.prototype.kind = function(){
return this.kind_;
};
/**
* Track src value
* @private
*/
vjs.TextTrack.prototype.src_;
/**
* Get the track src value
* @return {String}
*/
vjs.TextTrack.prototype.src = function(){
return this.src_;
};
/**
* Track default value
* If default is used, subtitles/captions to start showing
* @private
*/
vjs.TextTrack.prototype.dflt_;
/**
* Get the track default value. ('default' is a reserved keyword)
* @return {Boolean}
*/
vjs.TextTrack.prototype.dflt = function(){
return this.dflt_;
};
/**
* Track title value
* @private
*/
vjs.TextTrack.prototype.title_;
/**
* Get the track title value
* @return {String}
*/
vjs.TextTrack.prototype.title = function(){
return this.title_;
};
/**
* Language - two letter string to represent track language, e.g. 'en' for English
* Spec def: readonly attribute DOMString language;
* @private
*/
vjs.TextTrack.prototype.language_;
/**
* Get the track language value
* @return {String}
*/
vjs.TextTrack.prototype.language = function(){
return this.language_;
};
/**
* Track label e.g. 'English'
* Spec def: readonly attribute DOMString label;
* @private
*/
vjs.TextTrack.prototype.label_;
/**
* Get the track label value
* @return {String}
*/
vjs.TextTrack.prototype.label = function(){
return this.label_;
};
/**
* All cues of the track. Cues have a startTime, endTime, text, and other properties.
* Spec def: readonly attribute TextTrackCueList cues;
* @private
*/
vjs.TextTrack.prototype.cues_;
/**
* Get the track cues
* @return {Array}
*/
vjs.TextTrack.prototype.cues = function(){
return this.cues_;
};
/**
* ActiveCues is all cues that are currently showing
* Spec def: readonly attribute TextTrackCueList activeCues;
* @private
*/
vjs.TextTrack.prototype.activeCues_;
/**
* Get the track active cues
* @return {Array}
*/
vjs.TextTrack.prototype.activeCues = function(){
return this.activeCues_;
};
/**
* ReadyState describes if the text file has been loaded
* const unsigned short NONE = 0;
* const unsigned short LOADING = 1;
* const unsigned short LOADED = 2;
* const unsigned short ERROR = 3;
* readonly attribute unsigned short readyState;
* @private
*/
vjs.TextTrack.prototype.readyState_;
/**
* Get the track readyState
* @return {Number}
*/
vjs.TextTrack.prototype.readyState = function(){
return this.readyState_;
};
/**
* Mode describes if the track is showing, hidden, or disabled
* const unsigned short OFF = 0;
* const unsigned short HIDDEN = 1; (still triggering cuechange events, but not visible)
* const unsigned short SHOWING = 2;
* attribute unsigned short mode;
* @private
*/
vjs.TextTrack.prototype.mode_;
/**
* Get the track mode
* @return {Number}
*/
vjs.TextTrack.prototype.mode = function(){
return this.mode_;
};
/**
* Change the font size of the text track to make it larger when playing in fullscreen mode
* and restore it to its normal size when not in fullscreen mode.
*/
vjs.TextTrack.prototype.adjustFontSize = function(){
if (this.player_.isFullscreen()) {
// Scale the font by the same factor as increasing the video width to the full screen window width.
// Additionally, multiply that factor by 1.4, which is the default font size for
// the caption track (from the CSS)
this.el_.style.fontSize = screen.width / this.player_.width() * 1.4 * 100 + '%';
} else {
// Change the font size of the text track back to its original non-fullscreen size
this.el_.style.fontSize = '';
}
};
/**
* Create basic div to hold cue text
* @return {Element}
*/
vjs.TextTrack.prototype.createEl = function(){
return vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-' + this.kind_ + ' vjs-text-track'
});
};
/**
* Show: Mode Showing (2)
* Indicates that the text track is active. If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily.
* The user agent is maintaining a list of which cues are active, and events are being fired accordingly.
* In addition, for text tracks whose kind is subtitles or captions, the cues are being displayed over the video as appropriate;
* for text tracks whose kind is descriptions, the user agent is making the cues available to the user in a non-visual fashion;
* and for text tracks whose kind is chapters, the user agent is making available to the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue.
* The showing by default state is used in conjunction with the default attribute on track elements to indicate that the text track was enabled due to that attribute.
* This allows the user agent to override the state if a later track is discovered that is more appropriate per the user's preferences.
*/
vjs.TextTrack.prototype.show = function(){
this.activate();
this.mode_ = 2;
// Show element.
vjs.Component.prototype.show.call(this);
};
/**
* Hide: Mode Hidden (1)
* Indicates that the text track is active, but that the user agent is not actively displaying the cues.
* If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily.
* The user agent is maintaining a list of which cues are active, and events are being fired accordingly.
*/
vjs.TextTrack.prototype.hide = function(){
// When hidden, cues are still triggered. Disable to stop triggering.
this.activate();
this.mode_ = 1;
// Hide element.
vjs.Component.prototype.hide.call(this);
};
/**
* Disable: Mode Off/Disable (0)
* Indicates that the text track is not active. Other than for the purposes of exposing the track in the DOM, the user agent is ignoring the text track.
* No cues are active, no events are fired, and the user agent will not attempt to obtain the track's cues.
*/
vjs.TextTrack.prototype.disable = function(){
// If showing, hide.
if (this.mode_ == 2) { this.hide(); }
// Stop triggering cues
this.deactivate();
// Switch Mode to Off
this.mode_ = 0;
};
/**
* Turn on cue tracking. Tracks that are showing OR hidden are active.
*/
vjs.TextTrack.prototype.activate = function(){
// Load text file if it hasn't been yet.
if (this.readyState_ === 0) { this.load(); }
// Only activate if not already active.
if (this.mode_ === 0) {
// Update current cue on timeupdate
// Using unique ID for bind function so other tracks don't remove listener
this.player_.on('timeupdate', vjs.bind(this, this.update, this.id_));
// Reset cue time on media end
this.player_.on('ended', vjs.bind(this, this.reset, this.id_));
// Add to display
if (this.kind_ === 'captions' || this.kind_ === 'subtitles') {
this.player_.getChild('textTrackDisplay').addChild(this);
}
}
};
/**
* Turn off cue tracking.
*/
vjs.TextTrack.prototype.deactivate = function(){
// Using unique ID for bind function so other tracks don't remove listener
this.player_.off('timeupdate', vjs.bind(this, this.update, this.id_));
this.player_.off('ended', vjs.bind(this, this.reset, this.id_));
this.reset(); // Reset
// Remove from display
this.player_.getChild('textTrackDisplay').removeChild(this);
};
// A readiness state
// One of the following:
//
// Not loaded
// Indicates that the text track is known to exist (e.g. it has been declared with a track element), but its cues have not been obtained.
//
// Loading
// Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track.
//
// Loaded
// Indicates that the text track has been loaded with no fatal errors. No new cues will be added to the track except if the text track corresponds to a MutableTextTrack object.
//
// Failed to load
// Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way (e.g. URL could not be resolved, network error, unknown text track format). Some or all of the cues are likely missing and will not be obtained.
vjs.TextTrack.prototype.load = function(){
// Only load if not loaded yet.
if (this.readyState_ === 0) {
this.readyState_ = 1;
vjs.get(this.src_, vjs.bind(this, this.parseCues), vjs.bind(this, this.onError));
}
};
vjs.TextTrack.prototype.onError = function(err){
this.error = err;
this.readyState_ = 3;
this.trigger('error');
};
// Parse the WebVTT text format for cue times.
// TODO: Separate parser into own class so alternative timed text formats can be used. (TTML, DFXP)
vjs.TextTrack.prototype.parseCues = function(srcContent) {
var cue, time, text,
lines = srcContent.split('\n'),
line = '', id;
for (var i=1, j=lines.length; i<j; i++) {
// Line 0 should be 'WEBVTT', so skipping i=0
line = vjs.trim(lines[i]); // Trim whitespace and linebreaks
if (line) { // Loop until a line with content
// First line could be an optional cue ID
// Check if line has the time separator
if (line.indexOf('-->') == -1) {
id = line;
// Advance to next line for timing.
line = vjs.trim(lines[++i]);
} else {
id = this.cues_.length;
}
// First line - Number
cue = {
id: id, // Cue Number
index: this.cues_.length // Position in Array
};
// Timing line
time = line.split(/[\t ]+/);
cue.startTime = this.parseCueTime(time[0]);
cue.endTime = this.parseCueTime(time[2]);
// Additional lines - Cue Text
text = [];
// Loop until a blank line or end of lines
// Assumeing trim('') returns false for blank lines
while (lines[++i] && (line = vjs.trim(lines[i]))) {
text.push(line);
}
cue.text = text.join('<br/>');
// Add this cue
this.cues_.push(cue);
}
}
this.readyState_ = 2;
this.trigger('loaded');
};
vjs.TextTrack.prototype.parseCueTime = function(timeText) {
var parts = timeText.split(':'),
time = 0,
hours, minutes, other, seconds, ms;
// Check if optional hours place is included
// 00:00:00.000 vs. 00:00.000
if (parts.length == 3) {
hours = parts[0];
minutes = parts[1];
other = parts[2];
} else {
hours = 0;
minutes = parts[0];
other = parts[1];
}
// Break other (seconds, milliseconds, and flags) by spaces
// TODO: Make additional cue layout settings work with flags
other = other.split(/\s+/);
// Remove seconds. Seconds is the first part before any spaces.
seconds = other.splice(0,1)[0];
// Could use either . or , for decimal
seconds = seconds.split(/\.|,/);
// Get milliseconds
ms = parseFloat(seconds[1]);
seconds = seconds[0];
// hours => seconds
time += parseFloat(hours) * 3600;
// minutes => seconds
time += parseFloat(minutes) * 60;
// Add seconds
time += parseFloat(seconds);
// Add milliseconds
if (ms) { time += ms/1000; }
return time;
};
// Update active cues whenever timeupdate events are triggered on the player.
vjs.TextTrack.prototype.update = function(){
if (this.cues_.length > 0) {
// Get current player time, adjust for track offset
var offset = this.player_.options()['trackTimeOffset'] || 0;
var time = this.player_.currentTime() + offset;
// Check if the new time is outside the time box created by the the last update.
if (this.prevChange === undefined || time < this.prevChange || this.nextChange <= time) {
var cues = this.cues_,
// Create a new time box for this state.
newNextChange = this.player_.duration(), // Start at beginning of the timeline
newPrevChange = 0, // Start at end
reverse = false, // Set the direction of the loop through the cues. Optimized the cue check.
newCues = [], // Store new active cues.
// Store where in the loop the current active cues are, to provide a smart starting point for the next loop.
firstActiveIndex, lastActiveIndex,
cue, i; // Loop vars
// Check if time is going forwards or backwards (scrubbing/rewinding)
// If we know the direction we can optimize the starting position and direction of the loop through the cues array.
if (time >= this.nextChange || this.nextChange === undefined) { // NextChange should happen
// Forwards, so start at the index of the first active cue and loop forward
i = (this.firstActiveIndex !== undefined) ? this.firstActiveIndex : 0;
} else {
// Backwards, so start at the index of the last active cue and loop backward
reverse = true;
i = (this.lastActiveIndex !== undefined) ? this.lastActiveIndex : cues.length - 1;
}
while (true) { // Loop until broken
cue = cues[i];
// Cue ended at this point
if (cue.endTime <= time) {
newPrevChange = Math.max(newPrevChange, cue.endTime);
if (cue.active) {
cue.active = false;
}
// No earlier cues should have an active start time.
// Nevermind. Assume first cue could have a duration the same as the video.
// In that case we need to loop all the way back to the beginning.
// if (reverse && cue.startTime) { break; }
// Cue hasn't started
} else if (time < cue.startTime) {
newNextChange = Math.min(newNextChange, cue.startTime);
if (cue.active) {
cue.active = false;
}
// No later cues should have an active start time.
if (!reverse) { break; }
// Cue is current
} else {
if (reverse) {
// Add cue to front of array to keep in time order
newCues.splice(0,0,cue);
// If in reverse, the first current cue is our lastActiveCue
if (lastActiveIndex === undefined) { lastActiveIndex = i; }
firstActiveIndex = i;
} else {
// Add cue to end of array
newCues.push(cue);
// If forward, the first current cue is our firstActiveIndex
if (firstActiveIndex === undefined) { firstActiveIndex = i; }
lastActiveIndex = i;
}
newNextChange = Math.min(newNextChange, cue.endTime);
newPrevChange = Math.max(newPrevChange, cue.startTime);
cue.active = true;
}
if (reverse) {
// Reverse down the array of cues, break if at first
if (i === 0) { break; } else { i--; }
} else {
// Walk up the array fo cues, break if at last
if (i === cues.length - 1) { break; } else { i++; }
}
}
this.activeCues_ = newCues;
this.nextChange = newNextChange;
this.prevChange = newPrevChange;
this.firstActiveIndex = firstActiveIndex;
this.lastActiveIndex = lastActiveIndex;
this.updateDisplay();
this.trigger('cuechange');
}
}
};
// Add cue HTML to display
vjs.TextTrack.prototype.updateDisplay = function(){
var cues = this.activeCues_,
html = '',
i=0,j=cues.length;
for (;i<j;i++) {
html += '<span class="vjs-tt-cue">'+cues[i].text+'</span>';
}
this.el_.innerHTML = html;
};
// Set all loop helper values back
vjs.TextTrack.prototype.reset = function(){
this.nextChange = 0;
this.prevChange = this.player_.duration();
this.firstActiveIndex = 0;
this.lastActiveIndex = 0;
};
// Create specific track types
/**
* The track component for managing the hiding and showing of captions
*
* @constructor
*/
vjs.CaptionsTrack = vjs.TextTrack.extend();
vjs.CaptionsTrack.prototype.kind_ = 'captions';
// Exporting here because Track creation requires the track kind
// to be available on global object. e.g. new window['videojs'][Kind + 'Track']
/**
* The track component for managing the hiding and showing of subtitles
*
* @constructor
*/
vjs.SubtitlesTrack = vjs.TextTrack.extend();
vjs.SubtitlesTrack.prototype.kind_ = 'subtitles';
/**
* The track component for managing the hiding and showing of chapters
*
* @constructor
*/
vjs.ChaptersTrack = vjs.TextTrack.extend();
vjs.ChaptersTrack.prototype.kind_ = 'chapters';
/* Text Track Display
============================================================================= */
// Global container for both subtitle and captions text. Simple div container.
/**
* The component for displaying text track cues
*
* @constructor
*/
vjs.TextTrackDisplay = vjs.Component.extend({
/** @constructor */
init: function(player, options, ready){
vjs.Component.call(this, player, options, ready);
// This used to be called during player init, but was causing an error
// if a track should show by default and the display hadn't loaded yet.
// Should probably be moved to an external track loader when we support
// tracks that don't need a display.
if (player.options_['tracks'] && player.options_['tracks'].length > 0) {
this.player_.addTextTracks(player.options_['tracks']);
}
}
});
vjs.TextTrackDisplay.prototype.createEl = function(){
return vjs.Component.prototype.createEl.call(this, 'div', {
className: 'vjs-text-track-display'
});
};
/**
* The specific menu item type for selecting a language within a text track kind
*
* @constructor
*/
vjs.TextTrackMenuItem = vjs.MenuItem.extend({
/** @constructor */
init: function(player, options){
var track = this.track = options['track'];
// Modify options for parent MenuItem class's init.
options['label'] = track.label();
options['selected'] = track.dflt();
vjs.MenuItem.call(this, player, options);
this.player_.on(track.kind() + 'trackchange', vjs.bind(this, this.update));
}
});
vjs.TextTrackMenuItem.prototype.onClick = function(){
vjs.MenuItem.prototype.onClick.call(this);
this.player_.showTextTrack(this.track.id_, this.track.kind());
};
vjs.TextTrackMenuItem.prototype.update = function(){
this.selected(this.track.mode() == 2);
};
/**
* A special menu item for turning of a specific type of text track
*
* @constructor
*/
vjs.OffTextTrackMenuItem = vjs.TextTrackMenuItem.extend({
/** @constructor */
init: function(player, options){
// Create pseudo track info
// Requires options['kind']
options['track'] = {
kind: function() { return options['kind']; },
player: player,
label: function(){ return options['kind'] + ' off'; },
dflt: function(){ return false; },
mode: function(){ return false; }
};
vjs.TextTrackMenuItem.call(this, player, options);
this.selected(true);
}
});
vjs.OffTextTrackMenuItem.prototype.onClick = function(){
vjs.TextTrackMenuItem.prototype.onClick.call(this);
this.player_.showTextTrack(this.track.id_, this.track.kind());
};
vjs.OffTextTrackMenuItem.prototype.update = function(){
var tracks = this.player_.textTracks(),
i=0, j=tracks.length, track,
off = true;
for (;i<j;i++) {
track = tracks[i];
if (track.kind() == this.track.kind() && track.mode() == 2) {
off = false;
}
}
this.selected(off);
};
/**
* The base class for buttons that toggle specific text track types (e.g. subtitles)
*
* @constructor
*/
vjs.TextTrackButton = vjs.MenuButton.extend({
/** @constructor */
init: function(player, options){
vjs.MenuButton.call(this, player, options);
if (this.items.length <= 1) {
this.hide();
}
}
});
// vjs.TextTrackButton.prototype.buttonPressed = false;
// vjs.TextTrackButton.prototype.createMenu = function(){
// var menu = new vjs.Menu(this.player_);
// // Add a title list item to the top
// // menu.el().appendChild(vjs.createEl('li', {
// // className: 'vjs-menu-title',
// // innerHTML: vjs.capitalize(this.kind_),
// // tabindex: -1
// // }));
// this.items = this.createItems();
// // Add menu items to the menu
// for (var i = 0; i < this.items.length; i++) {
// menu.addItem(this.items[i]);
// }
// // Add list to element
// this.addChild(menu);
// return menu;
// };
// Create a menu item for each text track
vjs.TextTrackButton.prototype.createItems = function(){
var items = [], track;
// Add an OFF menu item to turn all tracks off
items.push(new vjs.OffTextTrackMenuItem(this.player_, { 'kind': this.kind_ }));
for (var i = 0; i < this.player_.textTracks().length; i++) {
track = this.player_.textTracks()[i];
if (track.kind() === this.kind_) {
items.push(new vjs.TextTrackMenuItem(this.player_, {
'track': track
}));
}
}
return items;
};
/**
* The button component for toggling and selecting captions
*
* @constructor
*/
vjs.CaptionsButton = vjs.TextTrackButton.extend({
/** @constructor */
init: function(player, options, ready){
vjs.TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label','Captions Menu');
}
});
vjs.CaptionsButton.prototype.kind_ = 'captions';
vjs.CaptionsButton.prototype.buttonText = 'Captions';
vjs.CaptionsButton.prototype.className = 'vjs-captions-button';
/**
* The button component for toggling and selecting subtitles
*
* @constructor
*/
vjs.SubtitlesButton = vjs.TextTrackButton.extend({
/** @constructor */
init: function(player, options, ready){
vjs.TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label','Subtitles Menu');
}
});
vjs.SubtitlesButton.prototype.kind_ = 'subtitles';
vjs.SubtitlesButton.prototype.buttonText = 'Subtitles';
vjs.SubtitlesButton.prototype.className = 'vjs-subtitles-button';
// Chapters act much differently than other text tracks
// Cues are navigation vs. other tracks of alternative languages
/**
* The button component for toggling and selecting chapters
*
* @constructor
*/
vjs.ChaptersButton = vjs.TextTrackButton.extend({
/** @constructor */
init: function(player, options, ready){
vjs.TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label','Chapters Menu');
}
});
vjs.ChaptersButton.prototype.kind_ = 'chapters';
vjs.ChaptersButton.prototype.buttonText = 'Chapters';
vjs.ChaptersButton.prototype.className = 'vjs-chapters-button';
// Create a menu item for each text track
vjs.ChaptersButton.prototype.createItems = function(){
var items = [], track;
for (var i = 0; i < this.player_.textTracks().length; i++) {
track = this.player_.textTracks()[i];
if (track.kind() === this.kind_) {
items.push(new vjs.TextTrackMenuItem(this.player_, {
'track': track
}));
}
}
return items;
};
vjs.ChaptersButton.prototype.createMenu = function(){
var tracks = this.player_.textTracks(),
i = 0,
j = tracks.length,
track, chaptersTrack,
items = this.items = [];
for (;i<j;i++) {
track = tracks[i];
if (track.kind() == this.kind_) {
if (track.readyState() === 0) {
track.load();
track.on('loaded', vjs.bind(this, this.createMenu));
} else {
chaptersTrack = track;
break;
}
}
}
var menu = this.menu;
if (menu === undefined) {
menu = new vjs.Menu(this.player_);
menu.contentEl().appendChild(vjs.createEl('li', {
className: 'vjs-menu-title',
innerHTML: vjs.capitalize(this.kind_),
tabindex: -1
}));
}
if (chaptersTrack) {
var cues = chaptersTrack.cues_, cue, mi;
i = 0;
j = cues.length;
for (;i<j;i++) {
cue = cues[i];
mi = new vjs.ChaptersTrackMenuItem(this.player_, {
'track': chaptersTrack,
'cue': cue
});
items.push(mi);
menu.addChild(mi);
}
this.addChild(menu);
}
if (this.items.length > 0) {
this.show();
}
return menu;
};
/**
* @constructor
*/
vjs.ChaptersTrackMenuItem = vjs.MenuItem.extend({
/** @constructor */
init: function(player, options){
var track = this.track = options['track'],
cue = this.cue = options['cue'],
currentTime = player.currentTime();
// Modify options for parent MenuItem class's init.
options['label'] = cue.text;
options['selected'] = (cue.startTime <= currentTime && currentTime < cue.endTime);
vjs.MenuItem.call(this, player, options);
track.on('cuechange', vjs.bind(this, this.update));
}
});
vjs.ChaptersTrackMenuItem.prototype.onClick = function(){
vjs.MenuItem.prototype.onClick.call(this);
this.player_.currentTime(this.cue.startTime);
this.update(this.cue.startTime);
};
vjs.ChaptersTrackMenuItem.prototype.update = function(){
var cue = this.cue,
currentTime = this.player_.currentTime();
// vjs.log(currentTime, cue.startTime);
this.selected(cue.startTime <= currentTime && currentTime < cue.endTime);
};
// Add Buttons to controlBar
vjs.obj.merge(vjs.ControlBar.prototype.options_['children'], {
'subtitlesButton': {},
'captionsButton': {},
'chaptersButton': {}
});
// vjs.Cue = vjs.Component.extend({
// /** @constructor */
// init: function(player, options){
// vjs.Component.call(this, player, options);
// }
// });
/**
* @fileoverview Add JSON support
* @suppress {undefinedVars}
* (Compiler doesn't like JSON not being declared)
*/
/**
* Javascript JSON implementation
* (Parse Method Only)
* https://github.com/douglascrockford/JSON-js/blob/master/json2.js
* Only using for parse method when parsing data-setup attribute JSON.
* @suppress {undefinedVars}
* @namespace
* @private
*/
vjs.JSON;
if (typeof window.JSON !== 'undefined' && window.JSON.parse === 'function') {
vjs.JSON = window.JSON;
} else {
vjs.JSON = {};
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
/**
* parse the json
*
* @memberof vjs.JSON
* @param {String} text The JSON string to parse
* @param {Function=} [reviver] Optional function that can transform the results
* @return {Object|Array} The parsed JSON
*/
vjs.JSON.parse = function (text, reviver) {
var j;
function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
j = eval('(' + text + ')');
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
throw new SyntaxError('JSON.parse(): invalid or malformed JSON data');
};
}
/**
* @fileoverview Functions for automatically setting up a player
* based on the data-setup attribute of the video tag
*/
// Automatically set up any tags that have a data-setup attribute
vjs.autoSetup = function(){
var options, vid, player,
vids = document.getElementsByTagName('video');
// Check if any media elements exist
if (vids && vids.length > 0) {
for (var i=0,j=vids.length; i<j; i++) {
vid = vids[i];
// Check if element exists, has getAttribute func.
// IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately.
if (vid && vid.getAttribute) {
// Make sure this player hasn't already been set up.
if (vid['player'] === undefined) {
options = vid.getAttribute('data-setup');
// Check if data-setup attr exists.
// We only auto-setup if they've added the data-setup attr.
if (options !== null) {
// Parse options JSON
// If empty string, make it a parsable json object.
options = vjs.JSON.parse(options || '{}');
// Create new video.js instance.
player = videojs(vid, options);
}
}
// If getAttribute isn't defined, we need to wait for the DOM.
} else {
vjs.autoSetupTimeout(1);
break;
}
}
// No videos were found, so keep looping unless page is finished loading.
} else if (!vjs.windowLoaded) {
vjs.autoSetupTimeout(1);
}
};
// Pause to let the DOM keep processing
vjs.autoSetupTimeout = function(wait){
setTimeout(vjs.autoSetup, wait);
};
if (document.readyState === 'complete') {
vjs.windowLoaded = true;
} else {
vjs.one(window, 'load', function(){
vjs.windowLoaded = true;
});
}
// Run Auto-load players
// You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version)
vjs.autoSetupTimeout(1);
/**
* the method for registering a video.js plugin
*
* @param {String} name The name of the plugin
* @param {Function} init The function that is run when the player inits
*/
vjs.plugin = function(name, init){
vjs.Player.prototype[name] = init;
};
|
imports/ui/components/MultipleStepJournal/MultipleStepJournal.js | jamiebones/Journal_Publication |
import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col, FormGroup, HelpBlock , Label ,
ControlLabel, Button , Well , FormControl } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { ReactiveVar } from 'meteor/reactive-var';
import Journals from '../../../api/Journal/Journal';
import Loading from '../Loading/Loading';
import { Capitalize , GetNameDetailsObjectFromId , GetEmailFromUserId , GetNameFromUserId } from '../../../modules/utilities';
export default class MultiStepJournal extends React.Component {
constructor(props){
super(props)
this.state = {
journalName : "0",
journalTitle : "",
}
this.handleNext = this.handleNext.bind( this );
this.handleChange = this.handleChange.bind(this);
}
handleNext(event){
event.preventDefault();
const journalName = document.getElementById('journalNameSelect').value;
const select = document.getElementById('journalNameSelect');
const journalTitle = select.options[select.selectedIndex].text;
this.props.nextButton(event , 'journalName' , this.state.journalName);
this.props.nextButton(event , 'journalTitle' , this.state.journalTitle);
this.setState({journalName : journalName ,
journalTitle : journalTitle});
this.props.updateState('journalName' , journalName );
this.props.updateState('journalTitle' , journalTitle );
}
handleChange (event) {
const value = event.target.value;
const select = document.getElementById('journalNameSelect');
const journalTitle = select.options[select.selectedIndex].text;
if (value !== "0"){
this.setState({journalName : value , journalTitle : journalTitle });
this.props.updateState('journalName' , value );
this.props.updateState('journalTitle' , journalTitle );
this.props.selectChange( value );
}
}
render(){
const {journals , selectedJournal , selectChange } = this.props;
return (journals.length ? (
<div>
<Row>
<Col md={6} mdOffset={3}>
{selectedJournal && selectedJournal.length > 0 ?
(
<div>
<Well bsSize="small">
<h4 className="text-center">
<Label bsStyle="default">Journal Details</Label>
</h4>
<p>Journal Name : {selectedJournal[0] && selectedJournal[0].journalName}</p>
<p>Contact Name : {selectedJournal[0] && selectedJournal[0].owner && GetNameFromUserId(selectedJournal[0].owner)}</p>
<p>Contact Email : {selectedJournal[0] && selectedJournal[0].owner && GetEmailFromUserId(selectedJournal[0].owner)}</p>
<p>Review Fee : {selectedJournal[0] && selectedJournal[0].settings &&
selectedJournal[0].settings.reviewFee === 0 || !selectedJournal[0].settings.reviewFee ? ('Free Review') :
<span>₦ {selectedJournal[0].settings.reviewFee}</span> }</p>
<p>Publish Fee : ₦{selectedJournal[0] && selectedJournal[0].settings && selectedJournal[0].settings.publishFee} </p>
<p>Telephone Number(s)</p>
<ul className="list-unstyled">
{selectedJournal[0] && selectedJournal[0].phone && selectedJournal[0].phone.map((number , index)=>{
return (<li key={index}>{number}</li>)
})}
</ul>
<hr/>
</Well>
</div>
) : ""}
<FormGroup>
<ControlLabel>Journal Name </ControlLabel>
<FormControl componentClass="select"
onChange={ this.handleChange }
id="journalNameSelect"
value={this.props.data.journalName}>
<option value="0">select </option>
{journals.map(({journalName , _id , settings} , index)=>{
return ( settings && settings.publishFee
&& settings.accountDetails ?
<option value={_id} key={index}>{Capitalize(journalName)}</option>
: "" )
})}
</FormControl>
<HelpBlock>Select the journal you what to published in .</HelpBlock>
</FormGroup>
<div className="pull-right">
<Button bsStyle="info" className="pull-right"
onClick={(event)=>this.handleNext(event) }
bsSize="small">Next
</Button>
</div>
</Col>
</Row>
</div>) : "")
}
}
|
classic/src/scenes/traypopout/src/Scenes/UnreadScene/UnreadMailboxList/UnreadMailboxListItem.js | wavebox/waveboxapp | import React from 'react'
import PropTypes from 'prop-types'
import { accountStore } from 'stores/account'
import { ListItem } from '@material-ui/core'
import MailboxBadge from 'wbui/MailboxBadge'
import ACAvatarCircle2 from 'wbui/ACAvatarCircle2'
import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight'
import { withStyles } from '@material-ui/core/styles'
import grey from '@material-ui/core/colors/grey'
import Resolver from 'Runtime/Resolver'
import classNames from 'classnames'
import MailboxDisplayName from '../Common/MailboxDisplayName'
const styles = {
root: {
cursor: 'pointer'
},
forwardArrow: {
color: grey[400]
}
}
@withStyles(styles)
class UnreadMailboxListItem extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
mailboxId: PropTypes.string.isRequired,
requestShowMailbox: PropTypes.func.isRequired,
requestSwitchMailbox: PropTypes.func.isRequired
}
/* **************************************************************************/
// Component Lifecycle
/* **************************************************************************/
componentDidMount () {
accountStore.listen(this.mailboxesChanged)
}
componentWillUnmount () {
accountStore.unlisten(this.mailboxesChanged)
}
componentWillReceiveProps (nextProps) {
if (this.props.mailboxId !== nextProps.mailboxId) {
this.setState(this.generateMailboxState(nextProps.mailboxId))
}
}
/* **************************************************************************/
// Data Lifecycle
/* **************************************************************************/
state = (() => {
return {
...this.generateMailboxState(this.props.mailboxId)
}
})()
mailboxesChanged = (mailboxState) => {
this.setState(this.generateMailboxState(this.props.mailboxId, mailboxState))
}
/**
* Generates the mailbox state
* @param mailboxId: the id of the mailbox
* @param accountState=autoget: the current store state
* @return the mailbox state
*/
generateMailboxState (mailboxId, accountState = accountStore.getState()) {
const mailbox = accountState.getMailbox(mailboxId)
return {
badgeColor: mailbox.badgeColor,
unreadCount: accountState.userUnreadCountForMailbox(mailboxId),
hasUnreadActivity: accountState.userUnreadActivityForMailbox(mailboxId),
avatar: accountState.getMailboxAvatarConfig(mailboxId)
}
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
render () {
const {
mailboxId,
requestSwitchMailbox,
requestShowMailbox,
classes,
className,
...passProps
} = this.props
const {
badgeColor,
avatar,
hasUnreadActivity,
unreadCount
} = this.state
return (
<ListItem
button
className={classNames(classes.root, className)}
onClick={(evt) => requestShowMailbox(evt, mailboxId)}
{...passProps}>
<MailboxBadge color={badgeColor} unreadCount={unreadCount} hasUnreadActivity={hasUnreadActivity}>
<ACAvatarCircle2
avatar={avatar}
resolver={(i) => Resolver.image(i)}
size={40}
onClick={(evt) => {
evt.preventDefault()
evt.stopPropagation()
requestSwitchMailbox(evt, mailboxId)
}} />
</MailboxBadge>
<MailboxDisplayName mailboxId={mailboxId} />
<KeyboardArrowRightIcon className={classes.forwardArrow} />
</ListItem>
)
}
}
export default UnreadMailboxListItem
|
ajax/libs/jquery/1.4.1/jquery.min.js | kodypeterson/cdnjs | /*!
* jQuery JavaScript Library v1.4.1
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Mon Jan 25 19:43:33 2010 -0500
*/
(function(z,v){function la(){if(!c.isReady){try{r.documentElement.doScroll("left")}catch(a){setTimeout(la,1);return}c.ready()}}function Ma(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,i){var j=a.length;if(typeof b==="object"){for(var n in b)X(a,n,b[n],f,e,d);return a}if(d!==v){f=!i&&f&&c.isFunction(d);for(n=0;n<j;n++)e(a[n],b,f?d.call(a[n],n,e(a[n],b)):d,i);return a}return j?
e(a[0],b):null}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function ma(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function na(a){var b,d=[],f=[],e=arguments,i,j,n,o,m,s,x=c.extend({},c.data(this,"events").live);if(!(a.button&&a.type==="click")){for(o in x){j=x[o];if(j.live===a.type||j.altLive&&c.inArray(a.type,j.altLive)>-1){i=j.data;i.beforeFilter&&i.beforeFilter[a.type]&&!i.beforeFilter[a.type](a)||f.push(j.selector)}else delete x[o]}i=c(a.target).closest(f,
a.currentTarget);m=0;for(s=i.length;m<s;m++)for(o in x){j=x[o];n=i[m].elem;f=null;if(i[m].selector===j.selector){if(j.live==="mouseenter"||j.live==="mouseleave")f=c(a.relatedTarget).closest(j.selector)[0];if(!f||f!==n)d.push({elem:n,fn:j})}}m=0;for(s=d.length;m<s;m++){i=d[m];a.currentTarget=i.elem;a.data=i.fn.data;if(i.fn.apply(i.elem,e)===false){b=false;break}}return b}}function oa(a,b){return"live."+(a?a+".":"")+b.replace(/\./g,"`").replace(/ /g,"&")}function pa(a){return!a||!a.parentNode||a.parentNode.nodeType===
11}function qa(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var i in f)for(var j in f[i])c.event.add(this,i,f[i][j],f[i][j].data)}}})}function ra(a,b,d){var f,e,i;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&a[0].indexOf("<option")<0&&(c.support.checkClone||!sa.test(a[0]))){e=true;if(i=c.fragments[a[0]])if(i!==1)f=i}if(!f){b=b&&b[0]?b[0].ownerDocument||b[0]:r;f=b.createDocumentFragment();
c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=i?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(ta.concat.apply([],ta.slice(0,b)),function(){d[this]=a});return d}function ua(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Na=z.jQuery,Oa=z.$,r=z.document,S,Pa=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Qa=/^.[^:#\[\.,]*$/,Ra=/\S/,Sa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Ta=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,O=navigator.userAgent,
va=false,P=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,Q=Array.prototype.slice,wa=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(typeof a==="string")if((d=Pa.exec(a))&&(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:r;if(a=Ta.exec(a))if(c.isPlainObject(b)){a=[r.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=ra([d[1]],
[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}}else{if(b=r.getElementById(d[2])){if(b.id!==d[2])return S.find(a);this.length=1;this[0]=b}this.context=r;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=r;a=r.getElementsByTagName(a)}else return!b||b.jquery?(b||S).find(a):c(b).find(a);else if(c.isFunction(a))return S.ready(a);if(a.selector!==v){this.selector=a.selector;this.context=a.context}return c.isArray(a)?this.setArray(a):c.makeArray(a,
this)},selector:"",jquery:"1.4.1",length:0,size:function(){return this.length},toArray:function(){return Q.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){a=c(a||null);a.prevObject=this;a.context=this.context;if(b==="find")a.selector=this.selector+(this.selector?" ":"")+d;else if(b)a.selector=this.selector+"."+b+"("+d+")";return a},setArray:function(a){this.length=0;ba.apply(this,a);return this},each:function(a,b){return c.each(this,
a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(r,c);else P&&P.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(Q.apply(this,arguments),"slice",Q.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};
c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,i,j,n;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(i in e){j=a[i];n=e[i];if(a!==n)if(f&&n&&(c.isPlainObject(n)||c.isArray(n))){j=j&&(c.isPlainObject(j)||c.isArray(j))?j:c.isArray(n)?[]:{};a[i]=c.extend(f,j,n)}else if(n!==v)a[i]=n}return a};c.extend({noConflict:function(a){z.$=
Oa;if(a)z.jQuery=Na;return c},isReady:false,ready:function(){if(!c.isReady){if(!r.body)return setTimeout(c.ready,13);c.isReady=true;if(P){for(var a,b=0;a=P[b++];)a.call(r,c);P=null}c.fn.triggerHandler&&c(r).triggerHandler("ready")}},bindReady:function(){if(!va){va=true;if(r.readyState==="complete")return c.ready();if(r.addEventListener){r.addEventListener("DOMContentLoaded",L,false);z.addEventListener("load",c.ready,false)}else if(r.attachEvent){r.attachEvent("onreadystatechange",L);z.attachEvent("onload",
c.ready);var a=false;try{a=z.frameElement==null}catch(b){}r.documentElement.doScroll&&a&&la()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,"isPrototypeOf"))return false;var b;for(b in a);return b===v||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;
return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return z.JSON&&z.JSON.parse?z.JSON.parse(a):(new Function("return "+a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Ra.test(a)){var b=r.getElementsByTagName("head")[0]||
r.documentElement,d=r.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(r.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,i=a.length,j=i===v||c.isFunction(a);if(d)if(j)for(f in a){if(b.apply(a[f],d)===false)break}else for(;e<i;){if(b.apply(a[e++],d)===false)break}else if(j)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=
a[0];e<i&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Sa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==
v;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,i=a.length;e<i;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,i=0,j=a.length;i<j;i++){e=b(a[i],i,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=v}else if(b&&!c.isFunction(b)){d=b;b=v}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},
uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});O=c.uaMatch(O);if(O.browser){c.browser[O.browser]=true;c.browser.version=O.version}if(c.browser.webkit)c.browser.safari=true;if(wa)c.inArray=function(a,b){return wa.call(b,a)};S=c(r);if(r.addEventListener)L=function(){r.removeEventListener("DOMContentLoaded",
L,false);c.ready()};else if(r.attachEvent)L=function(){if(r.readyState==="complete"){r.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=r.documentElement,b=r.createElement("script"),d=r.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=d.getElementsByTagName("*"),i=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!i)){c.support=
{leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(i.getAttribute("style")),hrefNormalized:i.getAttribute("href")==="/a",opacity:/^0.55$/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:r.createElement("select").appendChild(r.createElement("option")).selected,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};
b.type="text/javascript";try{b.appendChild(r.createTextNode("window."+f+"=1;"))}catch(j){}a.insertBefore(b,a.firstChild);if(z[f]){c.support.scriptEval=true;delete z[f]}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function n(){c.support.noCloneEvent=false;d.detachEvent("onclick",n)});d.cloneNode(true).fireEvent("onclick")}d=r.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=r.createDocumentFragment();a.appendChild(d.firstChild);
c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var n=r.createElement("div");n.style.width=n.style.paddingLeft="1px";r.body.appendChild(n);c.boxModel=c.support.boxModel=n.offsetWidth===2;r.body.removeChild(n).style.display="none"});a=function(n){var o=r.createElement("div");n="on"+n;var m=n in o;if(!m){o.setAttribute(n,"return;");m=typeof o[n]==="function"}return m};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=i=null}})();c.props=
{"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ua=0,xa={},Va={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==z?xa:a;var f=a[G],e=c.cache;if(!b&&!f)return null;f||(f=++Ua);if(typeof b==="object"){a[G]=f;e=e[f]=c.extend(true,
{},b)}else e=e[f]?e[f]:typeof d==="undefined"?Va:(e[f]={});if(d!==v){a[G]=f;e[b]=d}return typeof b==="string"?e[b]:e}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==z?xa:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{try{delete a[G]}catch(i){a.removeAttribute&&a.removeAttribute(G)}delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,
a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===v){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===v&&this.length)f=c.data(this[0],a);return f===v&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);
return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===v)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||
a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var ya=/[\n\t]/g,ca=/\s+/,Wa=/\r/g,Xa=/href|src|style/,Ya=/(button|input)/i,Za=/(button|input|object|select|textarea)/i,$a=/^(a|area)$/i,za=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(o){var m=
c(this);m.addClass(a.call(this,o,m.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className)for(var i=" "+e.className+" ",j=0,n=b.length;j<n;j++){if(i.indexOf(" "+b[j]+" ")<0)e.className+=" "+b[j]}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var m=c(this);m.removeClass(a.call(this,o,m.attr("class")))});if(a&&typeof a==="string"||a===v)for(var b=(a||"").split(ca),
d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var i=(" "+e.className+" ").replace(ya," "),j=0,n=b.length;j<n;j++)i=i.replace(" "+b[j]+" "," ");e.className=i.substring(1,i.length-1)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var i=c(this);i.toggleClass(a.call(this,e,i.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,i=0,j=c(this),n=b,o=
a.split(ca);e=o[i++];){n=f?n:!j.hasClass(e);j[n?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(ya," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===v){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||
{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var i=b?d:0;for(d=b?d+1:e.length;i<d;i++){var j=e[i];if(j.selected){a=c(j).val();if(b)return a;f.push(a)}}return f}if(za.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Wa,"")}return v}var n=c.isFunction(a);return this.each(function(o){var m=c(this),s=a;if(this.nodeType===1){if(n)s=a.call(this,o,m.val());
if(typeof s==="number")s+="";if(c.isArray(s)&&za.test(this.type))this.checked=c.inArray(m.val(),s)>=0;else if(c.nodeName(this,"select")){var x=c.makeArray(s);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),x)>=0});if(!x.length)this.selectedIndex=-1}else this.value=s}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return v;if(f&&b in c.attrFn)return c(a)[b](d);
f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==v;b=f&&c.props[b]||b;if(a.nodeType===1){var i=Xa.test(b);if(b in a&&f&&!i){if(e){b==="type"&&Ya.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:Za.test(a.nodeName)||$a.test(a.nodeName)&&a.href?0:v;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=
""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&i?a.getAttribute(b,2):a.getAttribute(b);return a===null?v:a}return c.style(a,b,d)}});var ab=function(a){return a.replace(/[^\w\s\.\|`]/g,function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==z&&!a.frameElement)a=z;if(!d.guid)d.guid=c.guid++;if(f!==v){d=c.proxy(d);d.data=f}var e=c.data(a,"events")||c.data(a,"events",{}),i=c.data(a,"handle"),j;if(!i){j=
function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(j.elem,arguments):v};i=c.data(a,"handle",j)}if(i){i.elem=a;b=b.split(/\s+/);for(var n,o=0;n=b[o++];){var m=n.split(".");n=m.shift();if(o>1){d=c.proxy(d);if(f!==v)d.data=f}d.type=m.slice(0).sort().join(".");var s=e[n],x=this.special[n]||{};if(!s){s=e[n]={};if(!x.setup||x.setup.call(a,f,m,d)===false)if(a.addEventListener)a.addEventListener(n,i,false);else a.attachEvent&&a.attachEvent("on"+n,i)}if(x.add)if((m=x.add.call(a,
d,f,m,s))&&c.isFunction(m)){m.guid=m.guid||d.guid;m.data=m.data||d.data;m.type=m.type||d.type;d=m}s[d.guid]=d;this.global[n]=true}a=null}}},global:{},remove:function(a,b,d){if(!(a.nodeType===3||a.nodeType===8)){var f=c.data(a,"events"),e,i,j;if(f){if(b===v||typeof b==="string"&&b.charAt(0)===".")for(i in f)this.remove(a,i+(b||""));else{if(b.type){d=b.handler;b=b.type}b=b.split(/\s+/);for(var n=0;i=b[n++];){var o=i.split(".");i=o.shift();var m=!o.length,s=c.map(o.slice(0).sort(),ab);s=new RegExp("(^|\\.)"+
s.join("\\.(?:.*\\.)?")+"(\\.|$)");var x=this.special[i]||{};if(f[i]){if(d){j=f[i][d.guid];delete f[i][d.guid]}else for(var A in f[i])if(m||s.test(f[i][A].type))delete f[i][A];x.remove&&x.remove.call(a,o,j);for(e in f[i])break;if(!e){if(!x.teardown||x.teardown.call(a,o)===false)if(a.removeEventListener)a.removeEventListener(i,c.data(a,"handle"),false);else a.detachEvent&&a.detachEvent("on"+i,c.data(a,"handle"));e=null;delete f[i]}}}}for(e in f)break;if(!e){if(A=c.data(a,"handle"))A.elem=null;c.removeData(a,
"events");c.removeData(a,"handle")}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();this.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return v;a.result=v;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,
b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(i){}if(!a.isPropagationStopped()&&f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){d=a.target;var j;if(!(c.nodeName(d,"a")&&e==="click")&&!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()])){try{if(d[e]){if(j=d["on"+e])d["on"+e]=null;this.triggered=true;d[e]()}}catch(n){}if(j)d["on"+e]=j;this.triggered=false}}},handle:function(a){var b,
d;a=arguments[0]=c.event.fix(a||z.event);a.currentTarget=this;d=a.type.split(".");a.type=d.shift();b=!d.length&&!a.exclusive;var f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)");d=(c.data(this,"events")||{})[a.type];for(var e in d){var i=d[e];if(b||f.test(i.type)){a.handler=i;a.data=i.data;i=i.apply(this,arguments);if(i!==v){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||r;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=r.documentElement;d=r.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==v)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a,b){c.extend(a,b||{});a.guid+=b.selector+b.live;b.liveProxy=a;c.event.add(this,b.live,na,b)},remove:function(a){if(a.length){var b=
0,d=new RegExp("(^|\\.)"+a[0]+"(\\.|$)");c.each(c.data(this,"events").live||{},function(){d.test(this.type)&&b++});b<1&&c.event.remove(this,a[0],na)}},special:{}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};
c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y};var Aa=function(a){for(var b=
a.relatedTarget;b&&b!==this;)try{b=b.parentNode}catch(d){break}if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}},Ba=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ba:Aa,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ba:Aa)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(a,b,d){if(this.nodeName.toLowerCase()!==
"form"){c.event.add(this,"click.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="submit"||i==="image")&&c(e).closest("form").length)return ma("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="text"||i==="password")&&c(e).closest("form").length&&f.keyCode===13)return ma("submit",this,arguments)})}else return false},remove:function(a,b){c.event.remove(this,"click.specialSubmit"+(b?"."+b.guid:""));c.event.remove(this,
"keypress.specialSubmit"+(b?"."+b.guid:""))}};if(!c.support.changeBubbles){var da=/textarea|input|select/i;function Ca(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d}function ea(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Ca(d);if(a.type!=="focusout"||
d.type!=="radio")c.data(d,"_change_data",e);if(!(f===v||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}}c.event.special.change={filters:{focusout:ea,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return ea.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return ea.call(this,a)},beforeactivate:function(a){a=
a.target;a.nodeName.toLowerCase()==="input"&&a.type==="radio"&&c.data(a,"_change_data",Ca(a))}},setup:function(a,b,d){for(var f in T)c.event.add(this,f+".specialChange."+d.guid,T[f]);return da.test(this.nodeName)},remove:function(a,b){for(var d in T)c.event.remove(this,d+".specialChange"+(b?"."+b.guid:""),T[d]);return da.test(this.nodeName)}};var T=c.event.special.change.filters}r.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,
f)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var i in d)this[b](i,f,d[i],e);return this}if(c.isFunction(f)){e=f;f=v}var j=b==="one"?c.proxy(e,function(n){c(this).unbind(n,j);return e.apply(this,arguments)}):e;return d==="unload"&&b!=="one"?this.one(d,f,e):this.each(function(){c.event.add(this,d,j,f)})}});c.fn.extend({unbind:function(a,
b){if(typeof a==="object"&&!a.preventDefault){for(var d in a)this.unbind(d,a[d]);return this}return this.each(function(){c.event.remove(this,a,b)})},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+
a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e){var i,j=0;if(c.isFunction(f)){e=f;f=v}for(d=(d||"").split(/\s+/);(i=d[j++])!=null;){i=i==="focus"?"focusin":i==="blur"?"focusout":i==="hover"?d.push("mouseleave")&&"mouseenter":i;b==="live"?c(this.context).bind(oa(i,this.selector),{data:f,selector:this.selector,
live:i},e):c(this.context).unbind(oa(i,this.selector),e?{guid:e.guid+this.selector+i}:null)}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});z.attachEvent&&!z.addEventListener&&z.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});
(function(){function a(g){for(var h="",k,l=0;g[l];l++){k=g[l];if(k.nodeType===3||k.nodeType===4)h+=k.nodeValue;else if(k.nodeType!==8)h+=a(k.childNodes)}return h}function b(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===k){y=l[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=k;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}l[q]=y}}}function d(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===
k){y=l[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=k;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(o.filter(h,[t]).length>0){y=t;break}}t=t[g]}l[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,i=Object.prototype.toString,j=false,n=true;[0,0].sort(function(){n=false;return 0});var o=function(g,h,k,l){k=k||[];var q=h=h||r;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||
typeof g!=="string")return k;for(var p=[],u,t,y,R,H=true,M=w(h),I=g;(f.exec(""),u=f.exec(I))!==null;){I=u[3];p.push(u[1]);if(u[2]){R=u[3];break}}if(p.length>1&&s.exec(g))if(p.length===2&&m.relative[p[0]])t=fa(p[0]+p[1],h);else for(t=m.relative[p[0]]?[h]:o(p.shift(),h);p.length;){g=p.shift();if(m.relative[g])g+=p.shift();t=fa(g,t)}else{if(!l&&p.length>1&&h.nodeType===9&&!M&&m.match.ID.test(p[0])&&!m.match.ID.test(p[p.length-1])){u=o.find(p.shift(),h,M);h=u.expr?o.filter(u.expr,u.set)[0]:u.set[0]}if(h){u=
l?{expr:p.pop(),set:A(l)}:o.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=u.expr?o.filter(u.expr,u.set):u.set;if(p.length>0)y=A(t);else H=false;for(;p.length;){var D=p.pop();u=D;if(m.relative[D])u=p.pop();else D="";if(u==null)u=h;m.relative[D](y,u,M)}}else y=[]}y||(y=t);y||o.error(D||g);if(i.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))k.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&
y[g].nodeType===1&&k.push(t[g]);else k.push.apply(k,y);else A(y,k);if(R){o(R,q,k,l);o.uniqueSort(k)}return k};o.uniqueSort=function(g){if(C){j=n;g.sort(C);if(j)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};o.matches=function(g,h){return o(g,null,null,h)};o.find=function(g,h,k){var l,q;if(!g)return[];for(var p=0,u=m.order.length;p<u;p++){var t=m.order[p];if(q=m.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");l=m.find[t](q,
h,k);if(l!=null){g=g.replace(m.match[t],"");break}}}}l||(l=h.getElementsByTagName("*"));return{set:l,expr:g}};o.filter=function(g,h,k,l){for(var q=g,p=[],u=h,t,y,R=h&&h[0]&&w(h[0]);g&&h.length;){for(var H in m.filter)if((t=m.leftMatch[H].exec(g))!=null&&t[2]){var M=m.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(u===p)p=[];if(m.preFilter[H])if(t=m.preFilter[H](t,u,k,p,l,R)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=u[U])!=null;U++)if(D){I=M(D,t,U,u);var Da=
l^!!I;if(k&&I!=null)if(Da)y=true;else u[U]=false;else if(Da){p.push(D);y=true}}if(I!==v){k||(u=p);g=g.replace(m.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)o.error(g);else break;q=g}return u};o.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var m=o.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,h){var k=typeof h==="string",l=k&&!/\W/.test(h);k=k&&!l;if(l)h=h.toLowerCase();l=0;for(var q=g.length,
p;l<q;l++)if(p=g[l]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[l]=k||p&&p.nodeName.toLowerCase()===h?p||false:p===h}k&&o.filter(h,g,true)},">":function(g,h){var k=typeof h==="string";if(k&&!/\W/.test(h)){h=h.toLowerCase();for(var l=0,q=g.length;l<q;l++){var p=g[l];if(p){k=p.parentNode;g[l]=k.nodeName.toLowerCase()===h?k:false}}}else{l=0;for(q=g.length;l<q;l++)if(p=g[l])g[l]=k?p.parentNode:p.parentNode===h;k&&o.filter(h,g,true)}},"":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=
h=h.toLowerCase();q=b}q("parentNode",h,l,g,p,k)},"~":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,l,g,p,k)}},find:{ID:function(g,h,k){if(typeof h.getElementById!=="undefined"&&!k)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var k=[];h=h.getElementsByName(g[1]);for(var l=0,q=h.length;l<q;l++)h[l].getAttribute("name")===g[1]&&k.push(h[l]);return k.length===0?null:k}},
TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,k,l,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var u;(u=h[p])!=null;p++)if(u)if(q^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))k||l.push(u);else if(k)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&
"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,k,l,q,p){h=g[1].replace(/\\/g,"");if(!p&&m.attrMap[h])g[1]=m.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,k,l,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=o(g[3],null,null,h);else{g=o.filter(g[3],h,k,true^q);k||l.push.apply(l,g);return false}else if(m.match.POS.test(g[0])||m.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);
return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,k){return!!o(k[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===
g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,h){return h===0},last:function(g,h,k,l){return h===l.length-1},even:function(g,h){return h%2===
0},odd:function(g,h){return h%2===1},lt:function(g,h,k){return h<k[3]-0},gt:function(g,h,k){return h>k[3]-0},nth:function(g,h,k){return k[3]-0===h},eq:function(g,h,k){return k[3]-0===h}},filter:{PSEUDO:function(g,h,k,l){var q=h[1],p=m.filters[q];if(p)return p(g,k,h,l);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=h[3];k=0;for(l=h.length;k<l;k++)if(h[k]===g)return false;return true}else o.error("Syntax error, unrecognized expression: "+
q)},CHILD:function(g,h){var k=h[1],l=g;switch(k){case "only":case "first":for(;l=l.previousSibling;)if(l.nodeType===1)return false;if(k==="first")return true;l=g;case "last":for(;l=l.nextSibling;)if(l.nodeType===1)return false;return true;case "nth":k=h[2];var q=h[3];if(k===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var u=0;for(l=p.firstChild;l;l=l.nextSibling)if(l.nodeType===1)l.nodeIndex=++u;p.sizcache=h}g=g.nodeIndex-q;return k===0?g===0:g%k===0&&g/k>=
0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var k=h[1];g=m.attrHandle[k]?m.attrHandle[k](g):g[k]!=null?g[k]:g.getAttribute(k);k=g+"";var l=h[2];h=h[4];return g==null?l==="!=":l==="="?k===h:l==="*="?k.indexOf(h)>=0:l==="~="?(" "+k+" ").indexOf(h)>=0:!h?k&&g!==false:l==="!="?k!==h:l==="^="?
k.indexOf(h)===0:l==="$="?k.substr(k.length-h.length)===h:l==="|="?k===h||k.substr(0,h.length+1)===h+"-":false},POS:function(g,h,k,l){var q=m.setFilters[h[2]];if(q)return q(g,k,h,l)}}},s=m.match.POS;for(var x in m.match){m.match[x]=new RegExp(m.match[x].source+/(?![^\[]*\])(?![^\(]*\))/.source);m.leftMatch[x]=new RegExp(/(^(?:.|\r|\n)*?)/.source+m.match[x].source.replace(/\\(\d+)/g,function(g,h){return"\\"+(h-0+1)}))}var A=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};
try{Array.prototype.slice.call(r.documentElement.childNodes,0)}catch(B){A=function(g,h){h=h||[];if(i.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var k=0,l=g.length;k<l;k++)h.push(g[k]);else for(k=0;g[k];k++)h.push(g[k]);return h}}var C;if(r.documentElement.compareDocumentPosition)C=function(g,h){if(!g.compareDocumentPosition||!h.compareDocumentPosition){if(g==h)j=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===
h?0:1;if(g===0)j=true;return g};else if("sourceIndex"in r.documentElement)C=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)j=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)j=true;return g};else if(r.createRange)C=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)j=true;return g.ownerDocument?-1:1}var k=g.ownerDocument.createRange(),l=h.ownerDocument.createRange();k.setStart(g,0);k.setEnd(g,0);l.setStart(h,0);l.setEnd(h,0);g=k.compareBoundaryPoints(Range.START_TO_END,
l);if(g===0)j=true;return g};(function(){var g=r.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var k=r.documentElement;k.insertBefore(g,k.firstChild);if(r.getElementById(h)){m.find.ID=function(l,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(l[1]))?q.id===l[1]||typeof q.getAttributeNode!=="undefined"&&q.getAttributeNode("id").nodeValue===l[1]?[q]:v:[]};m.filter.ID=function(l,q){var p=typeof l.getAttributeNode!=="undefined"&&l.getAttributeNode("id");
return l.nodeType===1&&p&&p.nodeValue===q}}k.removeChild(g);k=g=null})();(function(){var g=r.createElement("div");g.appendChild(r.createComment(""));if(g.getElementsByTagName("*").length>0)m.find.TAG=function(h,k){k=k.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var l=0;k[l];l++)k[l].nodeType===1&&h.push(k[l]);k=h}return k};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")m.attrHandle.href=function(h){return h.getAttribute("href",
2)};g=null})();r.querySelectorAll&&function(){var g=o,h=r.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){o=function(l,q,p,u){q=q||r;if(!u&&q.nodeType===9&&!w(q))try{return A(q.querySelectorAll(l),p)}catch(t){}return g(l,q,p,u)};for(var k in g)o[k]=g[k];h=null}}();(function(){var g=r.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===
0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){m.order.splice(1,0,"CLASS");m.find.CLASS=function(h,k,l){if(typeof k.getElementsByClassName!=="undefined"&&!l)return k.getElementsByClassName(h[1])};g=null}}})();var E=r.compareDocumentPosition?function(g,h){return g.compareDocumentPosition(h)&16}:function(g,h){return g!==h&&(g.contains?g.contains(h):true)},w=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},fa=function(g,h){var k=[],
l="",q;for(h=h.nodeType?[h]:h;q=m.match.PSEUDO.exec(g);){l+=q[0];g=g.replace(m.match.PSEUDO,"")}g=m.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)o(g,h[q],k);return o.filter(l,k)};c.find=o;c.expr=o.selectors;c.expr[":"]=c.expr.filters;c.unique=o.uniqueSort;c.getText=a;c.isXMLDoc=w;c.contains=E})();var bb=/Until$/,cb=/^(?:parents|prevUntil|prevAll)/,db=/,/;Q=Array.prototype.slice;var Ea=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,i){return!!b.call(e,i,e)===d});else if(b.nodeType)return c.grep(a,
function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Qa.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;c.find(a,this[f],b);if(f>0)for(var i=d;i<b.length;i++)for(var j=0;j<d;j++)if(b[j]===b[i]){b.splice(i--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=
0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ea(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ea(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,i={},j;if(f&&a.length){e=0;for(var n=a.length;e<n;e++){j=a[e];i[j]||(i[j]=c.expr.match.POS.test(j)?c(j,b||this.context):j)}for(;f&&f.ownerDocument&&f!==b;){for(j in i){e=i[j];if(e.jquery?e.index(f)>
-1:c(f).is(e)){d.push({selector:j,elem:f});delete i[j]}}f=f.parentNode}}return d}var o=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(m,s){for(;s&&s.ownerDocument&&s!==b;){if(o?o.index(s)>-1:c(s).is(a))return s;s=s.parentNode}return null})},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),
a);return this.pushStack(pa(a[0])||pa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},
nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);bb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):
e;if((this.length>1||db.test(f))&&cb.test(a))e=e.reverse();return this.pushStack(e,a,Q.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===v||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==
b&&d.push(a);return d}});var Fa=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ga=/(<([\w:]+)[^>]*?)\/>/g,eb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,Ha=/<([\w:]+)/,fb=/<tbody/i,gb=/<|&\w+;/,sa=/checked\s*(?:[^=]|=\s*.checked.)/i,Ia=function(a,b,d){return eb.test(d)?a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],
col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==v)return this.empty().append((this[0]&&this[0].ownerDocument||r).createTextNode(a));return c.getText(this)},
wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?
d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,
false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&
!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Fa,"").replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){qa(this,b);qa(this.find("*"),b.find("*"))}return b},html:function(a){if(a===v)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Fa,""):null;else if(typeof a==="string"&&!/<script/i.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(Ha.exec(a)||
["",""])[1].toLowerCase()]){a=a.replace(Ga,Ia);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var i=c(this),j=i.html();i.empty().append(function(){return a.call(this,e,j)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,
b,f))});else a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(s){return c.nodeName(s,"table")?s.getElementsByTagName("tbody")[0]||s.appendChild(s.ownerDocument.createElement("tbody")):s}var e,i,j=a[0],n=[];if(!c.support.checkClone&&arguments.length===3&&typeof j===
"string"&&sa.test(j))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(j))return this.each(function(s){var x=c(this);a[0]=j.call(this,s,b?x.html():v);x.domManip(a,b,d)});if(this[0]){e=a[0]&&a[0].parentNode&&a[0].parentNode.nodeType===11?{fragment:a[0].parentNode}:ra(a,this,n);if(i=e.fragment.firstChild){b=b&&c.nodeName(i,"tr");for(var o=0,m=this.length;o<m;o++)d.call(b?f(this[o],i):this[o],e.cacheable||this.length>1||o>0?e.fragment.cloneNode(true):e.fragment)}n&&c.each(n,
Ma)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);for(var e=0,i=d.length;e<i;e++){var j=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),j);f=f.concat(j)}return this.pushStack(f,a,d.selector)}});c.each({remove:function(a,b){if(!a||c.filter(a,[this]).length){if(!b&&this.nodeType===1){c.cleanData(this.getElementsByTagName("*"));c.cleanData([this])}this.parentNode&&
this.parentNode.removeChild(this)}},empty:function(){for(this.nodeType===1&&c.cleanData(this.getElementsByTagName("*"));this.firstChild;)this.removeChild(this.firstChild)}},function(a,b){c.fn[a]=function(){return this.each(b,arguments)}});c.extend({clean:function(a,b,d,f){b=b||r;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||r;var e=[];c.each(a,function(i,j){if(typeof j==="number")j+="";if(j){if(typeof j==="string"&&!gb.test(j))j=b.createTextNode(j);else if(typeof j===
"string"){j=j.replace(Ga,Ia);var n=(Ha.exec(j)||["",""])[1].toLowerCase(),o=F[n]||F._default,m=o[0];i=b.createElement("div");for(i.innerHTML=o[1]+j+o[2];m--;)i=i.lastChild;if(!c.support.tbody){m=fb.test(j);n=n==="table"&&!m?i.firstChild&&i.firstChild.childNodes:o[1]==="<table>"&&!m?i.childNodes:[];for(o=n.length-1;o>=0;--o)c.nodeName(n[o],"tbody")&&!n[o].childNodes.length&&n[o].parentNode.removeChild(n[o])}!c.support.leadingWhitespace&&V.test(j)&&i.insertBefore(b.createTextNode(V.exec(j)[0]),i.firstChild);
j=c.makeArray(i.childNodes)}if(j.nodeType)e.push(j);else e=c.merge(e,j)}});if(d)for(a=0;e[a];a++)if(f&&c.nodeName(e[a],"script")&&(!e[a].type||e[a].type.toLowerCase()==="text/javascript"))f.push(e[a].parentNode?e[a].parentNode.removeChild(e[a]):e[a]);else{e[a].nodeType===1&&e.splice.apply(e,[a+1,0].concat(c.makeArray(e[a].getElementsByTagName("script"))));d.appendChild(e[a])}return e},cleanData:function(a){for(var b=0,d;(d=a[b])!=null;b++){c.event.remove(d);c.removeData(d)}}});var hb=/z-?index|font-?weight|opacity|zoom|line-?height/i,
Ja=/alpha\([^)]*\)/,Ka=/opacity=([^)]*)/,ga=/float/i,ha=/-([a-z])/ig,ib=/([A-Z])/g,jb=/^-?\d+(?:px)?$/i,kb=/^-?\d/,lb={position:"absolute",visibility:"hidden",display:"block"},mb=["Left","Right"],nb=["Top","Bottom"],ob=r.defaultView&&r.defaultView.getComputedStyle,La=c.support.cssFloat?"cssFloat":"styleFloat",ia=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===v)return c.curCSS(d,f);if(typeof e==="number"&&!hb.test(f))e+="px";c.style(d,f,e)})};
c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return v;if((b==="width"||b==="height")&&parseFloat(d)<0)d=v;var f=a.style||a,e=d!==v;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=Ja.test(a)?a.replace(Ja,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Ka.exec(f.filter)[1])/100+"":""}if(ga.test(b))b=La;b=b.replace(ha,ia);if(e)f[b]=d;return f[b]},css:function(a,
b,d,f){if(b==="width"||b==="height"){var e,i=b==="width"?mb:nb;function j(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(i,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,"border"+this+"Width",true))||0})}a.offsetWidth!==0?j():c.swap(a,lb,j);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&
a.currentStyle){f=Ka.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ga.test(b))b=La;if(!d&&e&&e[b])f=e[b];else if(ob){if(ga.test(b))b="float";b=b.replace(ib,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ha,ia);f=a.currentStyle[b]||a.currentStyle[d];if(!jb.test(f)&&kb.test(f)){b=e.left;var i=a.runtimeStyle.left;a.runtimeStyle.left=
a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=i}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var pb=
J(),qb=/<script(.|\s)*?\/script>/gi,rb=/select|textarea/i,sb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ja=/\?/,tb=/(\?|&)_=.*?(&|$)/,ub=/^(\w+:)?\/\/([^\/?#]+)/,vb=/%20/g;c.fn.extend({_load:c.fn.load,load:function(a,b,d){if(typeof a!=="string")return this._load(a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=
c.param(b,c.ajaxSettings.traditional);f="POST"}var i=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(j,n){if(n==="success"||n==="notmodified")i.html(e?c("<div />").append(j.responseText.replace(qb,"")).find(e):j.responseText);d&&i.each(d,[j.responseText,n,j])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&
(this.checked||rb.test(this.nodeName)||sb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,
b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:z.XMLHttpRequest&&(z.location.protocol!=="file:"||!z.ActiveXObject)?function(){return new z.XMLHttpRequest}:
function(){try{return new z.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&e.success.call(o,n,j,w);e.global&&f("ajaxSuccess",[w,e])}function d(){e.complete&&e.complete.call(o,w,j);e.global&&f("ajaxComplete",[w,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}
function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),i,j,n,o=a&&a.context||e,m=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(m==="GET")N.test(e.url)||(e.url+=(ja.test(e.url)?"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||
N.test(e.url))){i=e.jsonpCallback||"jsonp"+pb++;if(e.data)e.data=(e.data+"").replace(N,"="+i+"$1");e.url=e.url.replace(N,"="+i+"$1");e.dataType="script";z[i]=z[i]||function(q){n=q;b();d();z[i]=v;try{delete z[i]}catch(p){}A&&A.removeChild(B)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===false&&m==="GET"){var s=J(),x=e.url.replace(tb,"$1_="+s+"$2");e.url=x+(x===e.url?(ja.test(e.url)?"&":"?")+"_="+s:"")}if(e.data&&m==="GET")e.url+=(ja.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&
c.event.trigger("ajaxStart");s=(s=ub.exec(e.url))&&(s[1]&&s[1]!==location.protocol||s[2]!==location.host);if(e.dataType==="script"&&m==="GET"&&s){var A=r.getElementsByTagName("head")[0]||r.documentElement,B=r.createElement("script");B.src=e.url;if(e.scriptCharset)B.charset=e.scriptCharset;if(!i){var C=false;B.onload=B.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;b();d();B.onload=B.onreadystatechange=null;A&&B.parentNode&&
A.removeChild(B)}}}A.insertBefore(B,A.firstChild);return v}var E=false,w=e.xhr();if(w){e.username?w.open(m,e.url,e.async,e.username,e.password):w.open(m,e.url,e.async);try{if(e.data||a&&a.contentType)w.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[e.url]);c.etag[e.url]&&w.setRequestHeader("If-None-Match",c.etag[e.url])}s||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",
e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(fa){}if(e.beforeSend&&e.beforeSend.call(o,w,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");w.abort();return false}e.global&&f("ajaxSend",[w,e]);var g=w.onreadystatechange=function(q){if(!w||w.readyState===0||q==="abort"){E||d();E=true;if(w)w.onreadystatechange=c.noop}else if(!E&&w&&(w.readyState===4||q==="timeout")){E=true;w.onreadystatechange=c.noop;j=q==="timeout"?"timeout":!c.httpSuccess(w)?
"error":e.ifModified&&c.httpNotModified(w,e.url)?"notmodified":"success";var p;if(j==="success")try{n=c.httpData(w,e.dataType,e)}catch(u){j="parsererror";p=u}if(j==="success"||j==="notmodified")i||b();else c.handleError(e,w,j,p);d();q==="timeout"&&w.abort();if(e.async)w=null}};try{var h=w.abort;w.abort=function(){w&&h.call(w);g("abort")}}catch(k){}e.async&&e.timeout>0&&setTimeout(function(){w&&!E&&g("timeout")},e.timeout);try{w.send(m==="POST"||m==="PUT"||m==="DELETE"?e.data:null)}catch(l){c.handleError(e,
w,null,l);d()}e.async||g();return w}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=
f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(j,n){if(c.isArray(n))c.each(n,
function(o,m){b?f(j,m):d(j+"["+(typeof m==="object"||c.isArray(m)?o:"")+"]",m)});else!b&&n!=null&&typeof n==="object"?c.each(n,function(o,m){d(j+"["+o+"]",m)}):f(j,n)}function f(j,n){n=c.isFunction(n)?n():n;e[e.length]=encodeURIComponent(j)+"="+encodeURIComponent(n)}var e=[];if(b===v)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var i in a)d(i,a[i]);return e.join("&").replace(vb,"+")}});var ka={},wb=/toggle|show|hide/,xb=/^([+-]=)?([\d+-.]+)(.*)$/,
W,ta=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(ka[d])f=ka[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();
ka[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&
c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var i=c.extend({},e),j,n=this.nodeType===1&&c(this).is(":hidden"),
o=this;for(j in a){var m=j.replace(ha,ia);if(j!==m){a[m]=a[j];delete a[j];j=m}if(a[j]==="hide"&&n||a[j]==="show"&&!n)return i.complete.call(this);if((j==="height"||j==="width")&&this.style){i.display=c.css(this,"display");i.overflow=this.style.overflow}if(c.isArray(a[j])){(i.specialEasing=i.specialEasing||{})[j]=a[j][1];a[j]=a[j][0]}}if(i.overflow!=null)this.style.overflow="hidden";i.curAnim=c.extend({},a);c.each(a,function(s,x){var A=new c.fx(o,i,s);if(wb.test(x))A[x==="toggle"?n?"show":"hide":x](a);
else{var B=xb.exec(x),C=A.cur(true)||0;if(B){x=parseFloat(B[2]);var E=B[3]||"px";if(E!=="px"){o.style[s]=(x||1)+E;C=(x||1)/A.cur(true)*C;o.style[s]=C+E}if(B[1])x=(B[1]==="-="?-1:1)*x+C;A.custom(C,x,E)}else A.custom(C,x,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",
1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration==="number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,
b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==
null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(i){return e.step(i)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop===
"width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=
this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=
c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=
null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in r.documentElement?function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),
f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(s){c.offset.setOffset(this,a,s)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=
b,e=b.ownerDocument,i,j=e.documentElement,n=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var o=b.offsetTop,m=b.offsetLeft;(b=b.parentNode)&&b!==n&&b!==j;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;i=e?e.getComputedStyle(b,null):b.currentStyle;o-=b.scrollTop;m-=b.scrollLeft;if(b===d){o+=b.offsetTop;m+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){o+=parseFloat(i.borderTopWidth)||
0;m+=parseFloat(i.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&i.overflow!=="visible"){o+=parseFloat(i.borderTopWidth)||0;m+=parseFloat(i.borderLeftWidth)||0}f=i}if(f.position==="relative"||f.position==="static"){o+=n.offsetTop;m+=n.offsetLeft}if(c.offset.supportsFixedPosition&&f.position==="fixed"){o+=Math.max(j.scrollTop,n.scrollTop);m+=Math.max(j.scrollLeft,n.scrollLeft)}return{top:o,left:m}};c.offset={initialize:function(){var a=r.body,b=r.createElement("div"),
d,f,e,i=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);
d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i;a.removeChild(b);c.offset.initialize=c.noop},
bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),i=parseInt(c.curCSS(a,"top",true),10)||0,j=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,d,e);d={top:b.top-e.top+i,left:b.left-
e.left+j};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=
this.offsetParent||r.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],i;if(!e)return null;if(f!==v)return this.each(function(){if(i=ua(this))i.scrollTo(!a?f:c(i).scrollLeft(),a?f:c(i).scrollTop());else this[d]=f});else return(i=ua(e))?"pageXOffset"in i?i[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&i.document.documentElement[d]||i.document.body[d]:e[d]}});
c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(i){var j=c(this);j[d](f.call(this,i,j[d]()))});return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||
e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===v?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});z.jQuery=z.$=c})(window);
|
client/extensions/woocommerce/app/products/product-header.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { localize } from 'i18n-calypso';
import Gridicon from 'gridicons';
import { isObject } from 'lodash';
/**
* Internal dependencies
*/
import ActionHeader from 'woocommerce/components/action-header';
import Button from 'components/button';
import { getLink } from 'woocommerce/lib/nav-utils';
function renderViewButton( product, label ) {
const url = product && product.permalink;
return (
// TODO: Do more to validate this URL?
<Button
borderless
className="products__header-view-link"
href={ url }
target="_blank"
rel="noopener noreferrer"
>
<Gridicon icon="visible" />
<span>{ label }</span>
</Button>
);
}
function renderTrashButton( onTrash, isBusy, label ) {
return (
onTrash && (
<Button borderless scary onClick={ onTrash ? onTrash : undefined }>
<Gridicon icon="trash" />
<span>{ label } </span>
</Button>
)
);
}
function renderSaveButton( onSave, isBusy, label ) {
const saveExists = 'undefined' !== typeof onSave;
const saveDisabled = false === onSave;
return (
saveExists && (
<Button
primary
onClick={ onSave ? onSave : undefined }
disabled={ saveDisabled }
busy={ isBusy }
>
{ label }
</Button>
)
);
}
const ProductHeader = ( { viewEnabled, onTrash, onSave, isBusy, translate, site, product } ) => {
const existing = product && ! isObject( product.id );
const viewButton = viewEnabled && renderViewButton( product, translate( 'View' ) );
const trashButton = renderTrashButton( onTrash, isBusy, translate( 'Delete' ) );
const saveLabel = existing ? translate( 'Update' ) : translate( 'Save & Publish' );
const saveButton = renderSaveButton( onSave, isBusy, saveLabel );
const currentCrumb =
product && existing ? (
<span>{ translate( 'Edit Product' ) }</span>
) : (
<span>{ translate( 'Add New' ) }</span>
);
const breadcrumbs = [
<a href={ getLink( '/store/products/:site/', site ) }> { translate( 'Products' ) } </a>,
currentCrumb,
];
return (
<ActionHeader breadcrumbs={ breadcrumbs } primaryLabel={ saveLabel }>
{ trashButton }
{ viewButton }
{ saveButton }
</ActionHeader>
);
};
ProductHeader.propTypes = {
site: PropTypes.shape( {
slug: PropTypes.string,
} ),
product: PropTypes.shape( {
id: PropTypes.oneOfType( [ PropTypes.number, PropTypes.object ] ),
} ),
viewEnabled: PropTypes.bool,
onTrash: PropTypes.func,
onSave: PropTypes.oneOfType( [ PropTypes.func, PropTypes.bool ] ),
};
export default localize( ProductHeader );
|
src/svg-icons/notification/sync.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationSync = (props) => (
<SvgIcon {...props}>
<path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/>
</SvgIcon>
);
NotificationSync = pure(NotificationSync);
NotificationSync.displayName = 'NotificationSync';
export default NotificationSync;
|
components/catalog/statistics.js | sgmap/inspire | import React from 'react'
import PropTypes from 'prop-types'
import {translate} from 'react-i18next'
import {get} from 'lodash'
import Counter from '../counter'
import Percent from '../percent'
import Pie from './pie'
const Statistics = ({metrics, t}) => {
const openness = get(metrics, 'datasets.partitions.openness.yes', 0)
const download = get(metrics, 'datasets.partitions.download.yes', 0)
return (
<div className='container'>
<div className='block'>
<h3>
{t('details.statistics.recordsCount')}
</h3>
<Counter
value={metrics.records.totalCount}
/>
</div>
<div className='block'>
<h3>
{t('details.statistics.openDataPercent')}
</h3>
<Percent
value={openness}
total={metrics.datasets.totalCount}
/>
</div>
<div className='block'>
<h3>
{t('details.statistics.downloadablePercent')}
</h3>
<Percent
value={download}
total={metrics.datasets.totalCount}
/>
</div>
{metrics.records.partitions.recordType && (
<div className='block'>
<h3>
{t('details.statistics.recordTypeChart')}
</h3>
<div>
<Pie data={metrics.records.partitions.recordType} />
</div>
</div>
)}
{metrics.datasets.partitions.dataType && (
<div className='block'>
<h3>
{t('details.statistics.dataTypeChart')}
</h3>
<div>
<Pie data={metrics.datasets.partitions.dataType} />
</div>
</div>
)}
{metrics.datasets.partitions.metadataType && (
<div className='block'>
<h3>
{t('details.statistics.metadataTypeChart')}
</h3>
<div>
<Pie data={metrics.datasets.partitions.metadataType} />
</div>
</div>
)}
<style jsx>{`
@import 'colors';
.container {
display: flex;
flex-wrap: wrap;
margin: 1em -0.6em 0 -0.6em;
}
.block {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
height: 200px;
padding: 2em;
border: 1px solid $lightgrey;
border-radius: 2px;
margin: 0 0.6em 1em 0.6em;
text-align: center;
max-width: calc(100% - 1.2em);
width: calc(33.33% - 1.2em);
@media (max-width: 960px) {
width: calc(50% - 1.2em);
}
@media (max-width: 767px) {
width: calc(100% - 1.2em);
}
@media (max-width: 551px) {
height: auto;
}
div {
display: flex;
overflow: hidden;
}
}
`}</style>
</div>
)
}
Statistics.propTypes = {
metrics: PropTypes.shape({
records: PropTypes.shape({
totalCount: PropTypes.number.isRequired
}).isRequired
}).isRequired,
t: PropTypes.func.isRequired
}
export default translate('catalogs')(Statistics)
|
Examples/UIExplorer/ListViewGridLayoutExample.js | dvcrn/react-native | /**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* 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 NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK 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.
*
* @flow
*/
'use strict';
var React = require('react-native');
var {
Image,
ListView,
TouchableHighlight,
StyleSheet,
Text,
View,
} = React;
var THUMB_URLS = [
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-ash3/t39.1997/p128x128/851549_767334479959628_274486868_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851561_767334496626293_1958532586_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-ash3/t39.1997/p128x128/851579_767334503292959_179092627_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851589_767334513292958_1747022277_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851563_767334559959620_1193692107_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851593_767334566626286_1953955109_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851591_767334523292957_797560749_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851567_767334529959623_843148472_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851548_767334489959627_794462220_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851575_767334539959622_441598241_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-ash3/t39.1997/p128x128/851573_767334549959621_534583464_n.png',
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851583_767334573292952_1519550680_n.png',
];
var ListViewGridLayoutExample = React.createClass({
statics: {
title: '<ListView> - Grid Layout',
description: 'Flexbox grid layout.'
},
getInitialState: function() {
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
return {
dataSource: ds.cloneWithRows(this._genRows({})),
};
},
_pressData: ({}: {[key: number]: boolean}),
componentWillMount: function() {
this._pressData = {};
},
render: function() {
return (
// ListView wraps ScrollView and so takes on its properties.
// With that in mind you can use the ScrollView's contentContainerStyle prop to style the items.
<ListView
contentContainerStyle={styles.list}
dataSource={this.state.dataSource}
renderRow={this._renderRow}
/>
);
},
_renderRow: function(rowData: string, sectionID: number, rowID: number) {
var rowHash = Math.abs(hashCode(rowData));
var imgSource = {
uri: THUMB_URLS[rowHash % THUMB_URLS.length],
};
return (
<TouchableHighlight onPress={() => this._pressRow(rowID)} underlayColor="transparent">
<View>
<View style={styles.row}>
<Image style={styles.thumb} source={imgSource} />
<Text style={styles.text}>
{rowData}
</Text>
</View>
</View>
</TouchableHighlight>
);
},
_genRows: function(pressData: {[key: number]: boolean}): Array<string> {
var dataBlob = [];
for (var ii = 0; ii < 100; ii++) {
var pressedText = pressData[ii] ? ' (X)' : '';
dataBlob.push('Cell ' + ii + pressedText);
}
return dataBlob;
},
_pressRow: function(rowID: number) {
this._pressData[rowID] = !this._pressData[rowID];
this.setState({dataSource: this.state.dataSource.cloneWithRows(
this._genRows(this._pressData)
)});
},
});
/* eslint no-bitwise: 0 */
var hashCode = function(str) {
var hash = 15;
for (var ii = str.length - 1; ii >= 0; ii--) {
hash = ((hash << 5) - hash) + str.charCodeAt(ii);
}
return hash;
};
var styles = StyleSheet.create({
list: {
justifyContent: 'space-around',
flexDirection: 'row',
flexWrap: 'wrap'
},
row: {
justifyContent: 'center',
padding: 5,
margin: 3,
width: 100,
height: 100,
backgroundColor: '#F6F6F6',
alignItems: 'center',
borderWidth: 1,
borderRadius: 5,
borderColor: '#CCC'
},
thumb: {
width: 64,
height: 64
},
text: {
flex: 1,
marginTop: 5,
fontWeight: 'bold'
},
});
module.exports = ListViewGridLayoutExample;
|
webpack.config.development.js | aidatorajiro/Ultimate-Development | /* eslint-disable max-len */
/**
* Build config for development process that uses Hot-Module-Replacement
* https://webpack.js.org/concepts/hot-module-replacement/
*/
import path from 'path';
import webpack from 'webpack';
import merge from 'webpack-merge';
import { spawn } from 'child_process';
import baseConfig from './webpack.config.base';
const port = process.env.PORT || 3000;
const publicPath = `http://localhost:${port}/dist`;
export default merge(baseConfig, {
devtool: 'inline-source-map',
entry: [
'react-hot-loader/patch',
`webpack-dev-server/client?http://localhost:${port}/`,
'webpack/hot/only-dev-server',
path.join(__dirname, 'app/index.js'),
],
output: {
publicPath: `http://localhost:${port}/dist/`
},
module: {
rules: [
{
test: /\.global\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
sourceMap: true,
},
}
]
},
{
test: /^((?!\.global).)*\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]__[local]__[hash:base64:5]',
}
},
]
},
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
}
},
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
}
}
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/octet-stream'
}
}
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: 'file-loader',
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'image/svg+xml',
}
}
},
{
test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/,
use: 'url-loader',
}
]
},
plugins: [
// https://webpack.js.org/concepts/hot-module-replacement/
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
/**
* Create global constants which can be configured at compile time.
*
* Useful for allowing different behaviour between development builds and
* release builds
*
* NODE_ENV should be production so that modules do not perform certain
* development checks
*/
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
}),
// turn debug mode on.
new webpack.LoaderOptionsPlugin({
debug: true
}),
],
/**
* https://github.com/chentsulin/webpack-target-electron-renderer#how-this-module-works
*/
target: 'electron-renderer',
devServer: {
port,
hot: true,
inline: false,
historyApiFallback: true,
contentBase: path.join(__dirname, 'dist'),
publicPath,
setup() {
if (process.env.START_HOT) {
spawn('npm', ['run', 'start-hot'], { shell: true, env: process.env, stdio: 'inherit' })
.on('close', code => process.exit(code))
.on('error', spawnError => console.error(spawnError));
}
}
},
});
|
docs/src/pages/components/transitions/SimpleSlide.js | lgollut/material-ui | import React from 'react';
import Switch from '@material-ui/core/Switch';
import Paper from '@material-ui/core/Paper';
import Slide from '@material-ui/core/Slide';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
root: {
height: 180,
},
wrapper: {
width: 100 + theme.spacing(2),
},
paper: {
zIndex: 1,
position: 'relative',
margin: theme.spacing(1),
},
svg: {
width: 100,
height: 100,
},
polygon: {
fill: theme.palette.common.white,
stroke: theme.palette.divider,
strokeWidth: 1,
},
}));
export default function SimpleSlide() {
const classes = useStyles();
const [checked, setChecked] = React.useState(false);
const handleChange = () => {
setChecked((prev) => !prev);
};
return (
<div className={classes.root}>
<div className={classes.wrapper}>
<FormControlLabel
control={<Switch checked={checked} onChange={handleChange} />}
label="Show"
/>
<Slide direction="up" in={checked} mountOnEnter unmountOnExit>
<Paper elevation={4} className={classes.paper}>
<svg className={classes.svg}>
<polygon points="0,100 50,00, 100,100" className={classes.polygon} />
</svg>
</Paper>
</Slide>
</div>
</div>
);
}
|
definitions/npm/react-toastify_v3.2.x/test_react-toastify_v3.2.x.js | orlandoc01/flow-typed | import React from 'react'
import { ToastContainer, toast, style } from 'react-toastify'
const toastContent = <div>Toast!</div>
// $ExpectError
toast(toastContent, { type: toast.TYPE.SUCCES })
toast(toastContent, { type: toast.TYPE.SUCCESS })
// $ExpectError
toast.success(toastContent, { onOpen: false })
toast.success(toastContent, { onOpen: () => console.log('open') })
// $ExpectError
toast.info(toastContent, { onClose: false })
toast.info(toastContent, { onClose: () => console.log('close') })
// $ExpectError
toast.warn(toastContent, { onOpen: false })
toast.warn(toastContent, { onOpen: () => console.log('open') })
// $ExpectError
toast.error(toastContent, { onClose: false })
toast.error(toastContent, { onClose: () => console.log('close') })
// $ExpectError
const isActiveBad: number = toast.isActive(1)
const isActiveGood: boolean = toast.isActive(1)
// $ExpectError
toast.dismiss('1')
toast.dismiss()
toast.dismiss(1)
// $ExpectError
toast.update()
toast.update(1)
toast.update(1, { render: toastContent })
// $ExpectError
style({ width: 100 })
style({ width: '100px' })
function BadToast() {
// $ExpectError
return <ToastContainer position={toast.POSITION.TOPP_RIGHT} />
}
function GoodToast() {
return (
<ToastContainer
newestOnTop
style={{}}
toastClassName="toasty"
pauseOnHover
closeOnClick
autoClose={false}
position={toast.POSITION.TOP_LEFT}
closeButton={false}
progressClassName="progress"
className="classes"
bodyClassName="body"
hideProgressBar
transition={false}
/>
)
}
|
files/rxjs/2.3.22/rx.compat.js | ntd/jsdelivr | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise,
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var deprecate = Rx.helpers.deprecate = function (name, alternative) {
/*if (typeof console !== "undefined" && typeof console.warn === "function") {
console.warn(name + ' is deprecated, use ' + alternative + ' instead.', new Error('').stack);
}*/
}
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
// Fix for Tessel
if (!propertyIsEnumerable) {
propertyIsEnumerable = objectProto.propertyIsEnumerable = function (key) {
for (var k in this) { if (k === key) { return true; } }
return false;
};
}
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
result[i] = fun.call(thisp, self[i], i, object);
}
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return {}.toString.call(arg) == arrayClass;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n != Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); }
var s = state;
var id = root.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
root.clearInterval(id);
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dueTime);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new Error('No concurrency detected!');
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
var onGlobalPostMessage = function (event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
var notification = new Notification('E');
notification.exception = e;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch (err) {
observer.onError(err);
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch (err) {
observer.onError(err);
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe(observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
}, source);
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
}, source);
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var source = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return source.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
}, source);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._s.charAt(this._i++);
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._a[this._i++];
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
var list = Object(iterable), it = getIterable(list);
return new AnonymousObservable(function (observer) {
var i = 0;
return scheduler.scheduleRecursive(function (self) {
var next;
try {
next = it.next();
} catch (e) {
observer.onError(e);
return;
}
if (next.done) {
observer.onCompleted();
return;
}
var result = next.value;
if (mapFn && isFunction(mapFn)) {
try {
result = mapFn.call(thisArg, result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
deprecate('fromArray', 'from');
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
return observableOf(null, arguments);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
return observableOf(scheduler, slice.call(arguments, 1));
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/** @deprecated use return or just */
Observable.returnValue = function () {
deprecate('returnValue', 'return or just');
return observableReturn.apply(null, arguments);
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* @deprecated use #catch or #catchError instead.
*/
observableProto.catchException = function (handlerOrSecond) {
deprecate('catchException', 'catch or catchError');
return this.catchError(handlerOrSecond);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = function () {
return enumerableOf(argsOrArray(arguments, 0)).catchError();
};
/**
* @deprecated use #catch or #catchError instead.
*/
Observable.catchException = function () {
deprecate('catchException', 'catch or catchError');
return observableCatch.apply(null, arguments);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
return enumerableOf(argsOrArray(arguments, 0)).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = function () {
return this.merge(1);
};
/** @deprecated Use `concatAll` instead. */
observableProto.concatObservable = function () {
deprecate('concatObservable', 'concatAll');
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); }
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [];
function subscribe(xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
isPromise(xs) && (xs = observableFromPromise(xs));
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(subscription);
if (q.length > 0) {
subscribe(q.shift());
} else {
activeCount--;
isStopped && activeCount === 0 && observer.onCompleted();
}
}));
}
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
activeCount === 0 && observer.onCompleted();
}));
return group;
}, sources);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && observer.onCompleted();
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
group.length === 1 && observer.onCompleted();
}));
return group;
}, sources);
};
/**
* @deprecated use #mergeAll instead.
*/
observableProto.mergeObservable = function () {
deprecate('mergeObservable', 'mergeAll');
return this.mergeAll.apply(this, arguments);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
observer.onError.bind(observer),
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
}, source);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, first);
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0), first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; }
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
return new AnonymousObservable(this.subscribe.bind(this), this);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (e) {
observer.onError(e);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (e) {
observer.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, this);
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
if (onError) {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
}
observer.onError(err);
}, function () {
if (onCompleted) {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
}
observer.onCompleted();
});
}, this);
};
/** @deprecated use #do or #tap instead. */
observableProto.doAction = function () {
deprecate('doAction', 'do or tap');
return this.tap.apply(this, arguments);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
!hasValue && hasSeed && observer.onNext(seed);
observer.onCompleted();
}
);
}, source);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && observer.onNext(q.shift());
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableOf([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while (q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
}, source);
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new Error(argumentOutOfRange); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new Error(argumentOutOfRange); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
!found && observer.onNext(defaultValue);
observer.onCompleted();
});
}, this);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
hashSet.push(key) && observer.onNext(x);
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
}, this);
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var selectorFn = isFunction(selector) ? selector : function () { return selector; },
source = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return source.subscribe(function (value) {
var result;
try {
result = selectorFn.call(thisArg, value, count++, source);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} prop The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (prop) {
return this.map(function (x) { return x[prop]; });
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, source).mergeAll();
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new Error(argumentOutOfRange); }
var source = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
running && observer.onNext(x);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new RangeError(argumentOutOfRange); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
observer.onNext(x);
remaining === 0 && observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return source.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, source);
} catch (e) {
observer.onError(e);
return;
}
shouldRun && observer.onNext(value);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
}, source);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
}, source);
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
!noError && this.dispose();
}
};
AutoDetachObserverPrototype.error = function (err) {
try {
this.observer.onError(err);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
|
app/react-icons/fa/opera.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaOpera extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m33.3 5.1q-3.7-2.5-8-2.5-3.4 0-6.5 1.7t-5.4 4.4q-1.7 2.1-2.7 4.9t-1 5.9v1q0.1 3.1 1 5.9t2.7 4.9q2.3 2.8 5.4 4.4t6.5 1.7q4.3 0 8-2.5-2.7 2.4-6.1 3.8t-7.2 1.3q-0.6 0-1 0-3.9-0.2-7.4-1.9t-6.1-4.3-4-6.2-1.5-7.6q0-4.1 1.6-7.8t4.2-6.4 6.4-4.2 7.8-1.6h0.1q3.7 0 7.1 1.4t6.1 3.7z m6.7 14.9q0 4.3-1.7 8.1t-4.8 6.6q-2.3 1.4-4.9 1.4-3.1 0-5.7-1.9 3.4-1.2 5.6-5.2t2.3-9q0-5.1-2.3-9t-5.6-5.2q2.7-1.9 5.7-1.9 2.6 0 5 1.5 3 2.7 4.7 6.5t1.7 8.1z"/></g>
</IconBase>
);
}
}
|
server/node_modules/react-dom/lib/ReactCompositeComponent.js | Atanasov86/Car-System | /**
* 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'),
_assign = require('object-assign');
var React = require('react/lib/React');
var ReactComponentEnvironment = require('./ReactComponentEnvironment');
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
var ReactErrorUtils = require('./ReactErrorUtils');
var ReactInstanceMap = require('./ReactInstanceMap');
var ReactInstrumentation = require('./ReactInstrumentation');
var ReactNodeTypes = require('./ReactNodeTypes');
var ReactReconciler = require('./ReactReconciler');
if (process.env.NODE_ENV !== 'production') {
var checkReactTypeSpec = require('./checkReactTypeSpec');
}
var emptyObject = require('fbjs/lib/emptyObject');
var invariant = require('fbjs/lib/invariant');
var shallowEqual = require('fbjs/lib/shallowEqual');
var shouldUpdateReactComponent = require('./shouldUpdateReactComponent');
var warning = require('fbjs/lib/warning');
var CompositeTypes = {
ImpureClass: 0,
PureClass: 1,
StatelessFunctional: 2
};
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function () {
var Component = ReactInstanceMap.get(this)._currentElement.type;
var element = Component(this.props, this.context, this.updater);
warnIfInvalidElement(Component, element);
return element;
};
function warnIfInvalidElement(Component, element) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(element === null || element === false || React.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0;
}
}
function shouldConstruct(Component) {
return !!(Component.prototype && Component.prototype.isReactComponent);
}
function isPureComponent(Component) {
return !!(Component.prototype && Component.prototype.isPureReactComponent);
}
// Separated into a function to contain deoptimizations caused by try/finally.
function measureLifeCyclePerf(fn, debugID, timerType) {
if (debugID === 0) {
// Top-level wrappers (see ReactMount) and empty components (see
// ReactDOMEmptyComponent) are invisible to hooks and devtools.
// Both are implementation details that should go away in the future.
return fn();
}
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType);
try {
return fn();
} finally {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType);
}
}
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* -----------------------------------------------------------------------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1;
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponent = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function (element) {
this._currentElement = element;
this._rootNodeID = 0;
this._compositeType = null;
this._instance = null;
this._hostParent = null;
this._hostContainerInfo = null;
// See ReactUpdateQueue
this._updateBatchNumber = null;
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedNodeType = null;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._topLevelWrapper = null;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
// ComponentWillUnmount shall only be called once
this._calledComponentWillUnmount = false;
if (process.env.NODE_ENV !== 'production') {
this._warnedAboutRefsInRender = false;
}
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} hostParent
* @param {?object} hostContainerInfo
* @param {?object} context
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
var _this = this;
this._context = context;
this._mountOrder = nextMountID++;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var publicProps = this._currentElement.props;
var publicContext = this._processContext(context);
var Component = this._currentElement.type;
var updateQueue = transaction.getUpdateQueue();
// Initialize the public class
var doConstruct = shouldConstruct(Component);
var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue);
var renderedElement;
// Support functional components
if (!doConstruct && (inst == null || inst.render == null)) {
renderedElement = inst;
warnIfInvalidElement(Component, renderedElement);
!(inst === null || inst === false || React.isValidElement(inst)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0;
inst = new StatelessComponent(Component);
this._compositeType = CompositeTypes.StatelessFunctional;
} else {
if (isPureComponent(Component)) {
this._compositeType = CompositeTypes.PureClass;
} else {
this._compositeType = CompositeTypes.ImpureClass;
}
}
if (process.env.NODE_ENV !== 'production') {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
if (inst.render == null) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0;
}
var propsMutated = inst.props !== publicProps;
var componentName = Component.displayName || Component.name || 'Component';
process.env.NODE_ENV !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", componentName, componentName) : void 0;
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
inst.updater = updateQueue;
this._instance = inst;
// Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this);
if (process.env.NODE_ENV !== 'production') {
// Since plain JS classes are defined without any special initialization
// logic, we can not catch common errors early. Therefore, we have to
// catch them here, at initialization time, instead.
process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved || inst.state, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0;
}
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
var markup;
if (inst.unstable_handleError) {
markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context);
} else {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
}
if (inst.componentDidMount) {
if (process.env.NODE_ENV !== 'production') {
transaction.getReactMountReady().enqueue(function () {
measureLifeCyclePerf(function () {
return inst.componentDidMount();
}, _this._debugID, 'componentDidMount');
});
} else {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
}
return markup;
},
_constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) {
if (process.env.NODE_ENV !== 'production') {
ReactCurrentOwner.current = this;
try {
return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue);
} finally {
ReactCurrentOwner.current = null;
}
} else {
return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue);
}
},
_constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) {
var Component = this._currentElement.type;
if (doConstruct) {
if (process.env.NODE_ENV !== 'production') {
return measureLifeCyclePerf(function () {
return new Component(publicProps, publicContext, updateQueue);
}, this._debugID, 'ctor');
} else {
return new Component(publicProps, publicContext, updateQueue);
}
}
// This can still be an instance in case of factory components
// but we'll count this as time spent rendering as the more common case.
if (process.env.NODE_ENV !== 'production') {
return measureLifeCyclePerf(function () {
return Component(publicProps, publicContext, updateQueue);
}, this._debugID, 'render');
} else {
return Component(publicProps, publicContext, updateQueue);
}
},
performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) {
var markup;
var checkpoint = transaction.checkpoint();
try {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
} catch (e) {
// Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint
transaction.rollback(checkpoint);
this._instance.unstable_handleError(e);
if (this._pendingStateQueue) {
this._instance.state = this._processPendingState(this._instance.props, this._instance.context);
}
checkpoint = transaction.checkpoint();
this._renderedComponent.unmountComponent(true);
transaction.rollback(checkpoint);
// Try again - we've informed the component about the error, so they can render an error message this time.
// If this throws again, the error will bubble up (and can be caught by a higher error boundary).
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
}
return markup;
},
performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) {
var inst = this._instance;
var debugID = 0;
if (process.env.NODE_ENV !== 'production') {
debugID = this._debugID;
}
if (inst.componentWillMount) {
if (process.env.NODE_ENV !== 'production') {
measureLifeCyclePerf(function () {
return inst.componentWillMount();
}, debugID, 'componentWillMount');
} else {
inst.componentWillMount();
}
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
// If not a stateless component, we now render
if (renderedElement === undefined) {
renderedElement = this._renderValidatedComponent();
}
var nodeType = ReactNodeTypes.getType(renderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
);
this._renderedComponent = child;
var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), debugID);
if (process.env.NODE_ENV !== 'production') {
if (debugID !== 0) {
var childDebugIDs = child._debugID !== 0 ? [child._debugID] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
}
return markup;
},
getHostNode: function () {
return ReactReconciler.getHostNode(this._renderedComponent);
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (safely) {
if (!this._renderedComponent) {
return;
}
var inst = this._instance;
if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) {
inst._calledComponentWillUnmount = true;
if (safely) {
var name = this.getName() + '.componentWillUnmount()';
ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst));
} else {
if (process.env.NODE_ENV !== 'production') {
measureLifeCyclePerf(function () {
return inst.componentWillUnmount();
}, this._debugID, 'componentWillUnmount');
} else {
inst.componentWillUnmount();
}
}
}
if (this._renderedComponent) {
ReactReconciler.unmountComponent(this._renderedComponent, safely);
this._renderedNodeType = null;
this._renderedComponent = null;
this._instance = null;
}
// Reset pending fields
// Even if this component is scheduled for another update in ReactUpdates,
// it would still be ignored because these fields are reset.
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._pendingCallbacks = null;
this._pendingElement = null;
// These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null;
this._rootNodeID = 0;
this._topLevelWrapper = null;
// Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
// Some existing components rely on inst.props even after they've been
// destroyed (in event handlers).
// TODO: inst.props = null;
// TODO: inst.state = null;
// TODO: inst.context = null;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function (context) {
var Component = this._currentElement.type;
var contextTypes = Component.contextTypes;
if (!contextTypes) {
return emptyObject;
}
var maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function (context) {
var maskedContext = this._maskContext(context);
if (process.env.NODE_ENV !== 'production') {
var Component = this._currentElement.type;
if (Component.contextTypes) {
this._checkContextTypes(Component.contextTypes, maskedContext, 'context');
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function (currentContext) {
var Component = this._currentElement.type;
var inst = this._instance;
var childContext;
if (inst.getChildContext) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onBeginProcessingChildContext();
try {
childContext = inst.getChildContext();
} finally {
ReactInstrumentation.debugTool.onEndProcessingChildContext();
}
} else {
childContext = inst.getChildContext();
}
}
if (childContext) {
!(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0;
if (process.env.NODE_ENV !== 'production') {
this._checkContextTypes(Component.childContextTypes, childContext, 'child context');
}
for (var name in childContext) {
!(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0;
}
return _assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Assert that the context types are valid
*
* @param {object} typeSpecs Map of context field to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkContextTypes: function (typeSpecs, values, location) {
if (process.env.NODE_ENV !== 'production') {
checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID);
}
},
receiveComponent: function (nextElement, transaction, nextContext) {
var prevElement = this._currentElement;
var prevContext = this._context;
this._pendingElement = null;
this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context);
} else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
} else {
this._updateBatchNumber = null;
}
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var inst = this._instance;
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', this.getName() || 'ReactCompositeComponent') : void 0;
var willReceive = false;
var nextContext;
// Determine if the context has changed or not
if (this._context === nextUnmaskedContext) {
nextContext = inst.context;
} else {
nextContext = this._processContext(nextUnmaskedContext);
willReceive = true;
}
var prevProps = prevParentElement.props;
var nextProps = nextParentElement.props;
// Not a simple state update but a props update
if (prevParentElement !== nextParentElement) {
willReceive = true;
}
// An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
if (willReceive && inst.componentWillReceiveProps) {
if (process.env.NODE_ENV !== 'production') {
measureLifeCyclePerf(function () {
return inst.componentWillReceiveProps(nextProps, nextContext);
}, this._debugID, 'componentWillReceiveProps');
} else {
inst.componentWillReceiveProps(nextProps, nextContext);
}
}
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = true;
if (!this._pendingForceUpdate) {
if (inst.shouldComponentUpdate) {
if (process.env.NODE_ENV !== 'production') {
shouldUpdate = measureLifeCyclePerf(function () {
return inst.shouldComponentUpdate(nextProps, nextState, nextContext);
}, this._debugID, 'shouldComponentUpdate');
} else {
shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
}
} else {
if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState);
}
}
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0;
}
this._updateBatchNumber = null;
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext);
} else {
// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement;
this._context = nextUnmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
}
},
_processPendingState: function (props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
if (replace && queue.length === 1) {
return queue[0];
}
var nextState = _assign({}, replace ? queue[0] : inst.state);
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
_assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial);
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
var _this2 = this;
var inst = this._instance;
var hasComponentDidUpdate = Boolean(inst.componentDidUpdate);
var prevProps;
var prevState;
var prevContext;
if (hasComponentDidUpdate) {
prevProps = inst.props;
prevState = inst.state;
prevContext = inst.context;
}
if (inst.componentWillUpdate) {
if (process.env.NODE_ENV !== 'production') {
measureLifeCyclePerf(function () {
return inst.componentWillUpdate(nextProps, nextState, nextContext);
}, this._debugID, 'componentWillUpdate');
} else {
inst.componentWillUpdate(nextProps, nextState, nextContext);
}
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
this._updateRenderedComponent(transaction, unmaskedContext);
if (hasComponentDidUpdate) {
if (process.env.NODE_ENV !== 'production') {
transaction.getReactMountReady().enqueue(function () {
measureLifeCyclePerf(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), _this2._debugID, 'componentDidUpdate');
});
} else {
transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst);
}
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function (transaction, context) {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var nextRenderedElement = this._renderValidatedComponent();
var debugID = 0;
if (process.env.NODE_ENV !== 'production') {
debugID = this._debugID;
}
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context));
} else {
var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance);
ReactReconciler.unmountComponent(prevComponentInstance, false);
var nodeType = ReactNodeTypes.getType(nextRenderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
);
this._renderedComponent = child;
var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), debugID);
if (process.env.NODE_ENV !== 'production') {
if (debugID !== 0) {
var childDebugIDs = child._debugID !== 0 ? [child._debugID] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
}
this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance);
}
},
/**
* Overridden in shallow rendering.
*
* @protected
*/
_replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) {
ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function () {
var inst = this._instance;
var renderedElement;
if (process.env.NODE_ENV !== 'production') {
renderedElement = measureLifeCyclePerf(function () {
return inst.render();
}, this._debugID, 'render');
} else {
renderedElement = inst.render();
}
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (renderedElement === undefined && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
renderedElement = null;
}
}
return renderedElement;
},
/**
* @private
*/
_renderValidatedComponent: function () {
var renderedElement;
if (process.env.NODE_ENV !== 'production' || this._compositeType !== CompositeTypes.StatelessFunctional) {
ReactCurrentOwner.current = this;
try {
renderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
} else {
renderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
}
!(
// TODO: An `isValidNode` function would probably be more appropriate
renderedElement === null || renderedElement === false || React.isValidElement(renderedElement)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0;
return renderedElement;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function (ref, component) {
var inst = this.getPublicInstance();
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : _prodInvariant('110') : void 0;
var publicComponentInstance = component.getPublicInstance();
if (process.env.NODE_ENV !== 'production') {
var componentName = component && component.getName ? component.getName() : 'a component';
process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null || component._compositeType !== CompositeTypes.StatelessFunctional, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0;
}
var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
refs[ref] = publicComponentInstance;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function (ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function () {
var type = this._currentElement.type;
var constructor = this._instance && this._instance.constructor;
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function () {
var inst = this._instance;
if (this._compositeType === CompositeTypes.StatelessFunctional) {
return null;
}
return inst;
},
// Stub
_instantiateReactComponent: null
};
module.exports = ReactCompositeComponent; |
src/App.js | Dmidify/mlblog | import React, { Component } from 'react';
import { Link } from 'react-router';
import { postsData } from './sample-data';
import './App.css';
import Navbar from './components/navbar';
import HomeHeader from './components/home-header';
import PostsList from './components/posts-list';
import Footer from './components/footer';
class App extends Component {
state = {
posts: postsData
}
newPost = () => {
const newPost = {
"id": "2c0f759c14404c9596690dcfb364127f",
"title": "My Blog Post New",
"content" : "Some content for a blog post again.",
"username" : "sampleUser",
"datetime" : "20160910T19:13:39+00:00"
};
this.setState({
posts: this.state.posts.concat([newPost]),
});
}
render() {
return (
<div className="container-fluid">
<div className="row">
<Navbar />
<HomeHeader />
<PostsList />
<Footer />
</div>
</div>
);
}
};
export default App;
|
react/features/video-menu/components/web/MuteEveryoneElsesVideoButton.js | gpolitis/jitsi-meet | // @flow
import React from 'react';
import ContextMenuItem from '../../../base/components/context-menu/ContextMenuItem';
import { translate } from '../../../base/i18n';
import { IconMuteVideoEveryoneElse } from '../../../base/icons';
import { connect } from '../../../base/redux';
import AbstractMuteEveryoneElsesVideoButton, {
type Props
} from '../AbstractMuteEveryoneElsesVideoButton';
/**
* Implements a React {@link Component} which displays a button for audio muting
* every participant in the conference except the one with the given
* participantID.
*/
class MuteEveryoneElsesVideoButton extends AbstractMuteEveryoneElsesVideoButton {
/**
* Instantiates a new {@code Component}.
*
* @inheritdoc
*/
constructor(props: Props) {
super(props);
this._handleClick = this._handleClick.bind(this);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { t } = this.props;
return (
<ContextMenuItem
accessibilityLabel = { t('toolbar.accessibilityLabel.muteEveryoneElsesVideoStream') }
icon = { IconMuteVideoEveryoneElse }
// eslint-disable-next-line react/jsx-handler-names
onClick = { this._handleClick }
text = { t('videothumbnail.domuteVideoOfOthers') } />
);
}
_handleClick: () => void;
}
export default translate(connect()(MuteEveryoneElsesVideoButton));
|
ajax/libs/react-bootstrap-typeahead/0.1.5/react-bootstrap-typeahead.min.js | sashberd/cdnjs | !function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={exports:{},id:o,loaded:!1};return e[o].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),a=o(r),s=n(11),i=o(s),l=n(12),u=o(l),d=n(13),p=o(d),c=n(9),f=n(2),h=n(7),v=o(h),m=a["default"].PropTypes;n(8);var y=a["default"].createClass({displayName:"Typeahead",mixins:[v["default"]],propTypes:{defaultSelected:m.array,emptyLabel:m.string,labelKey:m.string,maxHeight:m.number,multiple:m.bool,options:m.array.isRequired,placeholder:m.string,selected:m.array},getDefaultProps:function(){return{defaultSelected:[],labelKey:"label",multiple:!1,selected:[]}},getInitialState:function(){var e=this.props,t=e.defaultSelected,n=e.selected;return{activeIndex:0,selected:(0,c.isEmpty)(t)?n:t,showMenu:!1,text:""}},componentWillReceiveProps:function(e){(0,c.isEqual)(this.props.selected,e.selected)||this.setState({selected:e.selected}),this.props.multiple!==e.multiple&&this.setState({text:""})},render:function(){var e=this.props,t=e.labelKey,n=e.multiple,o=e.options,r=this.state,s=r.activeIndex,l=r.selected,d=r.text,f=o.filter(function(e){return!(-1===e[t].toLowerCase().indexOf(d.toLowerCase())||n&&(0,c.find)(l,e))}),h=void 0;this.state.showMenu&&(h=a["default"].createElement(p["default"],{activeIndex:s,emptyLabel:this.props.emptyLabel,labelKey:t,maxHeight:this.props.maxHeight,onClick:this._handleAddOption,options:f}));var v=i["default"];return n||(v=u["default"],l=(0,c.head)(l),d=l&&l[t]||d),a["default"].createElement("div",{className:"bootstrap-typeahead open",style:{position:"relative"}},a["default"].createElement(v,{filteredOptions:f,labelKey:t,onAdd:this._handleAddOption,onChange:this._handleTextChange,onFocus:this._handleFocus,onKeyDown:this._handleKeydown.bind(null,f),onRemove:this._handleRemoveOption,placeholder:this.props.placeholder,ref:"input",selected:l,text:d}),h)},_handleFocus:function(){this.setState({showMenu:!0})},_handleTextChange:function(e){this.setState({activeIndex:0,showMenu:!0,text:e.target.value})},_handleKeydown:function(e,t){var n=this.state.activeIndex;switch(t.keyCode){case f.BACKSPACE:t.stopPropagation();break;case f.UP:t.preventDefault(),n--,0>n&&(n=e.length-1),this.setState({activeIndex:n});break;case f.DOWN:case f.TAB:t.preventDefault(),n++,n===e.length&&(n=0),this.setState({activeIndex:n});break;case f.ESC:t.stopPropagation(),this._hideDropdown();break;case f.RETURN:var o=e[n];o&&this._handleAddOption(o)}},_handleAddOption:function(e){var t=this.props,n=t.multiple,o=t.labelKey,r=t.onChange,a=void 0,s=void 0;n?(a=this.state.selected.concat(e),s=""):(a=[e],s=e[o]),this.setState({activeIndex:0,selected:a,showMenu:!1,text:s}),r&&r(a)},_handleRemoveOption:function(e){var t=this.state.selected.slice();t=t.filter(function(t){return!(0,c.isEqual)(t,e)}),this.setState({activeIndex:0,selected:t,showMenu:!1}),this.props.onChange&&this.props.onChange(t)},handleClickOutside:function(e){this._hideDropdown()},_hideDropdown:function(){this.setState({activeIndex:0,showMenu:!1})}});t["default"]=y},function(e,t){e.exports=React},function(e,t){"use strict";e.exports={BACKSPACE:8,TAB:9,RETURN:13,ESC:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40}},function(e,t,n){var o;/*!
Copyright (c) 2015 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
!function(){"use strict";function r(){for(var e="",t=0;t<arguments.length;t++){var n=arguments[t];if(n){var o=typeof n;if("string"===o||"number"===o)e+=" "+n;else if(Array.isArray(n))e+=" "+r.apply(null,n);else if("object"===o)for(var s in n)a.call(n,s)&&n[s]&&(e+=" "+s)}}return e.substr(1)}var a={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=r:(o=function(){return r}.call(t,n,t,e),!(void 0!==o&&(e.exports=o)))}()},function(e,t){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var n=this[t];n[2]?e.push("@media "+n[2]+"{"+n[1]+"}"):e.push(n[1])}return e.join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var o={},r=0;r<this.length;r++){var a=this[r][0];"number"==typeof a&&(o[a]=!0)}for(r=0;r<t.length;r++){var s=t[r];"number"==typeof s[0]&&o[s[0]]||(n&&!s[2]?s[2]=n:n&&(s[2]="("+s[2]+") and ("+n+")"),e.push(s))}},e}},function(e,t,n){function o(e,t){for(var n=0;n<e.length;n++){var o=e[n],r=f[o.id];if(r){r.refs++;for(var a=0;a<r.parts.length;a++)r.parts[a](o.parts[a]);for(;a<o.parts.length;a++)r.parts.push(u(o.parts[a],t))}else{for(var s=[],a=0;a<o.parts.length;a++)s.push(u(o.parts[a],t));f[o.id]={id:o.id,refs:1,parts:s}}}}function r(e){for(var t=[],n={},o=0;o<e.length;o++){var r=e[o],a=r[0],s=r[1],i=r[2],l=r[3],u={css:s,media:i,sourceMap:l};n[a]?n[a].parts.push(u):t.push(n[a]={id:a,parts:[u]})}return t}function a(e,t){var n=m(),o=g[g.length-1];if("top"===e.insertAt)o?o.nextSibling?n.insertBefore(t,o.nextSibling):n.appendChild(t):n.insertBefore(t,n.firstChild),g.push(t);else{if("bottom"!==e.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(t)}}function s(e){e.parentNode.removeChild(e);var t=g.indexOf(e);t>=0&&g.splice(t,1)}function i(e){var t=document.createElement("style");return t.type="text/css",a(e,t),t}function l(e){var t=document.createElement("link");return t.rel="stylesheet",a(e,t),t}function u(e,t){var n,o,r;if(t.singleton){var a=b++;n=y||(y=i(t)),o=d.bind(null,n,a,!1),r=d.bind(null,n,a,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=l(t),o=c.bind(null,n),r=function(){s(n),n.href&&URL.revokeObjectURL(n.href)}):(n=i(t),o=p.bind(null,n),r=function(){s(n)});return o(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;o(e=t)}else r()}}function d(e,t,n,o){var r=n?"":o.css;if(e.styleSheet)e.styleSheet.cssText=x(t,r);else{var a=document.createTextNode(r),s=e.childNodes;s[t]&&e.removeChild(s[t]),s.length?e.insertBefore(a,s[t]):e.appendChild(a)}}function p(e,t){var n=t.css,o=t.media;t.sourceMap;if(o&&e.setAttribute("media",o),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function c(e,t){var n=t.css,o=(t.media,t.sourceMap);o&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */");var r=new Blob([n],{type:"text/css"}),a=e.href;e.href=URL.createObjectURL(r),a&&URL.revokeObjectURL(a)}var f={},h=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},v=h(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),m=h(function(){return document.head||document.getElementsByTagName("head")[0]}),y=null,b=0,g=[];e.exports=function(e,t){t=t||{},"undefined"==typeof t.singleton&&(t.singleton=v()),"undefined"==typeof t.insertAt&&(t.insertAt="bottom");var n=r(e);return o(n,t),function(e){for(var a=[],s=0;s<n.length;s++){var i=n[s],l=f[i.id];l.refs--,a.push(l)}if(e){var u=r(e);o(u,t)}for(var s=0;s<a.length;s++){var l=a[s];if(0===l.refs){for(var d=0;d<l.parts.length;d++)l.parts[d]();delete f[l.id]}}}};var x=function(){var e=[];return function(t,n){return e[t]=n,e.filter(Boolean).join("\n")}}()},function(e,t){e.exports=ReactDOM},function(e,t){e.exports=onClickOutside},function(e,t,n){var o=n(16);"string"==typeof o&&(o=[[e.id,o,""]]);n(5)(o,{});o.locals&&(e.exports=o.locals)},function(e,t){e.exports=lodash},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),a=o(r),s=n(6),i=n(3),l=o(i),u=n(2),d=o(u),p=n(7),c=o(p);n(17);var f=a["default"].createClass({displayName:"Token",mixins:[c["default"]],propTypes:{onRemove:a["default"].PropTypes.func},getInitialState:function(){return{selected:!1}},render:function(){return this.props.onRemove?this._renderRemoveableToken():this._renderToken()},_renderRemoveableToken:function(){return a["default"].createElement("button",{className:(0,l["default"])("token","token-removeable",{"token-selected":this.state.selected},this.props.className),onBlur:this._handleBlur,onClick:this._handleSelect,onFocus:this._handleSelect,onKeyDown:this._handleKeyDown,tabIndex:0},this.props.children,a["default"].createElement("span",{className:"token-close-button",onClick:this._handleRemove},"×"))},_renderToken:function(){var e=(0,l["default"])("token",this.props.className);return this.props.href?a["default"].createElement("a",{className:e,href:this.props.href},this.props.children):a["default"].createElement("div",{className:e},this.props.children)},_handleBlur:function(e){(0,s.findDOMNode)(this).blur(),this.setState({selected:!1})},_handleKeyDown:function(e){switch(e.keyCode){case d["default"].BACKSPACE:this.state.selected&&(e.preventDefault(),this._handleRemove())}},handleClickOutside:function(e){this._handleBlur()},_handleRemove:function(e){this.props.onRemove&&this.props.onRemove()},_handleSelect:function(e){e.stopPropagation(),this.setState({selected:!0})}});t["default"]=f},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};Object.defineProperty(t,"__esModule",{value:!0});var a=n(19),s=o(a),i=n(1),l=o(i),u=n(10),d=o(u),p=n(3),c=o(p),f=n(6),h=n(2),v=o(h),m=l["default"].PropTypes;n(18);var y=l["default"].createClass({displayName:"TokenizerInput",propTypes:{labelKey:m.string,placeholder:m.string,selected:m.array},render:function(){var e=this.props,t=e.className,n=e.placeholder,o=e.selected,a=e.text;return l["default"].createElement("div",{className:(0,c["default"])("bootstrap-tokenizer","form-control","clearfix",t),onClick:this._handleInputFocus,onFocus:this._handleInputFocus,tabIndex:0},o.map(this._renderToken),l["default"].createElement(s["default"],r({},this.props,{className:"bootstrap-tokenizer-input",inputStyle:{backgroundColor:"inherit",border:0,outline:"none",padding:0},onKeyDown:this._handleKeydown,placeholder:o.length?null:n,ref:"input",type:"text",value:a})))},_renderToken:function(e,t){var n=this.props,o=n.onRemove,r=n.labelKey;return l["default"].createElement(d["default"],{key:t,onRemove:o.bind(null,e)},e[r])},_handleKeydown:function(e){switch(e.keyCode){case v["default"].LEFT:case v["default"].RIGHT:break;case v["default"].BACKSPACE:var t=(0,f.findDOMNode)(this.refs.input);if(t&&t.contains(document.activeElement)&&!this.props.text){var n=t.previousSibling;n&&n.focus()}}this.props.onKeyDown&&this.props.onKeyDown(e)},_handleInputFocus:function(e){this.refs.input.focus()}});t["default"]=y},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=o(a),i=n(3),l=o(i),u=n(9),d=n(2),p=o(d),c=n(7),f=o(c),h=s["default"].PropTypes;n(8);var v=s["default"].createClass({displayName:"TypeaheadInput",mixins:[f["default"]],propTypes:{filteredOptions:h.array,labelKey:h.string,onChange:h.func,selected:h.object,text:h.string},render:function(){return s["default"].createElement("div",{className:(0,l["default"])("bootstrap-typeahead-input",this.props.className),onClick:this._handleInputFocus,onFocus:this._handleInputFocus,tabIndex:0},s["default"].createElement("input",r({},this.props,{className:(0,l["default"])("bootstrap-typeahead-input-main","form-control",{"has-selection":!this.props.selected}),onKeyDown:this._handleKeydown,ref:"input",style:{backgroundColor:"transparent",display:"block",position:"relative",zIndex:1},type:"text",value:this._getInputValue()})),s["default"].createElement("input",{className:"bootstrap-typeahead-input-hint form-control",style:{borderColor:"transparent",bottom:0,display:"block",position:"absolute",top:0,width:"100%",zIndex:0},value:this._getHintText()}))},_getInputValue:function(){var e=this.props,t=e.labelKey,n=e.selected,o=e.text;return n?n[t]:o},_getHintText:function(){var e=this.props,t=e.filteredOptions,n=e.labelKey,o=e.text,r=(0,u.head)(t);return this.refs.input===document.activeElement&&o&&r&&0===r[n].indexOf(o)?r[n]:void 0},_handleInputFocus:function(e){this.refs.input.focus()},_handleKeydown:function(e){var t=this.props,n=t.filteredOptions,o=t.onAdd,r=t.onRemove,a=t.selected;switch(e.keyCode){case p["default"].ESC:this.refs.input.blur();break;case p["default"].RIGHT:this._getHintText()&&!a&&o&&o((0,u.head)(n));break;case p["default"].BACKSPACE:a&&r&&r(a)}this.props.onKeyDown&&this.props.onKeyDown(e)},handleClickOutside:function(e){this.refs.input.blur()}});t["default"]=v},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=o(a),i=n(6),l=n(3),u=o(l),d=s["default"].PropTypes,p=s["default"].createClass({displayName:"Menu",render:function(){return s["default"].createElement("ul",r({},this.props,{className:(0,u["default"])("dropdown-menu",this.props.className)}),this.props.children)}}),c=s["default"].createClass({displayName:"MenuItem",componentWillReceiveProps:function(e){e.active&&(0,i.findDOMNode)(this).firstChild.focus()},render:function(){return s["default"].createElement("li",{className:(0,u["default"])({active:this.props.active,disabled:this.props.disabled})},s["default"].createElement("a",{href:"#",onClick:this._handleClick},this.props.children))},_handleClick:function(e){e.preventDefault(),this.props.onClick&&this.props.onClick()}}),f=s["default"].createClass({displayName:"TypeaheadMenu",propTypes:{activeIndex:d.number,emptyLabel:d.string,labelKey:d.string.isRequired,maxHeight:d.number,options:d.array},getDefaultProps:function(){return{emptyLabel:"No matches found.",maxHeight:300}},render:function(){var e=this.props,t=e.maxHeight,n=e.options,o=n.length?n.map(this._renderDropdownItem):s["default"].createElement(c,{disabled:!0},this.props.emptyLabel);return s["default"].createElement(p,{style:{maxHeight:t+"px",right:0}},o)},_renderDropdownItem:function(e,t){var n=this.props,o=n.activeIndex,r=n.onClick;return s["default"].createElement(c,{active:t===o,key:t,onClick:r.bind(null,e)},e[this.props.labelKey])}});t["default"]=f},function(e,t,n){t=e.exports=n(4)(),t.push([e.id,".token{background-color:#e7f4ff;border:0;border-radius:2px;color:#1f8dd6;display:inline-block;line-height:1em;padding:4px 7px;position:relative}.token-removeable,.token:focus{padding-right:21px}.token-selected{background-color:#1f8dd6;color:#fff;outline:none;text-decoration:none}.bootstrap-tokenizer .token{margin:0 3px 3px 0}.token-close-button{bottom:0;padding:3px 7px;position:absolute;right:0;top:0}",""])},function(e,t,n){t=e.exports=n(4)(),t.push([e.id,".bootstrap-tokenizer{cursor:text;height:auto;padding:5px 12px 2px}.bootstrap-tokenizer-input{margin:1px 0 4px}",""])},function(e,t,n){t=e.exports=n(4)(),t.push([e.id,".bootstrap-typeahead .dropdown-menu{overflow:scroll}.bootstrap-typeahead .dropdown-menu>li a:focus{outline:none}.bootstrap-typeahead-input-hint{color:#aaa}",""])},function(e,t,n){var o=n(14);"string"==typeof o&&(o=[[e.id,o,""]]);n(5)(o,{});o.locals&&(e.exports=o.locals)},function(e,t,n){var o=n(15);"string"==typeof o&&(o=[[e.id,o,""]]);n(5)(o,{});o.locals&&(e.exports=o.locals)},function(e,t){e.exports=AutosizeInput}]);
//# sourceMappingURL=react-bootstrap-typeahead.min.js.map |
src/js/Main/components/App.js | fr3nchN/proactive | import React from 'react'
import Values from './Values'
import Features from './Features'
import LatestNews from './LatestNews'
import ProActiveProject from './ProActiveProject'
import { Link } from 'react-router-dom'
import links from "./../links"
const App = () => (
<div>
<div className="background-image border-bottom-grey">
<div className="jumbotron jumbotron-fluid mb-0 background-orange-transparent">
<div className="container">
<div className="row">
<div className="col-md-8 text-white">
<h1 className="display-1">Activeeon</h1>
<p className="h2 mb-4">Job Scheduling, Workload Automation, Orchestration & Metascheduling <br /> on-premises and on all clouds.</p>
<p className="h4 mb-4">Open source workflow engine</p>
<Link className="btn btn-outline-light" to={links.getstarted}>Try it in 3 steps</Link>
</div>
</div>
</div>
</div>
</div>
<div className="background-lightgray border-bottom-grey">
<div className="container pb-3 pt-3">
<LatestNews />
</div>
</div>
<div className="container mb-3 mt-5">
<Values/>
</div>
<div className="background-home-request">
<div className="background-orange-transparent">
<div className="container">
<div className="row row-setheight align-items-center">
<div className="col-6 text-center">
<h2 className="display-3 text-white">Get in touch</h2>
<a href="mailto:[email protected]?Subject=[ProActive]%20Request%20for%20information" className="btn btn-light">Contact us</a>
</div>
</div>
</div>
</div>
</div>
<div className="container mt-4">
<Features />
</div>
<div className="background-lightgray border-bottom-grey border-top-grey">
<div className="container pb-3 pt-3">
<ProActiveProject />
</div>
</div>
<div className="background-home-try mt-0">
<div className="background-white">
<div className="container">
<div className="row justify-content-md-center align-items-center">
<div className="col-lg-5 text-center">
<h2>Try Online</h2>
<hr/>
<p className="h4">
Try it for free <a href={links.external.try.home} target="_blank">here</a> and follow this tutorial in <Link to={links.getstarted}>3 steps</Link>.
</p>
<div>
<a className="btn btn-outline-primary" href={links.external.try.home} target="_blank">Try It</a>
</div>
</div>
<div className="col-lg-5">
<div className="row justify-content-md-center">
<div className="col-12 text-center">
<h2>Strategic Alliances</h2>
<hr />
</div>
<div className="col-3">
<img src="images/alliance/alliance-aws.png" alt="aws" className="img-thumbnail mb-2"/>
</div>
<div className="col-3">
<img src="images/alliance/alliance-azure.png" alt="azure" className="img-thumbnail mb-2"/>
</div>
<div className="col-3">
<img src="images/alliance/alliance-capgemini.png" alt="capgemini" className="img-thumbnail mb-2"/>
</div>
<div className="col-3">
<img src="images/alliance/alliance-devoteam.png" alt="devoteam" className="img-thumbnail mb-2"/>
</div>
<div className="col-3">
<img src="images/alliance/alliance-docker.png" alt="docker" className="img-thumbnail mb-2"/>
</div>
<div className="col-3">
<img src="images/alliance/alliance-gcp.png" alt="gcp" className="img-thumbnail mb-2"/>
</div>
<div className="col-3">
<img src="images/alliance/alliance-sap.png" alt="sap" className="img-thumbnail mb-2"/>
</div>
<div className="col-3">
<img src="images/alliance/alliance-suse.png" alt="suse" className="img-thumbnail mb-2"/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
export default App;
|
packages/material-ui-icons/src/ShowChart.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M3.5 18.49l6-6.01 4 4L22 6.92l-1.41-1.41-7.09 7.97-4-4L2 16.99z" />
, 'ShowChart');
|
src/components/Quote.js | sergey-shulyak/simple-quote | import React from 'react';
import PropTypes from 'prop-types';
import { NavLink as Link } from 'react-router-dom';
const Quote = ({ text, favourite = false, book }) => (
<div className="ui piled segment">
<blockquote>{text}</blockquote>
{book &&
<Link to={`/${book.id}`} className="ui bottom right attached label">
{book.title}
</Link>}
</div>
);
Quote.propTypes = {
text: PropTypes.string.isRequired,
favourite: PropTypes.bool,
books: PropTypes.object
};
export default Quote;
|
src/server.js | stephenhandley/concertcalendar | import Express from 'express';
import React from 'react';
import Location from 'react-router/lib/Location';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import universalRouter from './helpers/universalRouter';
import Html from './helpers/Html';
import PrettyError from 'pretty-error';
const pretty = new PrettyError();
const app = new Express();
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:' + config.apiPort
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
let json;
console.log('proxy error', error);
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
json = { error: 'proxy_error', reason: error.message };
res.end(JSON.stringify(json));
});
app.use((req, res) => {
if (__DEVELOPMENT__) {
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
webpackIsomorphicTools.refresh();
}
const client = new ApiClient(req);
const store = createStore(client);
const location = new Location(req.path, req.query);
const hydrateOnClient = function() {
res.send('<!doctype html>\n' +
React.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={<div/>} store={store}/>));
}
if (__DISABLE_SSR__) {
hydrateOnClient();
return;
} else {
universalRouter(location, undefined, store)
.then(({component, transition, isRedirect}) => {
if (isRedirect) {
res.redirect(transition.redirectInfo.pathname);
return;
}
res.send('<!doctype html>\n' +
React.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
})
.catch((error) => {
if (error.redirect) {
res.redirect(error.redirect);
return;
}
console.error('ROUTER ERROR:', pretty.render(error));
hydrateOnClient(); // let client render error page or re-request data
});
}
});
if (config.port) {
app.listen(config.port, (err) => {
if (err) {
console.error(err);
}
console.info('----\n==> ✅ %s is running.', config.app.name);
console.info('==> 💻 Open http://localhost:%s in a browser to view the app.', config.port);
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
app/screens/Settings/SettingsScreenView.js | JSSolutions/Perfi | import React from 'react';
import T from 'prop-types';
import { Text, View } from 'react-native';
import { Subtitle, Select, ScreenWrapper, Icon, Button } from '../../components';
import currencies from '../../constants/currencies';
import s from './styles';
import { dimensions, colors } from '../../styles';
const Settings = ({
currency,
onChangeCurrency,
onGenerateData,
onResetData,
}) => (
<ScreenWrapper style={s.container}>
<View>
<Subtitle leftText="Choose a currency" />
<Select
isShowScroll={false}
options={[currencies.dollar, currencies.euro, currencies.hryvnia]}
containerStyle={s.selectorContainer}
style={s.selector}
defaultValue={currency}
selectorsWidth={dimensions.containerWidth}
onSelect={onChangeCurrency}
textStyle={s.selectTextStyle}
optionHeight={dimensions.verticalIndent * 2.8}
/>
<View style={s.generateButtonContainer}>
<Button
onPress={onGenerateData}
title="Generate data"
titleStyle={s.buttonTitle}
containerStyle={s.buttonContainer}
/>
<Button
onPress={onResetData}
title="Reset data"
titleStyle={s.buttonTitle}
containerStyle={s.buttonContainer}
backgroundColor={colors.red}
/>
</View>
</View>
<View style={s.secondContainer}>
<Text style={s.text}>Made with ❤️ by</Text>
<Icon
name="apikoLogo"
width={80}
height={24}
/>
</View>
</ScreenWrapper>
);
Settings.propTypes = {
currency: T.object,
onChangeCurrency: T.func,
onGenerateData: T.func,
onResetData: T.func,
};
export default Settings;
|
__tests__/index.ios.js | ravicpn/ReactNativeAppStoreClient | import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
manabi/static/js/draft-js-furigana-plugin/MentionSuggestions/Entry/Avatar/index.js | aehlke/manabi | import React from 'react';
const Avatar = ({ mention, theme = {} }) => {
if (mention.has('avatar')) {
return (
<img
src={mention.get('avatar')}
className={theme.mentionSuggestionsEntryAvatar}
role="presentation"
/>
);
}
return null;
};
export default Avatar;
|
src/pages/projects.js | bretafinley/site |
import React from 'react';
import Link from 'gatsby-link';
import ProjectCard from '../components/cards/project-card';
const Projects = ({data}) => {
const projects = data.allMarkdownRemark.edges.map((d, i) => {
const excerpt = d.node.excerpt;
const front = d.node.frontmatter;
return <ProjectCard key={i} frontmatter={front} excerpt={excerpt} />
});
return (
<div>
<h2 className="card page-title">Projects</h2>
{projects}
</div>
);
};
export default Projects;
export const projectQuery = graphql`
query ProjectIndexQuery {
allMarkdownRemark(
sort: { fields: [frontmatter___post_date], order: DESC },
filter: {
frontmatter: {
post_type: { eq: 2 },
published: { eq: true }
}
}){
edges {
node {
id
excerpt
frontmatter {
title
subtitle
path
post_type
post_date
published
subject_url
category
folder
tags
}
}
}
}
}`
|
packages/material-ui-icons/lib/ImportContactsSharp.js | mbrookes/material-ui | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M21 5c-1.11-.35-2.33-.5-3.5-.5-1.95 0-4.05.4-5.5 1.5-1.45-1.1-3.55-1.5-5.5-1.5S2.45 4.9 1 6v15.5C2.45 20.4 4.55 20 6.5 20s4.05.4 5.5 1.5c1.45-1.1 3.55-1.5 5.5-1.5 1.17 0 2.39.15 3.5.5.75.25 1.4.55 2 1V6c-.6-.45-1.25-.75-2-1zm0 13.5c-1.1-.35-2.3-.5-3.5-.5-1.7 0-4.15.65-5.5 1.5V8c1.35-.85 3.8-1.5 5.5-1.5 1.2 0 2.4.15 3.5.5v11.5z"
}), 'ImportContactsSharp');
exports.default = _default; |
ajax/libs/forerunnerdb/1.3.60/fdb-all.min.js | dakshshah96/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){{var d=a("./core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/Grid"),a("../lib/Rest"),a("../lib/Odm")}"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":5,"../lib/Document":9,"../lib/Grid":10,"../lib/Highchart":11,"../lib/Odm":25,"../lib/Overview":28,"../lib/Persist":30,"../lib/Rest":32,"../lib/View":35,"./core":2}],2:[function(a,b,c){{var d=a("../lib/Core");a("../lib/Shim.IE8")}"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":6,"../lib/Shim.IE8":34}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),e.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":33}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._internalData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this.subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if("dropped"===this._state)return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log("Dropping collection "+this._name),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._internalData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&this.primaryKey(a.primaryKey()),this.$super.apply(this,arguments)}),n.prototype.setData=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw'ForerunnerDB.Collection "'+this.name()+'": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: '+d[this._primaryKey]}else h.set(d[k],d);e=JSON.stringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';b=this.decouple(b),b=this.transformIn(b),this.debug()&&console.log('Updating some collection data for collection "'+this.name()+'"');var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,d,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw'ForerunnerDB.Collection "'+this.name()+'": Primary key violation in update! Key violated: '+a[this._primaryKey];return this},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":this._updateIncrement(a,p,b[p]),q=!0;break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw'ForerunnerDB.Collection "'+this.name()+'": Cannot update cast to unknown type: '+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot push to a key that is not an array! ('+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pullAll without being given an array of values to pull! ('+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! ('+p+")";var s,t,u,v,w=a[p],x=w.length,y=!0,z=d&&d.$addToSet;for(b[p].$key?(u=!1,v=new h(b[p].$key),t=v.value(b[p])[0],delete b[p].$key):z&&z.key?(u=!1,v=new h(z.key),t=v.value(b[p])[0]):(t=JSON.stringify(b[p]),u=!0),s=0;x>s;s++)if(u){if(JSON.stringify(w[s])===t){y=!1;break}}else if(t===v.value(w[s])[0]){y=!1;break}y&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+p+")";if(l=b.$index,void 0===l)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush without a $index integer value!';delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move on a key that is not an array! ('+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],"",{})){var A=b.$index;if(void 0===A)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move without a $index integer value!';delete b.$index,this._updateSpliceMove(a[p],j,A),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pop from a key that is not an array! ('+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b=void 0),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this._onChange(),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.deferEmit=function(a,b){var c,d=this;this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log("ForerunnerDB.Collection: Emitting "+c[0]),d.emit.apply(d,c)},1))},n.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c)},n.prototype.insert=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=JSON.stringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=JSON.stringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return!0},n.prototype.distinct=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=JSON.stringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b,c){return c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C=this._metrics.create("find"),D=this.primaryKey(),E=this,F=!0,G={},H=[],I=[],J=[],K={},L={},M=function(b){return E._match(b,a,"and",K)};if(C.start(),a){if(C.time("analyseQuery"),c=this._analyseQuery(E.decouple(a),b,C),C.time("analyseQuery"),C.data("analysis",c),c.hasJoin&&c.queriesJoin){for(C.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],G[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];C.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(C.data("index.potential",c.indexMatch),C.data("index.used",c.indexMatch[0].index),C.time("indexLookup"),e=c.indexMatch[0].lookup||[],C.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(F=!1)):C.flag("usedIndex",!1),F&&(e&&e.length?(d=e.length,C.time("tableScan: "+d),e=e.filter(M)):(d=this._data.length,C.time("tableScan: "+d),e=this._data.filter(M)),b.$orderBy&&(C.time("sort"),e=this.sort(b.$orderBy,e),C.time("sort")),C.time("tableScan: "+d)),void 0!==b.$page&&void 0!==b.$limit&&(L.page=b.$page,L.pages=Math.ceil(e.length/b.$limit),L.records=e.length,b.$page&&b.$limit>0&&(C.data("cursor",L),e.splice(0,b.$page*b.$limit))),b.$skip&&(L.skip=b.$skip,e.splice(0,b.$skip),C.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(L.limit=b.$limit,e.length=b.$limit,C.data("limit",b.$limit)),b.$decouple&&(C.time("decouple"),e=this.decouple(e),C.time("decouple"),C.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(s=k,l=G[k]?G[k]:this._db.collection(k),m=b.$join[f][k],t=0;t<e.length;t++){o={},p=!1,q=!1;for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$as":s=m[n];break;case"$multi":p=m[n];break;case"$require":q=m[n]}else o[n]=new h(m[n]).value(e[t])[0];r=l.find(o),!q||q&&r[0]?e[t][s]=p===!1?r[0]:r:H.push(e[t])}C.data("flag.join",!0)}if(H.length){for(C.time("removalQueue"),v=0;v<H.length;v++)u=e.indexOf(H[v]),u>-1&&e.splice(u,1);C.time("removalQueue")}if(b.$transform){for(C.time("transform"),v=0;v<e.length;v++)e.splice(v,1,b.$transform(e[v]));C.time("transform"),C.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(C.time("transformOut"),e=this.transformOut(e),C.time("transformOut")),C.data("results",e.length)}else e=[];C.time("scanFields");for(v in b)b.hasOwnProperty(v)&&0!==v.indexOf("$")&&(1===b[v]?I.push(v):0===b[v]&&J.push(v));if(C.time("scanFields"),I.length||J.length){for(C.data("flag.limitFields",!0),C.data("limitFields.on",I),C.data("limitFields.off",J),C.time("limitFields"),v=0;v<e.length;v++){B=e[v];for(w in B)B.hasOwnProperty(w)&&(I.length&&w!==D&&-1===I.indexOf(w)&&delete B[w],J.length&&J.indexOf(w)>-1&&delete B[w])}C.time("limitFields")}if(b.$elemMatch){C.data("flag.elemMatch",!0),C.time("projection-elemMatch");for(v in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length)for(x=0;x<z.length;x++)if(E._match(z[x],b.$elemMatch[v],"",{})){y.set(e[w],v,[z[x]]);break}C.time("projection-elemMatch")}if(b.$elemsMatch){C.data("flag.elemsMatch",!0),C.time("projection-elemsMatch");for(v in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length){for(A=[],x=0;x<z.length;x++)E._match(z[x],b.$elemsMatch[v],"",{})&&A.push(z[x]);y.set(e[w],v,A)}C.time("projection-elemsMatch")}return C.stop(),e.__fdbOp=C,e.$cursor=L,e},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a){var b=this.find(a,{$decouple:!1})[0];return b?this._data.indexOf(b):-1},n.prototype.indexOfDocById=function(a){return this._data.indexOf("object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]))},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=c,e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f=a.shift(),g=[];if(a.length>0){b=this._sort(f,b),d=this.bucket(f.___fdbKey,b);for(e in d)d.hasOwnProperty(e)&&(c=[].concat(a),g=g.concat(this._bucketSort(c,d[e])));return g}return this._sort(f,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw'ForerunnerDB.Collection "'+this.name()+'": $orderBy clause has invalid direction: '+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d={};for(c=0;c<b.length;c++)d[b[c][a]]=d[b[c][a]]||[],d[b[c][a]].push(b[c]);return d},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),r.push("$as"in b.$join[d][e]?b.$join[d][e].$as:e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw'ForerunnerDB.Collection "'+this.name()+'": Collection diffing requires that both collections have the same primary key!';for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({object:function(a){return this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+this.name()+'": Cannot get collection '+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log("Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b).db(this),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+this.name()+'": Cannot get collection with undefined name!'}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._collection)this._collection.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,count:this._collection[b].count()}):c.push({name:b,count:this._collection[b].count()}));return c.sort(function(a,b){
return a.name.localeCompare(b.name)}),c},d.finishModule("Collection"),b.exports=n},{"./Crc":7,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":29,"./ReactorIO":31,"./Shared":33}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": All collections in a collection group must have the same primary key!'}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(){if("dropped"!==this._state){var a,b,c;if(this._debug&&console.log("Dropping collection group "+this._name),this._state="dropped",this._collections&&this._collections.length)for(b=[].concat(this._collections),a=0;a<b.length;a++)this.removeCollection(b[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]);this.emit("drop",this)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":4,"./Shared":33}],6:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;if(void 0!==a){for(b=0;b<h.length;b++)if(h[b].name===a)return h[b];return void 0}for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":33}],7:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],8:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d=d.concat("string"===e?c.peek(a):c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if("dropped"!==this._state){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if("dropped"!==this._state){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a]},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},b.exports=j},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":15,"./Overload":27,"./Shared":33}],9:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a)if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){this.updateObject(this._data,b,a,c)},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log('ForerunnerDB.Document: Setting data-bound document property "'+b+'" for collection "'+this.name()+'"')):(a[b]=c,this.debug()&&console.log('ForerunnerDB.Document: Setting non-data-bound document property "'+b+'" for collection "'+this.name()+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log('ForerunnerDB.Document: Moving data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Document: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype._updatePop=function(a,b){var c,d=!1;return a.length>0&&(this._linked?(1===b?c=a.length-1:-1===b&&(c=0),c>-1&&(window.jQuery.observable(a).remove(c),d=!0)):1===b?(a.pop(),d=!0):-1===b&&(a.shift(),d=!0)),d},g.prototype.drop=function(){return"dropped"===this._state?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),!0):!1},f.prototype.document=function(a){return a?(this._document=this._document||{},this._document[a]=this._document[a]||new g(a).db(this),this._document[a]):this._document},f.prototype.documents=function(){var a,b=[];for(a in this._document)this._document.hasOwnProperty(a)&&b.push({name:a});return b},d.finishModule("Document"),b.exports=g},{"./Collection":4,"./Shared":33}],10:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},l.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(){return"dropped"===this._state?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.Grid: Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),delete this._selector,delete this._template,delete this._from,delete this._db,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget).attr("data-grid-sort")||"",d=c.split(","),e={};for(b=0;b<d.length;b++)e[d]=1;this._from.orderBy(e),this.emit("sort",e)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked> All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox"> {^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(this._db._grid[a])throw'ForerunnerDB.Collection/View "'+this.name()+'": Cannot create a grid using this collection/view because a grid with this name already exists: '+name;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw'ForerunnerDB.Collection/View "'+this.name()+'": Cannot remove a grid using this collection/view because a grid with this name does not exist: '+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log('ForerunnerDB.Collection/View "'+this.name()+'": Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Db.Grid: Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Db.Grid: Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b=[];for(a in this._grid)this._grid.hasOwnProperty(a)&&b.push({name:a,count:this._grid[a].count()});return b},d.finishModule("Grid"),b.exports=l},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":31,"./Shared":33,"./View":35}],11:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw'ForerunnerDB.Highchart "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw'ForerunnerDB.Highchart "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d){var e,f,g,h,i,j,k=this._collection.distinct(a),l=[],m={categories:[]};for(i=0;i<k.length;i++){for(e=k[i],f={},f[a]=e,h=[],g=this._collection.find(f,{orderBy:d}),j=0;j<g.length;j++)m.categories.push(g[j][b]),h.push(g[j][c]);l.push({name:e,data:h})}return{xAxis:m,series:l}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a,arguments)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy);for(a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(){return"dropped"!==this._state?(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),!0):!0},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":27,"./Shared":33}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){},g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new(f.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(f.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},g.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},g.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);
else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./Path":29,"./Shared":33}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":29,"./Shared":33}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":33}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":26,"./Shared":33}],16:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={chain:function(a){this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||"dropped"===d._state))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload");d={store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}return void 0},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=JSON.stringify(a),e=[];for(c=0;b>c;c++)e.push(JSON.parse(d));return e}return JSON.parse(JSON.stringify(a))}return void 0},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}])},b.exports=d},{"./Overload":27}],19:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],20:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d;if(this._listeners[a]["*"]){var e=this._listeners[a]["*"];for(d=e.length,c=0;d>c;c++)e[c].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&&b[0]&&b[0][this._primaryKey]){var f,g,h=this._listeners[a];for(d=b.length,c=0;d>c;c++)if(h[b[c][this._primaryKey]])for(f=h[b[c][this._primaryKey]].length,g=0;f>g;g++)h[b[c][this._primaryKey]][g].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};b.exports=e},{"./Overload":27}],21:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d){var e,f,g,h,i,j,k,l=typeof a,m=typeof b,n=!0;if(d=d||{},d.$rootQuery||(d.$rootQuery=b),d.$rootData=d.$rootData||{},"string"!==l&&"number"!==l||"string"!==m&&"number"!==m){for(k in b)if(b.hasOwnProperty(k)){if(e=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],d),i>-1)){if(i){if("or"===c)return!0}else n=i;e=!0}if(!e&&b[k]instanceof RegExp)if(e=!0,"object"==typeof a&&void 0!==a[k]&&b[k].test(a[k])){if("or"===c)return!0}else n=!1;if(!e)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],f,d)){if("or"===c)return!0}else n=!1;else if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else n=!1;else if(a&&a[k]===b[k]){if("or"===c)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else n=!1;if("and"===c&&!n)return!1}}else"number"===l?a!==b&&(n=!1):a.localeCompare(b)&&(n=!1);return n},_matchOp:function(a,b,c,d){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$or":for(var e=0;e<c.length;e++)if(this._match(b,c[e],"and",d))return!0;return!1;case"$and":for(var f=0;f<c.length;f++)if(!this._match(b,c[f],"and",d))return!1;return!0;case"$in":if(c instanceof Array){var g,h=c,i=h.length;for(g=0;i>g;g++)if(h[g]===b)return!0;return!1}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use an $in operator on a non-array key: '+a;case"$nin":if(c instanceof Array){var j,k=c,l=k.length;for(j=0;l>j;j++)if(k[j]===b)return!1;return!0}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use a $nin operator on a non-array key: '+a;case"$distinct":d.$rootData["//distinctLookup"]=d.$rootData["//distinctLookup"]||{};for(var m in c)if(c.hasOwnProperty(m))return d.$rootData["//distinctLookup"][m]=d.$rootData["//distinctLookup"][m]||{},d.$rootData["//distinctLookup"][m][b[m]]?!1:(d.$rootData["//distinctLookup"][m][b[m]]=!0,!0)}return-1}};b.exports=d},{}],22:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":27}],24:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "'+b+'" for "'+this.name()+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for "'+this.name()+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c=!1;return a.length>0&&(1===b?(a.pop(),c=!0):-1===b&&(a.shift(),c=!0)),c}};b.exports=d},{}],25:[function(a,b,c){"use strict";var d,e;d=a("./Shared");var f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){var b=this;b._collectionDroppedWrap=function(){b._collectionDropped.apply(b,arguments)},b.from(a)},d.addModule("Odm",f),d.mixin(f.prototype,"Mixin.Common"),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Constants"),d.mixin(f.prototype,"Mixin.Events"),e=a("./Collection"),d.synthesize(f.prototype,"state"),d.synthesize(f.prototype,"parent"),d.synthesize(f.prototype,"query"),d.synthesize(f.prototype,"from",function(a){return void 0!==a&&(a.chain(this),a.on("drop",this._collectionDroppedWrap)),this.$super(a)}),f.prototype._collectionDropped=function(a){this.drop()},f.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":}},f.prototype.drop=function(){return"dropped"!==this.state()&&(this.state("dropped"),this.emit("drop",this),this._from&&delete this._from._odm,delete this._name),!0},f.prototype.$=function(a,b){var c,d,g,h;return a===this._from.primaryKey()?(d={},d[a]=b,c=this._from.find(d,{$decouple:!1}),g=new e,g.setData(c,{$decouple:!1}),g._linked=this._from._linked):(g=new e,c=this._from.find({},{$decouple:!1}),c[0]&&c[0][a]&&(g.setData(c[0][a],{$decouple:!1}),b&&(c=g.find(b,{$decouple:!1}),g.setData(c,{$decouple:!1}))),g._linked=this._from._linked),h=new f(g),h.parent(this),h.query(b),h},f.prototype.prop=function(a,b){var c;if(void 0!==a){if(void 0!==b)return c={},c[a]=b,this._from.update({},c);if(this._from._data[0])return this._from._data[0][a]}return void 0},e.prototype.odm=function(){return this._odm||(this._odm=new f(this)),this._odm},d.finishModule("Odm"),b.exports=f},{"./Collection":4,"./Shared":33}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":29,"./Shared":33}],27:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)f.push(e);if(d=f.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=f.length;b>=0;b--)if(d=f.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw'ForerunnerDB.Overload "'+this.name()+'": Overloaded method does not have a matching signature for the passed arguments: '+JSON.stringify(f)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],28:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._collections=[],this._collectionDroppedWrap=function(){b._collectionDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._collections},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._collections.length;)this._removeCollection(this._collections[0]);return this._addCollection(a),this},h.prototype._addCollection=function(a){return-1===this._collections.indexOf(a)&&(this._collections.push(a),a.chain(this),a.on("drop",this._collectionDroppedWrap),this._refresh()),this},h.prototype._removeCollection=function(a){var b=this._collections.indexOf(a);return b>-1&&(this._collections.splice(a,1),a.unChain(this),a.off("drop",this._collectionDroppedWrap),this._refresh()),this},h.prototype._collectionDropped=function(a){a&&this._removeCollection(a)},h.prototype._refresh=function(){if("dropped"!==this._state){if(this._collections&&this._collections[0]){this._collData.primaryKey(this._collections[0].primaryKey());var a,b=[];for(a=0;a<this._collections.length;a++)b=b.concat(this._collections[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(){if("dropped"!==this._state){for(this._state="dropped",delete this._data,delete this._collData;this._collections.length;)this._removeCollection(this._collections[0]);delete this._collections,this._db&&this._name&&delete this._db._overview[this._name],delete this._name,this.emit("drop",this)}return!0},e.prototype.overview=function(a){return a?(this._overview=this._overview||{},this._overview[a]=this._overview[a]||new h(a).db(this),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b=[];for(a in this._overview)this._overview.hasOwnProperty(a)&&b.push({name:a,count:this._overview[a].count()});return b},d.finishModule("Overview"),b.exports=h},{"./Collection":4,"./Document":9,"./Shared":33}],29:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else f.push(b?{path:g,value:a[d]}:{path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":33}],30:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("localforage");k=function(){this.init.apply(this,arguments)},k.prototype.init=function(a){a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),n.config({driver:[n.INDEXEDDB,n.WEBSQL,n.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":n.setDriver(n.LOCALSTORAGE);break;case"WEBSQL":n.setDriver(n.WEBSQL);break;case"INDEXEDDB":n.setDriver(n.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return n.driver()},k.prototype.save=function(a,b,c){var d;switch(d=function(a,b){a="object"==typeof a?"json::fdb::"+JSON.stringify(a):"raw::fdb::"+a,b&&b(!1,a)},this.mode()){case"localforage":d(b,function(b,d){n.setItem(a,d).then(function(a){c&&c(!1,a)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c,d,e;switch(e=function(a,b){if(a){switch(c=a.split("::fdb::"),c[0]){case"json":d=JSON.parse(c[1]);break;case"raw":d=c[1]}b&&b(!1,d,{foundData:!0,rowCount:d.length})}else b&&b(!1,a,{foundData:!1,rowCount:0})},this.mode()){case"localforage":n.getItem(a).then(function(a){e(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":n.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){"dropped"!==this._state&&this.drop(!0)},"function":function(a){"dropped"!==this._state&&this.drop(!0,a)},"boolean":function(a){if("dropped"!==this._state){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";if(!this._db)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when the collection is not attached to a database!";this._db.persist.drop(this._db._name+"::"+this._name)}f.apply(this)}},"boolean, function":function(a,b){"dropped"!==this._state&&(a&&(this._name?this._db?this._db.persist.drop(this._db._name+"::"+this._name,b):b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"):b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")),f.apply(this,b))}}),e.prototype.save=function(a){this._name?this._db?this._db.persist.save(this._db._name+"::"+this._name,this._data,a):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;this._name?this._db?this._db.persist.load(this._db._name+"::"+this._name,function(c,d){c?a&&a(c):(d&&b.setData(d),a&&a(!1))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].load(b)},d.prototype.save=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].save(b)},m.finishModule("Persist"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./Shared":33,localforage:43}],31:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return"dropped"!==this._state&&(this._state="dropped",
this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":33}],32:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k=a("./Shared"),l=a("rest"),m=a("rest/interceptor/mime"),n=function(){this.init.apply(this,arguments)};n.prototype.init=function(a){this._endPoint="",this._client=l.wrap(m)},n.prototype._params=function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(encodeURIComponent(c)+"="+encodeURIComponent(a[c]));return b.join("&")},n.prototype.get=function(a,b,c){var d,e=this;a=void 0!==a?a:"",this._client({method:"get",path:this.endPoint()+a,params:b}).then(function(a){a.entity&&a.entity.error?c&&c(a.entity.error,a.entity,a):(d=e.collection(),d&&d.upsert(a.entity),c&&c(!1,a.entity,a))},function(a){c&&c(!0,a.entity,a)})},n.prototype.post=function(a,b,c){this._client({method:"post",path:this.endPoint()+a,entity:b,headers:{"Content-Type":"application/json"}}).then(function(a){a.entity&&a.entity.error?c&&c(a.entity.error,a.entity,a):c&&c(!1,a.entity,a)},function(a){c&&c(!0,a)})},k.synthesize(n.prototype,"sessionData"),k.synthesize(n.prototype,"endPoint"),k.synthesize(n.prototype,"collection"),k.addModule("Rest",n),k.mixin(n.prototype,"Mixin.ChainReactor"),d=k.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=k.overload,e.prototype.init=function(){this.rest=new n,this.rest.collection(this),h.apply(this,arguments)},d.prototype.init=function(){this.rest=new n,i.apply(this,arguments)},k.finishModule("Rest"),b.exports=n},{"./Collection":4,"./CollectionGroup":5,"./Shared":33,rest:46,"rest/interceptor/mime":51}],33:[function(a,b,c){"use strict";var d={version:"1.3.60",modules:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:function(a,b){var c=this.mixins[b];if(!c)throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])},synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:a("./Overload"),mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating")}};d.mixin(d,"Mixin.Events"),b.exports=d},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Triggers":23,"./Mixin.Updating":24,"./Overload":27}],34:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],35:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f("__FDB__view_privateData_"+this._name)},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a){var b=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var c,d,e,f,g,h,i;if(b._querySettings.query){if("insert"===a.type){if(c=a.data,c instanceof Array)for(f=[],i=0;i<c.length;i++)b._privateData._match(c[i],b._querySettings.query,"and",{})&&(f.push(c[i]),g=!0);else b._privateData._match(c,b._querySettings.query,"and",{})&&(f=c,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=b._privateData.diff(b._from.subset(b._querySettings.query,b._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=b._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=b._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var c=a.find(this._querySettings.query,this._querySettings.options);this._transformPrimaryKey(a.primaryKey()),this._transformSetData(c),this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(c),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket()}return this},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i,j,k;switch(a.type){case"setData":this.debug()&&console.log('ForerunnerDB.View: Setting data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"');var l=this._from.find(this._querySettings.query,this._querySettings.options);this._transformSetData(l),this._privateData.setData(l);break;case"insert":if(this.debug()&&console.log('ForerunnerDB.View: Inserting some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log('ForerunnerDB.View: Updating some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)i=f[d],this._activeBucket.remove(i),j=this._privateData._data.indexOf(i),e=this._activeBucket.insert(i),j!==e&&this._privateData._updateSpliceMove(this._privateData._data,j,e);if(this._transformEnabled&&this._transformIn)for(g=this._publicData.primaryKey(),k=0;k<f.length;k++)h={},i=f[k],h[g]=i[g],this._transformUpdate(h,i);break;case"remove":this.debug()&&console.log('ForerunnerDB.View: Removing some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){return this._privateData.distinct.apply(this._privateData,arguments)},l.prototype.primaryKey=function(){return this._privateData.primaryKey()},l.prototype.drop=function(){return"dropped"===this._state?!0:this._from?(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this),(this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.View: Dropping view "+this._name),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0):!1},l.prototype.db=function(a){return void 0!==a?(this._db=a,this.privateData().db(a),this.publicData().db(a),this):this._db},l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},l.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),b.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this._privateData&&this._privateData._data?this._privateData._data.length:0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformPrimaryKey(this.privateData().primaryKey()),this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},l.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))},l.prototype._transformInsert=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.insert(a,b)},l.prototype._transformUpdate=function(a,b,c){this._transformEnabled&&this._publicData&&this._publicData.update(a,b,c)},l.prototype._transformRemove=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.remove(a,b)},l.prototype._transformPrimaryKey=function(a){this._transformEnabled&&this._publicData&&this._publicData.primaryKey(a)},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw'ForerunnerDB.Collection "'+this.name()+'": Cannot create a view using this collection because a view with this name already exists: '+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){return this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Db.View: Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a]},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b=[];for(a in this._view)this._view.hasOwnProperty(a)&&b.push({name:a,count:this._view[a].count()});return b},d.finishModule("View"),b.exports=l},{"./ActiveBucket":3,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":31,"./Shared":33}],36:[function(a,b,c){function d(){if(!h){h=!0;for(var a,b=g.length;b;){a=g,g=[];for(var c=-1;++c<b;)a[c]();b=g.length}h=!1}}function e(){}var f=b.exports={},g=[],h=!1;f.nextTick=function(a){g.push(a),h||setTimeout(d,0)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=e,f.addListener=e,f.once=e,f.off=e,f.removeListener=e,f.removeAllListeners=e,f.emit=e,f.binding=function(a){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(a){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},{}],37:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:39}],38:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":37,asap:39}],39:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:36}],40:[function(a,b,c){(function(){"use strict";function c(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new m(function(a,d){var e=n.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(){e.result.createObjectStore(c.storeName)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=a(c.value,c.key,h++);void 0!==d?b(d):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){var f=d._dbInfo,g=f.db.transaction(f.storeName,"readwrite"),h=g.objectStore(f.storeName);null===b&&(b=void 0);var i=h.put(b,a);g.oncomplete=function(){void 0===b&&(b=null),c(b)},g.onabort=g.onerror=function(){var a=i.error?i.error:i.transaction.error;e(a)}})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=n||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(n){var o={_driver:"asyncStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=o:"function"==typeof define&&define.amd?define("asyncStorage",function(){return o}):this.asyncStorage=o}}).call(window)},{promise:38}],41:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=0;e>f;f++){var g=p.key(f),h=p.getItem(g);if(h&&(h=o.deserialize(h)),h=a(h,g.substring(d),f+1),void 0!==h)return h}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){("QuotaExceededError"===i.name||"NS_ERROR_DOM_QUOTA_REACHED"===i.name)&&f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":44,promise:38}],42:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":44,promise:38}],43:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){
var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){var k=new g(function(b){if(n===l.DEFINE)a([f],b);else if(n===l.EXPORT)switch(f){case i.INDEXEDDB:b(a("./drivers/indexeddb"));break;case i.LOCALSTORAGE:b(a("./drivers/localstorage"));break;case i.WEBSQL:b(a("./drivers/websql"))}else b(q[f])});k.then(function(a){i._extend(a),c()})}else h[f]?(i._extend(h[f]),c()):(i._driverSet=g.reject(j),d(j))}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":40,"./drivers/localstorage":41,"./drivers/websql":42,promise:38}],44:[function(a,b,c){(function(){"use strict";function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=h;a instanceof ArrayBuffer?(d=a,e+=j):(d=a.buffer,"[object Int8Array]"===c?e+=l:"[object Uint8Array]"===c?e+=m:"[object Uint8ClampedArray]"===c?e+=n:"[object Int16Array]"===c?e+=o:"[object Uint16Array]"===c?e+=q:"[object Int32Array]"===c?e+=p:"[object Uint32Array]"===c?e+=r:"[object Float32Array]"===c?e+=s:"[object Float64Array]"===c?e+=t:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var a=f(this.result);b(h+k+a)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){window.console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(a){if(a.substring(0,i)!==h)return JSON.parse(a);var b=a.substring(u),c=a.substring(i,u),d=e(b);switch(c){case j:return d;case k:return new Blob([d]);case l:return new Int8Array(d);case m:return new Uint8Array(d);case n:return new Uint8ClampedArray(d);case o:return new Int16Array(d);case q:return new Uint16Array(d);case p:return new Int32Array(d);case r:return new Uint32Array(d);case s:return new Float32Array(d);case t:return new Float64Array(d);default:throw new Error("Unkown type: "+c)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="__lfsc__:",i=h.length,j="arbf",k="blob",l="si08",m="ui08",n="uic8",o="si16",p="si32",q="ur16",r="ui32",s="fl32",t="fl64",u=i+j.length,v={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=v:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return v}):this.localforageSerializer=v}).call(window)},{}],45:[function(a,b,c){!function(a,b){"use strict";var c;a(function(a){function d(a,b){var c,d,e,f;if(c=a,e={},b){for(d in b)f=new RegExp("\\{"+d+"\\}"),f.test(c)?c=c.replace(f,encodeURIComponent(b[d]),"g"):e[d]=b[d];for(d in e)c+=-1===c.indexOf("?")?"?":"&",c+=encodeURIComponent(d),null!==e[d]&&void 0!==e[d]&&(c+="=",c+=encodeURIComponent(e[d]))}return c}function e(a,b){return 0===a.indexOf(b)}function f(a,b){return this instanceof f?void(a instanceof f?(this._template=a.template,this._params=g({},this._params,b)):(this._template=(a||"").toString(),this._params=b||{})):new f(a,b)}var g,h,i,j,k;return g=a("./util/mixin"),i=/([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?(\/[^?#]*)?(\?[^#]*)?(#\S*)?/i,j=/^([a-z][a-z0-9\-\+\.]*:\/\/|\/)/i,k=/([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?\//i,f.prototype={append:function(a,b){return new f(this._template+a,g({},this._params,b))},fullyQualify:function(){if(!b)return this;if(this.isFullyQualified())return this;var a=this._template;return e(a,"//")?a=h.protocol+a:e(a,"/")?a=h.origin+a:this.isAbsolute()||(a=h.origin+h.pathname.substring(0,h.pathname.lastIndexOf("/")+1)),-1===a.indexOf("/",8)&&(a+="/"),new f(a,this._params)},isAbsolute:function(){return j.test(this.build())},isFullyQualified:function(){return k.test(this.build())},isCrossOrigin:function(){if(!h)return!0;var a=this.parts();return a.protocol!==h.protocol||a.hostname!==h.hostname||a.port!==h.port},parts:function(){var a,b;return a=this.fullyQualify().build().match(i),b={href:a[0],protocol:a[1],host:a[3]||"",hostname:a[4]||"",port:a[6],pathname:a[7]||"",search:a[8]||"",hash:a[9]||""},b.origin=b.protocol+"//"+b.host,b.port=b.port||("https:"===b.protocol?"443":"http:"===b.protocol?"80":""),b},build:function(a){return d(this._template,g({},this._params,a))},toString:function(){return this.build()}},h=b?new f(b.href).parts():c,f})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)},"undefined"!=typeof window?window.location:void 0)},{"./util/mixin":81}],46:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("./client/default"),c=a("./client/xhr");return b.setPlatformDefaultClient(c),b})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./client/default":48,"./client/xhr":49}],47:[function(a,b,c){!function(a){"use strict";a(function(){return function(a,b){return b&&(a.skip=function(){return b}),a.wrap=function(b,c){return b(a,c)},a.chain=function(){return"undefined"!=typeof console&&console.log("rest.js: client.chain() is deprecated, use client.wrap() instead"),a.wrap.apply(this,arguments)},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],48:[function(a,b,c){!function(a){"use strict";var b;a(function(a){function c(){return e.apply(b,arguments)}var d,e,f;return d=a("../client"),c.setDefaultClient=function(a){e=a},c.getDefaultClient=function(){return e},c.resetDefaultClient=function(){e=f},c.setPlatformDefaultClient=function(a){if(f)throw new Error("Unable to redefine platformDefaultClient");e=f=a},d(c)})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../client":47}],49:[function(a,b,c){!function(a,b){"use strict";a(function(a){function c(a){var b={};return a?(a.trim().split(j).forEach(function(a){var c,d,e;c=a.indexOf(":"),d=g(a.substring(0,c).trim()),e=a.substring(c+1).trim(),b[d]?Array.isArray(b[d])?b[d].push(e):b[d]=[b[d],e]:b[d]=e}),b):b}function d(a,b){return Object.keys(b||{}).forEach(function(c){if(b.hasOwnProperty(c)&&c in a)try{a[c]=b[c]}catch(d){}}),a}var e,f,g,h,i,j;return e=a("when"),f=a("../UrlBuilder"),g=a("../util/normalizeHeaderName"),h=a("../util/responsePromise"),i=a("../client"),j=/[\r|\n]+/,i(function(a){return h.promise(function(e,g){var h,i,j,k,l,m,n,o;if(a="string"==typeof a?{path:a}:a||{},n={request:a},a.canceled)return n.error="precanceled",void g(n);if(o=a.engine||b.XMLHttpRequest,!o)return void g({request:a,error:"xhr-not-available"});l=a.entity,a.method=a.method||(l?"POST":"GET"),i=a.method,j=new f(a.path||"",a.params).build();try{h=n.raw=new o,d(h,a.mixin),h.open(i,j,!0),d(h,a.mixin),k=a.headers;for(m in k)("Content-Type"!==m||"multipart/form-data"!==k[m])&&h.setRequestHeader(m,k[m]);a.canceled=!1,a.cancel=function(){a.canceled=!0,h.abort(),g(n)},h.onreadystatechange=function(){a.canceled||h.readyState===(o.DONE||4)&&(n.status={code:h.status,text:h.statusText},n.headers=c(h.getAllResponseHeaders()),n.entity=h.responseText,n.status.code>0?e(n):setTimeout(function(){e(n)},0))};try{h.onerror=function(){n.error="loaderror",g(n)}}catch(p){}h.send(l)}catch(p){n.error="loaderror",g(n)}})})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)},"undefined"!=typeof window?window:void 0)},{"../UrlBuilder":45,"../client":47,"../util/normalizeHeaderName":82,"../util/responsePromise":83,when:78}],50:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){return a}function c(a){return a}function d(a){return a}function e(a){return l.promise(function(b,c){a.forEach(function(a){l(a,b,c)})})}function f(a){return this instanceof f?void i(this,a):new f(a)}function g(a){var g,i,m,n;return a=a||{},g=a.init||b,i=a.request||c,m=a.success||a.response||d,n=a.error||function(){return l((a.response||d).apply(this,arguments),l.reject,l.reject)},function(b,c){function d(a){var g,h;return g={},h={arguments:Array.prototype.slice.call(arguments),client:d},a="string"==typeof a?{path:a}:a||{},a.originator=a.originator||d,j(i.call(g,a,c,h),function(a){var d,i,j;return j=b,a instanceof f&&(i=a.abort,j=a.client||j,d=a.response,a=a.request),d=d||l(a,function(a){return l(j(a),function(a){return m.call(g,a,c,h)},function(a){return n.call(g,a,c,h)})}),i?e([d,i]):d},function(b){return l.reject({request:a,error:b})})}return"object"==typeof b&&(c=b),"function"!=typeof b&&(b=a.client||h),c=g(c||{}),k(d,b)}}var h,i,j,k,l;return h=a("./client/default"),i=a("./util/mixin"),j=a("./util/responsePromise"),k=a("./client"),l=a("when"),g.ComplexRequest=f,g})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./client":47,"./client/default":48,"./util/mixin":81,"./util/responsePromise":83,when:78}],51:[function(a,b,c){!function(a){"use strict";a(function(a){var b,c,d,e,f;return b=a("../interceptor"),c=a("../mime"),d=a("../mime/registry"),f=a("when"),e={read:function(a){return a},write:function(a){return a}},b({init:function(a){return a.registry=a.registry||d,a},request:function(a,b){var d,g;return g=a.headers||(a.headers={}),d=c.parse(g["Content-Type"]=g["Content-Type"]||b.mime||"text/plain"),g.Accept=g.Accept||b.accept||d.raw+", application/json;q=0.8, text/plain;q=0.5, */*;q=0.2","entity"in a?b.registry.lookup(d).otherwise(function(){if(b.permissive)return e;throw"mime-unknown"}).then(function(c){var e=b.client||a.originator;return f.attempt(c.write,a.entity,{client:e,request:a,mime:d,registry:b.registry}).otherwise(function(){throw"mime-serialization"}).then(function(b){return a.entity=b,a})}):a},response:function(a,b){if(!(a.headers&&a.headers["Content-Type"]&&a.entity))return a;var d=c.parse(a.headers["Content-Type"]);return b.registry.lookup(d).otherwise(function(){return e}).then(function(c){var e=b.client||a.request&&a.request.originator;return f.attempt(c.read,a.entity,{client:e,response:a,mime:d,registry:b.registry}).otherwise(function(b){throw a.error="mime-deserialization",a.cause=b,a}).then(function(b){return a.entity=b,a})})}})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../interceptor":50,"../mime":54,"../mime/registry":55,when:78}],52:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b){return 0===a.indexOf(b)}function c(a,b){return a.lastIndexOf(b)+b.length===a.length}var d,e;return d=a("../interceptor"),e=a("../UrlBuilder"),d({request:function(a,d){var f;return d.prefix&&!new e(a.path).isFullyQualified()&&(f=d.prefix,a.path&&(c(f,"/")||b(a.path,"/")||(f+="/"),f+=a.path),a.path=f),a}})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../UrlBuilder":45,"../interceptor":50}],53:[function(a,b,c){!function(a){"use strict";a(function(a){var b,c,d;return b=a("../interceptor"),c=a("../util/uriTemplate"),d=a("../util/mixin"),b({init:function(a){return a.params=a.params||{},a.template=a.template||"",a},request:function(a,b){var e,f;return e=a.path||b.template,f=d({},a.params,b.params),a.path=c.expand(e,f),delete a.params,a}})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../interceptor":50,"../util/mixin":81,"../util/uriTemplate":85}],54:[function(a,b,c){!function(a){"use strict";var b;a(function(){function a(a){var c,d;return c=a.split(";"),d=c[0].trim().split("+"),{raw:a,type:d[0],suffix:d[1]?"+"+d[1]:"",params:c.slice(1).reduce(function(a,c){return c=c.split("="),a[c[0].trim()]=c[1]?c[1].trim():b,a},{})}}return{parse:a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],55:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){this.lookup=function(b){var e;return e="string"==typeof b?c.parse(b):b,a[e.raw]?a[e.raw]:a[e.type+e.suffix]?a[e.type+e.suffix]:a[e.type]?a[e.type]:a[e.suffix]?a[e.suffix]:d.reject(new Error('Unable to locate converter for mime "'+e.raw+'"'))},this.delegate=function(a){return{read:function(){var b=arguments;return this.lookup(a).then(function(a){return a.read.apply(this,b)}.bind(this))}.bind(this),write:function(){var b=arguments;return this.lookup(a).then(function(a){return a.write.apply(this,b)}.bind(this))}.bind(this)}},this.register=function(b,c){return a[b]=d(c),a[b]},this.child=function(){return new b(Object.create(a))}}var c,d,e;return c=a("../mime"),d=a("when"),e=new b({}),e.register("application/hal",a("./type/application/hal")),e.register("application/json",a("./type/application/json")),e.register("application/x-www-form-urlencoded",a("./type/application/x-www-form-urlencoded")),e.register("multipart/form-data",a("./type/multipart/form-data")),e.register("text/plain",a("./type/text/plain")),e.register("+json",e.delegate("application/json")),e})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../mime":54,"./type/application/hal":56,"./type/application/json":57,"./type/application/x-www-form-urlencoded":58,"./type/multipart/form-data":59,"./type/text/plain":60,when:78}],56:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b,c){Object.defineProperty(a,b,{value:c,configurable:!0,enumerable:!1,writeable:!0})}var c,d,e,f,g,h;return c=a("../../../interceptor/pathPrefix"),d=a("../../../interceptor/template"),e=a("../../../util/find"),f=a("../../../util/lazyPromise"),g=a("../../../util/responsePromise"),h=a("when"),{read:function(a,i){function j(a,b){(b&&l&&l.warn||l.log)&&(l.warn||l.log).call(l,"Relationship '"+a+"' is deprecated, see "+b)}var k,l;return i=i||{},k=i.client,l=i.console||l,i.registry.lookup(i.mime.suffix).then(function(l){return h(l.read(a,i)).then(function(a){return e.findProperties(a,"_embedded",function(a,c,d){Object.keys(a).forEach(function(d){if(!(d in c)){var e=g({entity:a[d]});b(c,d,e)}}),b(c,d,a)}),e.findProperties(a,"_links",function(a,e,h){Object.keys(a).forEach(function(c){var h=a[c];c in e||b(e,c,g.make(f(function(){return h.deprecation&&j(c,h.deprecation),h.templated===!0?d(k)({path:h.href}):k({path:h.href})})))}),b(e,h,a),b(e,"clientFor",function(b,e){var f=a[b];if(!f)throw new Error("Unknown relationship: "+b);return f.deprecation&&j(b,f.deprecation),f.templated===!0?d(e||k,{template:f.href}):c(e||k,{prefix:f.href})}),b(e,"requestFor",function(a,b,c){var d=this.clientFor(a,c);return d(b)})}),a})})},write:function(a,b){return b.registry.lookup(b.mime.suffix).then(function(c){return c.write(a,b)})}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../../../interceptor/pathPrefix":52,"../../../interceptor/template":53,"../../../util/find":79,"../../../util/lazyPromise":80,"../../../util/responsePromise":83,when:78}],57:[function(a,b,c){!function(a){"use strict";a(function(){function a(b,c){return{read:function(a){return JSON.parse(a,b)},write:function(a){return JSON.stringify(a,c)},extend:a}}return a()})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],58:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){return a=encodeURIComponent(a),a.replace(d,"+")}function b(a){return a=a.replace(e," "),decodeURIComponent(a)}function c(b,d,e){return Array.isArray(e)?e.forEach(function(a){b=c(b,d,a)}):(b.length>0&&(b+="&"),b+=a(d),void 0!==e&&null!==e&&(b+="="+a(e))),b}var d,e;return d=/%20/g,e=/\+/g,{read:function(a){var c={};return a.split("&").forEach(function(a){var d,e,f;d=a.split("="),e=b(d[0]),f=2===d.length?b(d[1]):null,e in c?(Array.isArray(c[e])||(c[e]=[c[e]]),c[e].push(f)):c[e]=f}),c},write:function(a){var b="";return Object.keys(a).forEach(function(d){b=c(b,d,a[d])}),b}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],59:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){return a&&1===a.nodeType&&"FORM"===a.tagName}function b(a){var b,c=new FormData;for(var d in a)a.hasOwnProperty(d)&&(b=a[d],b instanceof File?c.append(d,b,b.name):b instanceof Blob?c.append(d,b):c.append(d,String(b)));return c}return{write:function(c){if("undefined"==typeof FormData)throw new Error("The multipart/form-data mime serializer requires FormData support");if(c instanceof FormData)return c;if(a(c))return new FormData(c);if("object"==typeof c&&null!==c)return b(c);throw new Error("Unable to create FormData from object "+c)}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],60:[function(a,b,c){!function(a){"use strict";a(function(){return{read:function(a){return a},write:function(a){return a.toString()}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],61:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("./makePromise"),c=a("./Scheduler"),d=a("./env").asap;return b({scheduler:new c(d)})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./Scheduler":62,"./env":74,"./makePromise":76}],62:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){this._async=a,this._running=!1,this._queue=this,this._queueLen=0,this._afterQueue={},this._afterQueueLen=0;var b=this;this.drain=function(){b._drain()}}return a.prototype.enqueue=function(a){this._queue[this._queueLen++]=a,this.run()},a.prototype.afterQueue=function(a){this._afterQueue[this._afterQueueLen++]=a,this.run()},a.prototype.run=function(){this._running||(this._running=!0,this._async(this.drain))},a.prototype._drain=function(){for(var a=0;a<this._queueLen;++a)this._queue[a].run(),this._queue[a]=void 0;for(this._queueLen=0,this._running=!1,a=0;a<this._afterQueueLen;++a)this._afterQueue[a].run(),this._afterQueue[a]=void 0;this._afterQueueLen=0},a})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],63:[function(a,b,c){!function(a){"use strict";a(function(){function a(b){Error.call(this),this.message=b,this.name=a.name,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,a)}return a.prototype=Object.create(Error.prototype),a.prototype.constructor=a,a})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],64:[function(a,b,c){!function(a){"use strict";a(function(){function a(a,c){function d(b,d,f){var g=a._defer(),h=f.length,i=new Array(h);return e({f:b,thisArg:d,args:f,params:i,i:h-1,call:c},g._handler),g}function e(b,d){if(b.i<0)return c(b.f,b.thisArg,b.params,d);var e=a._handler(b.args[b.i]);e.fold(f,b,void 0,d)}function f(a,b,c){a.params[a.i]=b,a.i-=1,e(a,c)}return arguments.length<2&&(c=b),d}function b(a,b,c,d){try{d.resolve(a.apply(b,c))}catch(e){d.reject(e)}}return a.tryCatchResolve=b,a})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],65:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("../state"),c=a("../apply");return function(a){function d(b){function c(a){k=null,this.resolve(a)}function d(a){this.resolved||(k.push(a),0===--j&&this.reject(k))}for(var e,f,g=a._defer(),h=g._handler,i=b.length>>>0,j=i,k=[],l=0;i>l;++l)if(f=b[l],void 0!==f||l in b){if(e=a._handler(f),e.state()>0){h.become(e),a._visitRemaining(b,l,e);break}e.visit(h,c,d)}else--j;return 0===j&&h.reject(new RangeError("any(): array must not be empty")),g}function e(b,c){function d(a){this.resolved||(k.push(a),0===--n&&(l=null,this.resolve(k)))}function e(a){this.resolved||(l.push(a),0===--f&&(k=null,this.reject(l)))}var f,g,h,i=a._defer(),j=i._handler,k=[],l=[],m=b.length>>>0,n=0;for(h=0;m>h;++h)g=b[h],(void 0!==g||h in b)&&++n;for(c=Math.max(c,0),f=n-c+1,n=Math.min(c,n),c>n?j.reject(new RangeError("some(): array must contain at least "+c+" item(s), but had "+n)):0===n&&j.resolve(k),h=0;m>h;++h)g=b[h],(void 0!==g||h in b)&&a._handler(g).visit(j,d,e,j.notify);return i}function f(b,c){return a._traverse(c,b)}function g(b,c){var d=s.call(b);return a._traverse(c,d).then(function(a){return h(d,a)})}function h(b,c){for(var d=c.length,e=new Array(d),f=0,g=0;d>f;++f)c[f]&&(e[g++]=a._handler(b[f]).value);return e.length=g,e}function i(a){return p(a.map(j))}function j(c){var d=a._handler(c);return 0===d.state()?o(c).then(b.fulfilled,b.rejected):(d._unreport(),b.inspect(d))}function k(a,b){return arguments.length>2?q.call(a,m(b),arguments[2]):q.call(a,m(b))}function l(a,b){return arguments.length>2?r.call(a,m(b),arguments[2]):r.call(a,m(b))}function m(a){return function(b,c,d){return n(a,void 0,[b,c,d])}}var n=c(a),o=a.resolve,p=a.all,q=Array.prototype.reduce,r=Array.prototype.reduceRight,s=Array.prototype.slice;return a.any=d,a.some=e,a.settle=i,a.map=f,a.filter=g,a.reduce=k,a.reduceRight=l,a.prototype.spread=function(a){return this.then(p).then(function(b){return a.apply(this,b)})},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../apply":64,"../state":77}],66:[function(a,b,c){!function(a){"use strict";a(function(){function a(){throw new TypeError("catch predicate must be a function")}function b(a,b){return c(b)?a instanceof b:b(a)}function c(a){return a===Error||null!=a&&a.prototype instanceof Error}function d(a){return("object"==typeof a||"function"==typeof a)&&null!==a}function e(a){return a}return function(c){function f(a,c){return function(d){return b(d,c)?a.call(this,d):j(d)}}function g(a,b,c,e){var f=a.call(b);return d(f)?h(f,c,e):c(e)}function h(a,b,c){return i(a).then(function(){return b(c)})}var i=c.resolve,j=c.reject,k=c.prototype["catch"];return c.prototype.done=function(a,b){this._handler.visit(this._handler.receiver,a,b)},c.prototype["catch"]=c.prototype.otherwise=function(b){return arguments.length<2?k.call(this,b):"function"!=typeof b?this.ensure(a):k.call(this,f(arguments[1],b))},c.prototype["finally"]=c.prototype.ensure=function(a){return"function"!=typeof a?this:this.then(function(b){return g(a,this,e,b)},function(b){return g(a,this,j,b)})},c.prototype["else"]=c.prototype.orElse=function(a){return this.then(void 0,function(){return a})},c.prototype["yield"]=function(a){return this.then(function(){return a})},c.prototype.tap=function(a){return this.then(a)["yield"](this)},c}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],67:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){return a.prototype.fold=function(b,c){var d=this._beget();return this._handler.fold(function(c,d,e){a._handler(c).fold(function(a,c,d){d.resolve(b.call(this,c,a))},d,this,e)},c,d._handler.receiver,d._handler),d},a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],68:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("../state").inspect;return function(a){return a.prototype.inspect=function(){return b(a._handler(this))},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../state":77}],69:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){function b(a,b,d,e){return c(function(b){return[b,a(b)]},b,d,e)}function c(a,b,e,f){function g(f,g){return d(e(f)).then(function(){return c(a,b,e,g)})}return d(f).then(function(c){return d(b(c)).then(function(b){return b?c:d(a(c)).spread(g)})})}var d=a.resolve;return a.iterate=b,a.unfold=c,a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],70:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){return a.prototype.progress=function(a){return this.then(void 0,void 0,a)},a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],71:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b,d,e){return c.setTimer(function(){a(d,e,b)},b)}var c=a("../env"),d=a("../TimeoutError");return function(a){function e(a,c,d){b(f,a,c,d)}function f(a,b){b.resolve(a)}function g(a,b,c){var e="undefined"==typeof a?new d("timed out after "+c+"ms"):a;b.reject(e)}return a.prototype.delay=function(a){var b=this._beget();return this._handler.fold(e,a,void 0,b._handler),b},a.prototype.timeout=function(a,d){var e=this._beget(),f=e._handler,h=b(g,a,d,e._handler);return this._handler.visit(f,function(a){c.clearTimer(h),this.resolve(a)},function(a){c.clearTimer(h),this.reject(a)},f.notify),e},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../TimeoutError":63,"../env":74}],72:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){throw a}function c(){}var d=a("../env").setTimer,e=a("../format");return function(a){function f(a){a.handled||(n.push(a),k("Potentially unhandled rejection ["+a.id+"] "+e.formatError(a.value)))}function g(a){var b=n.indexOf(a);b>=0&&(n.splice(b,1),l("Handled previous rejection ["+a.id+"] "+e.formatObject(a.value)))}function h(a,b){m.push(a,b),null===o&&(o=d(i,0))}function i(){for(o=null;m.length>0;)m.shift()(m.shift())}var j,k=c,l=c;"undefined"!=typeof console&&(j=console,k="undefined"!=typeof j.error?function(a){j.error(a)}:function(a){j.log(a)},l="undefined"!=typeof j.info?function(a){j.info(a)}:function(a){j.log(a)}),a.onPotentiallyUnhandledRejection=function(a){h(f,a)},a.onPotentiallyUnhandledRejectionHandled=function(a){h(g,a)},a.onFatalRejection=function(a){h(b,a.value)};var m=[],n=[],o=null;return a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../env":74,"../format":75}],73:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){return a.prototype["with"]=a.prototype.withThis=function(a){var b=this._beget(),c=b._handler;return c.receiver=a,this._handler.chain(c,a),b},a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],74:[function(a,b,c){(function(c){!function(a){"use strict";a(function(a){function b(){return"undefined"!=typeof c&&null!==c&&"function"==typeof c.nextTick}function d(){return"function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver}function e(a){function b(){var a=c;c=void 0,a()}var c,d=document.createTextNode(""),e=new a(b);e.observe(d,{characterData:!0});var f=0;return function(a){c=a,d.data=f^=1}}var f,g="undefined"!=typeof setTimeout&&setTimeout,h=function(a,b){return setTimeout(a,b)},i=function(a){return clearTimeout(a)},j=function(a){return g(a,0)};if(b())j=function(a){return c.nextTick(a)};else if(f=d())j=e(f);else if(!g){var k=a,l=k("vertx");h=function(a,b){return l.setTimer(b,a)},i=l.cancelTimer,j=l.runOnLoop||l.runOnContext}return{setTimer:h,clearTimer:i,asap:j}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})}).call(this,a("_process"))},{_process:36}],75:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){var c="object"==typeof a&&null!==a&&a.stack?a.stack:b(a);return a instanceof Error?c:c+" (WARNING: non-Error used)"}function b(a){var b=String(a);return"[object Object]"===b&&"undefined"!=typeof JSON&&(b=c(a,b)),b}function c(a,b){try{return JSON.stringify(a)}catch(c){return b}}return{formatError:a,formatObject:b,tryStringify:c}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],76:[function(a,b,c){(function(a){!function(b){"use strict";b(function(){return function(b){function c(a,b){this._handler=a===u?b:d(a)}function d(a){function b(a){e.resolve(a)}function c(a){e.reject(a)}function d(a){e.notify(a)}var e=new w;try{a(b,c,d)}catch(f){c(f)}return e}function e(a){return J(a)?a:new c(u,new x(r(a)))}function f(a){return new c(u,new x(new A(a)))}function g(){return aa}function h(){return new c(u,new w)}function i(a,b){var c=new w(a.receiver,a.join().context);return new b(u,c)}function j(a){return l(T,null,a)}function k(a,b){return l(O,a,b)}function l(a,b,d){function e(c,e,g){g.resolved||m(d,f,c,a(b,e,c),g)}function f(a,b,c){k[a]=b,0===--j&&c.become(new z(k))}for(var g,h="function"==typeof b?e:f,i=new w,j=d.length>>>0,k=new Array(j),l=0;l<d.length&&!i.resolved;++l)g=d[l],void 0!==g||l in d?m(d,h,l,g,i):--j;return 0===j&&i.become(new z(k)),new c(u,i)}function m(a,b,c,d,e){if(K(d)){var f=s(d),g=f.state();0===g?f.fold(b,c,void 0,e):g>0?b(c,f.value,e):(e.become(f),
n(a,c+1,f))}else b(c,d,e)}function n(a,b,c){for(var d=b;d<a.length;++d)o(r(a[d]),c)}function o(a,b){if(a!==b){var c=a.state();0===c?a.visit(a,void 0,a._unreport):0>c&&a._unreport()}}function p(a){return"object"!=typeof a||null===a?f(new TypeError("non-iterable passed to race()")):0===a.length?g():1===a.length?e(a[0]):q(a)}function q(a){var b,d,e,f=new w;for(b=0;b<a.length;++b)if(d=a[b],void 0!==d||b in a){if(e=r(d),0!==e.state()){f.become(e),n(a,b+1,e);break}e.visit(f,f.resolve,f.reject)}return new c(u,f)}function r(a){return J(a)?a._handler.join():K(a)?t(a):new z(a)}function s(a){return J(a)?a._handler.join():t(a)}function t(a){try{var b=a.then;return"function"==typeof b?new y(b,a):new z(a)}catch(c){return new A(c)}}function u(){}function v(){}function w(a,b){c.createContext(this,b),this.consumers=void 0,this.receiver=a,this.handler=void 0,this.resolved=!1}function x(a){this.handler=a}function y(a,b){w.call(this),W.enqueue(new G(a,b,this))}function z(a){c.createContext(this),this.value=a}function A(a){c.createContext(this),this.id=++$,this.value=a,this.handled=!1,this.reported=!1,this._report()}function B(a,b){this.rejection=a,this.context=b}function C(a){this.rejection=a}function D(){return new A(new TypeError("Promise cycle"))}function E(a,b){this.continuation=a,this.handler=b}function F(a,b){this.handler=b,this.value=a}function G(a,b,c){this._then=a,this.thenable=b,this.resolver=c}function H(a,b,c,d,e){try{a.call(b,c,d,e)}catch(f){d(f)}}function I(a,b,c,d){this.f=a,this.z=b,this.c=c,this.to=d,this.resolver=Z,this.receiver=this}function J(a){return a instanceof c}function K(a){return("object"==typeof a||"function"==typeof a)&&null!==a}function L(a,b,d,e){return"function"!=typeof a?e.become(b):(c.enterContext(b),P(a,b.value,d,e),void c.exitContext())}function M(a,b,d,e,f){return"function"!=typeof a?f.become(d):(c.enterContext(d),Q(a,b,d.value,e,f),void c.exitContext())}function N(a,b,d,e,f){return"function"!=typeof a?f.notify(b):(c.enterContext(d),R(a,b,e,f),void c.exitContext())}function O(a,b,c){try{return a(b,c)}catch(d){return f(d)}}function P(a,b,c,d){try{d.become(r(a.call(c,b)))}catch(e){d.become(new A(e))}}function Q(a,b,c,d,e){try{a.call(d,b,c,e)}catch(f){e.become(new A(f))}}function R(a,b,c,d){try{d.notify(a.call(c,b))}catch(e){d.notify(e)}}function S(a,b){b.prototype=Y(a.prototype),b.prototype.constructor=b}function T(a,b){return b}function U(){}function V(){return"undefined"!=typeof a&&null!==a&&"function"==typeof a.emit?function(b,c){return"unhandledRejection"===b?a.emit(b,c.value,c):a.emit(b,c)}:"undefined"!=typeof self&&"function"==typeof CustomEvent?function(a,b,c){var d=!1;try{var e=new c("unhandledRejection");d=e instanceof c}catch(f){}return d?function(a,d){var e=new c(a,{detail:{reason:d.value,key:d},bubbles:!1,cancelable:!0});return!b.dispatchEvent(e)}:a}(U,self,CustomEvent):U}var W=b.scheduler,X=V(),Y=Object.create||function(a){function b(){}return b.prototype=a,new b};c.resolve=e,c.reject=f,c.never=g,c._defer=h,c._handler=r,c.prototype.then=function(a,b,c){var d=this._handler,e=d.join().state();if("function"!=typeof a&&e>0||"function"!=typeof b&&0>e)return new this.constructor(u,d);var f=this._beget(),g=f._handler;return d.chain(g,d.receiver,a,b,c),f},c.prototype["catch"]=function(a){return this.then(void 0,a)},c.prototype._beget=function(){return i(this._handler,this.constructor)},c.all=j,c.race=p,c._traverse=k,c._visitRemaining=n,u.prototype.when=u.prototype.become=u.prototype.notify=u.prototype.fail=u.prototype._unreport=u.prototype._report=U,u.prototype._state=0,u.prototype.state=function(){return this._state},u.prototype.join=function(){for(var a=this;void 0!==a.handler;)a=a.handler;return a},u.prototype.chain=function(a,b,c,d,e){this.when({resolver:a,receiver:b,fulfilled:c,rejected:d,progress:e})},u.prototype.visit=function(a,b,c,d){this.chain(Z,a,b,c,d)},u.prototype.fold=function(a,b,c,d){this.when(new I(a,b,c,d))},S(u,v),v.prototype.become=function(a){a.fail()};var Z=new v;S(u,w),w.prototype._state=0,w.prototype.resolve=function(a){this.become(r(a))},w.prototype.reject=function(a){this.resolved||this.become(new A(a))},w.prototype.join=function(){if(!this.resolved)return this;for(var a=this;void 0!==a.handler;)if(a=a.handler,a===this)return this.handler=D();return a},w.prototype.run=function(){var a=this.consumers,b=this.handler;this.handler=this.handler.join(),this.consumers=void 0;for(var c=0;c<a.length;++c)b.when(a[c])},w.prototype.become=function(a){this.resolved||(this.resolved=!0,this.handler=a,void 0!==this.consumers&&W.enqueue(this),void 0!==this.context&&a._report(this.context))},w.prototype.when=function(a){this.resolved?W.enqueue(new E(a,this.handler)):void 0===this.consumers?this.consumers=[a]:this.consumers.push(a)},w.prototype.notify=function(a){this.resolved||W.enqueue(new F(a,this))},w.prototype.fail=function(a){var b="undefined"==typeof a?this.context:a;this.resolved&&this.handler.join().fail(b)},w.prototype._report=function(a){this.resolved&&this.handler.join()._report(a)},w.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},S(u,x),x.prototype.when=function(a){W.enqueue(new E(a,this))},x.prototype._report=function(a){this.join()._report(a)},x.prototype._unreport=function(){this.join()._unreport()},S(w,y),S(u,z),z.prototype._state=1,z.prototype.fold=function(a,b,c,d){M(a,b,this,c,d)},z.prototype.when=function(a){L(a.fulfilled,this,a.receiver,a.resolver)};var $=0;S(u,A),A.prototype._state=-1,A.prototype.fold=function(a,b,c,d){d.become(this)},A.prototype.when=function(a){"function"==typeof a.rejected&&this._unreport(),L(a.rejected,this,a.receiver,a.resolver)},A.prototype._report=function(a){W.afterQueue(new B(this,a))},A.prototype._unreport=function(){this.handled||(this.handled=!0,W.afterQueue(new C(this)))},A.prototype.fail=function(a){this.reported=!0,X("unhandledRejection",this),c.onFatalRejection(this,void 0===a?this.context:a)},B.prototype.run=function(){this.rejection.handled||this.rejection.reported||(this.rejection.reported=!0,X("unhandledRejection",this.rejection)||c.onPotentiallyUnhandledRejection(this.rejection,this.context))},C.prototype.run=function(){this.rejection.reported&&(X("rejectionHandled",this.rejection)||c.onPotentiallyUnhandledRejectionHandled(this.rejection))},c.createContext=c.enterContext=c.exitContext=c.onPotentiallyUnhandledRejection=c.onPotentiallyUnhandledRejectionHandled=c.onFatalRejection=U;var _=new u,aa=new c(u,_);return E.prototype.run=function(){this.handler.join().when(this.continuation)},F.prototype.run=function(){var a=this.handler.consumers;if(void 0!==a)for(var b,c=0;c<a.length;++c)b=a[c],N(b.progress,this.value,this.handler,b.receiver,b.resolver)},G.prototype.run=function(){function a(a){d.resolve(a)}function b(a){d.reject(a)}function c(a){d.notify(a)}var d=this.resolver;H(this._then,this.thenable,a,b,c)},I.prototype.fulfilled=function(a){this.f.call(this.c,this.z,a,this.to)},I.prototype.rejected=function(a){this.to.reject(a)},I.prototype.progress=function(a){this.to.notify(a)},c}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})}).call(this,a("_process"))},{_process:36}],77:[function(a,b,c){!function(a){"use strict";a(function(){function a(){return{state:"pending"}}function b(a){return{state:"rejected",reason:a}}function c(a){return{state:"fulfilled",value:a}}function d(d){var e=d.state();return 0===e?a():e>0?c(d.value):b(d.value)}return{pending:a,fulfilled:c,rejected:b,inspect:d}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],78:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b,c,d){var e=x.resolve(a);return arguments.length<2?e:e.then(b,c,d)}function c(a){return new x(a)}function d(a){return function(){for(var b=0,c=arguments.length,d=new Array(c);c>b;++b)d[b]=arguments[b];return y(a,this,d)}}function e(a){for(var b=0,c=arguments.length-1,d=new Array(c);c>b;++b)d[b]=arguments[b+1];return y(a,this,d)}function f(){return new g}function g(){function a(a){d._handler.resolve(a)}function b(a){d._handler.reject(a)}function c(a){d._handler.notify(a)}var d=x._defer();this.promise=d,this.resolve=a,this.reject=b,this.notify=c,this.resolver={resolve:a,reject:b,notify:c}}function h(a){return a&&"function"==typeof a.then}function i(){return x.all(arguments)}function j(a){return b(a,x.all)}function k(a){return b(a,x.settle)}function l(a,c){return b(a,function(a){return x.map(a,c)})}function m(a,c){return b(a,function(a){return x.filter(a,c)})}var n=a("./lib/decorators/timed"),o=a("./lib/decorators/array"),p=a("./lib/decorators/flow"),q=a("./lib/decorators/fold"),r=a("./lib/decorators/inspect"),s=a("./lib/decorators/iterate"),t=a("./lib/decorators/progress"),u=a("./lib/decorators/with"),v=a("./lib/decorators/unhandledRejection"),w=a("./lib/TimeoutError"),x=[o,p,q,s,t,r,u,n,v].reduce(function(a,b){return b(a)},a("./lib/Promise")),y=a("./lib/apply")(x);return b.promise=c,b.resolve=x.resolve,b.reject=x.reject,b.lift=d,b["try"]=e,b.attempt=e,b.iterate=x.iterate,b.unfold=x.unfold,b.join=i,b.all=j,b.settle=k,b.any=d(x.any),b.some=d(x.some),b.race=d(x.race),b.map=l,b.filter=m,b.reduce=d(x.reduce),b.reduceRight=d(x.reduceRight),b.isPromiseLike=h,b.Promise=x,b.defer=f,b.TimeoutError=w,b})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./lib/Promise":61,"./lib/TimeoutError":63,"./lib/apply":64,"./lib/decorators/array":65,"./lib/decorators/flow":66,"./lib/decorators/fold":67,"./lib/decorators/inspect":68,"./lib/decorators/iterate":69,"./lib/decorators/progress":70,"./lib/decorators/timed":71,"./lib/decorators/unhandledRejection":72,"./lib/decorators/with":73}],79:[function(a,b,c){!function(a){"use strict";a(function(){return{findProperties:function a(b,c,d){"object"==typeof b&&null!==b&&(c in b&&d(b[c],b,c),Object.keys(b).forEach(function(e){a(b[e],c,d)}))}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],80:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){var b,d,e,f,g;return b=c.defer(),d=!1,e=b.resolver,f=b.promise,g=f.then,f.then=function(){return d||(d=!0,c.attempt(a).then(e.resolve,e.reject)),g.apply(f,arguments)},f}var c;return c=a("when"),b})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{when:78}],81:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){var c,d,e,f;for(a||(a={}),c=1,d=arguments.length;d>c;c+=1){e=arguments[c];for(f in e)f in a&&(a[f]===e[f]||f in b&&b[f]===e[f])||(a[f]=e[f])}return a}var b={};return a})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],82:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){return a.toLowerCase().split("-").map(function(a){return a.charAt(0).toUpperCase()+a.slice(1)}).join("-")}return a})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],83:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b){return a.then(function(a){return a&&a[b]},function(a){return j.reject(a&&a[b])})}function c(){return b(this,"entity")}function d(){return b(b(this,"status"),"code")}function e(){return b(this,"headers")}function f(a){return a=k(a),b(this.headers(),a)}function g(a){return a=[].concat(a),h(j.reduce(a,function(a,b){if("string"==typeof b&&(b={rel:b}),"function"!=typeof a.entity.clientFor)throw new Error("Hypermedia response expected");var c=a.entity.clientFor(b.rel);return c({params:b.params})},this))}function h(a){return a.status=d,a.headers=e,a.header=f,a.entity=c,a.follow=g,a}function i(){return h(j.apply(j,arguments))}var j=a("when"),k=a("./normalizeHeaderName");return i.make=h,i.reject=function(a){return h(j.reject(a))},i.promise=function(a){return h(j.promise(a))},i})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./normalizeHeaderName":82,when:78}],84:[function(a,b,c){!function(a){"use strict";a(function(){function a(a,b){if("string"!=typeof a)throw new Error("String required for URL encoding");return a.split("").map(function(a){if(b.hasOwnProperty(a))return a;var c=a.charCodeAt(0);return 127>=c?"%"+c.toString(16).toUpperCase():encodeURIComponent(a).toUpperCase()}).join("")}function b(b){return b=b||d.unreserved,function(c){return a(c,b)}}function c(a){return decodeURIComponent(a)}var d;return d=function(){var a={alpha:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",digit:"0123456789"};return a.genDelims=":/?#[]@",a.subDelims="!$&'()*+,;=",a.reserved=a.genDelims+a.subDelims,a.unreserved=a.alpha+a.digit+"-._~",a.url=a.reserved+a.unreserved,a.scheme=a.alpha+a.digit+"+-.",a.userinfo=a.unreserved+a.subDelims+":",a.host=a.unreserved+a.subDelims,a.port=a.digit,a.pchar=a.unreserved+a.subDelims+":@",a.segment=a.pchar,a.path=a.segment+"/",a.query=a.pchar+"/?",a.fragment=a.pchar+"/?",Object.keys(a).reduce(function(b,c){return b[c]=a[c].split("").reduce(function(a,b){return a[b]=!0,a},{}),b},{})}(),{decode:c,encode:b(),encodeURL:b(d.url),encodeScheme:b(d.scheme),encodeUserInfo:b(d.userinfo),encodeHost:b(d.host),encodePort:b(d.port),encodePathSegment:b(d.segment),encodePath:b(d.path),encodeQuery:b(d.query),encodeFragment:b(d.fragment)}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],85:[function(a,b,c){!function(a){"use strict";var b;a(function(a){function c(a,c,d){return c.split(",").reduce(function(c,e){var g,i;if(g={},"*"===e.slice(-1)&&(e=e.slice(0,-1),g.explode=!0),h.test(e)){var j=h.exec(e);e=j[1],g.maxLength=parseInt(j[2])}return e=f.decode(e),i=d[e],i===b||null===i?c:("string"==typeof i?(g.maxLength&&(i=i.slice(0,g.maxLength)),c+=c.length?a.separator:a.first,a.named&&(c+=a.encoder(e),c+=i.length?"=":a.empty),c+=a.encoder(i)):c+=Array.isArray(i)?i.reduce(function(b,c){return b.length?(b+=g.explode?a.separator:",",a.named&&g.explode&&(b+=a.encoder(e),b+=c.length?"=":a.empty)):(b+=a.first,a.named&&(b+=a.encoder(e),b+=c.length?"=":a.empty)),b+=a.encoder(c)},""):Object.keys(i).reduce(function(b,c){return b.length?b+=g.explode?a.separator:",":(b+=a.first,a.named&&!g.explode&&(b+=a.encoder(e),b+=i[c].length?"=":a.empty)),b+=a.encoder(c),b+=g.explode?"=":",",b+=a.encoder(i[c])},""),c)},"")}function d(a,b){var d;if(d=g[a.slice(0,1)],d?a=a.slice(1):d=g[""],d.reserved)throw new Error("Reserved expression operations are not supported");return c(d,a,b)}function e(a,b){var c,e,f;for(f="",e=0;;){if(c=a.indexOf("{",e),-1===c){f+=a.slice(e);break}f+=a.slice(e,c),e=a.indexOf("}",c)+1,f+=d(a.slice(c+1,e-1),b)}return f}var f,g,h;return f=a("./uriEncoder"),h=/^([^:]*):([0-9]+)$/,g={"":{first:"",separator:",",named:!1,empty:"",encoder:f.encode},"+":{first:"",separator:",",named:!1,empty:"",encoder:f.encodeURL},"#":{first:"#",separator:",",named:!1,empty:"",encoder:f.encodeURL},".":{first:".",separator:".",named:!1,empty:"",encoder:f.encode},"/":{first:"/",separator:"/",named:!1,empty:"",encoder:f.encode},";":{first:";",separator:";",named:!0,empty:"",encoder:f.encode},"?":{first:"?",separator:"&",named:!0,empty:"=",encoder:f.encode},"&":{first:"&",separator:"&",named:!0,empty:"=",encoder:f.encode},"=":{reserved:!0},",":{reserved:!0},"!":{reserved:!0},"@":{reserved:!0},"|":{reserved:!0}},{expand:e}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./uriEncoder":84}]},{},[1]); |
client/src/react/financial/AccountContainer.js | charlesj/Apollo | import React from 'react'
import PropTypes from 'prop-types'
import { connect, } from 'react-redux'
import Flexbox from 'flexbox-react'
import {
Container,
TextButton,
} from '../_controls'
import AccountForm from './AccountForm'
import AccountDisplay from './AccountDisplay'
import { financialSelectors, } from '../../redux/selectors'
import { financialActions, } from '../../redux/actions'
import './accountContainer.css'
function AccountContainer(props) {
const {
selectedAccount,
saveAccount,
accountMode,
setAccountMode,
} = props
const isEditMode = (accountMode==='edit')
return (
<Container width={500}>
<Flexbox className='accountTitle'>
<Flexbox flexGrow={1}>{selectedAccount.name}</Flexbox>
<Flexbox><TextButton onClick={() => setAccountMode('edit')}>edit</TextButton></Flexbox>
</Flexbox>
{ isEditMode &&
<AccountForm
account={selectedAccount}
onSubmit={saveAccount}
onCancel={() => setAccountMode('view')}
/>}
{ ( !isEditMode && <AccountDisplay account={selectedAccount} />)}
</Container>
)
}
AccountContainer.propTypes = {
selectedAccount: PropTypes.object.isRequired,
saveAccount: PropTypes.func.isRequired,
selectAccount: PropTypes.func.isRequired,
setAccountMode: PropTypes.func.isRequired,
accountMode: PropTypes.string.isRequired,
}
function mapStateToProps(state){
return {
accountMode: financialSelectors.accountMode(state),
}
}
function mapDispatchToProps(dispatch){
return {
setAccountMode: mode => dispatch(financialActions.actions.setAccountMode(mode)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AccountContainer) |
src/routes/index.js | raineroviir/SUWProject | import React from 'react'
import { Route, IndexRoute, Redirect } from 'react-router'
// NOTE: here we're making use of the `resolve.root` configuration
// option in webpack, which allows us to specify import paths as if
// they were from the root of the ~/src directory. This makes it
// very easy to navigate to files regardless of how deeply nested
// your current file is.
import CoreLayout from 'layouts/CoreLayout/CoreLayout'
import HomeView from 'views/HomeView/HomeView'
import NotFoundView from 'views/NotFoundView/NotFoundView'
import ImageSwipeView from 'views/ImageSwipeView/ImageSwipeView'
import ProgressView from 'views/ProgressView/ProgressView'
export default (
<Route path='/' component={CoreLayout}>
<IndexRoute component={HomeView} />
<Route path='/404' component={NotFoundView} />
<Route path='/myhome' component={ImageSwipeView} />
<Route path='/progress' component={ProgressView} />
<Redirect from='*' to='/404' />
</Route>
)
|
src/svg-icons/places/fitness-center.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesFitnessCenter = (props) => (
<SvgIcon {...props}>
<path d="M20.57 14.86L22 13.43 20.57 12 17 15.57 8.43 7 12 3.43 10.57 2 9.14 3.43 7.71 2 5.57 4.14 4.14 2.71 2.71 4.14l1.43 1.43L2 7.71l1.43 1.43L2 10.57 3.43 12 7 8.43 15.57 17 12 20.57 13.43 22l1.43-1.43L16.29 22l2.14-2.14 1.43 1.43 1.43-1.43-1.43-1.43L22 16.29z"/>
</SvgIcon>
);
PlacesFitnessCenter = pure(PlacesFitnessCenter);
PlacesFitnessCenter.displayName = 'PlacesFitnessCenter';
export default PlacesFitnessCenter;
|
src/js/components/pages/ErrorPage.js | at-ishikawa/paintlive | import React from 'react';
class ErrorPage extends React.Component {
render() {
return (
<div>
<div style={{
"background-color": "white",
"font-size": "2rem",
"padding": "32px",
"text-align": "center"
}}>
Sorry, the requested page was not found.<br />
<br />
<a href="/" style={{
"color": "blue",
"text-decoration": "underline"
}}>
Back to TOP
</a>
</div>
</div>
);
}
}
export default ErrorPage;
|
src/frontend/components/forms/GCPhoneField.js | al3x/ground-control | import React from 'react';
import {TextField} from 'material-ui';
import {BernieText} from '../styles/bernie-css';
import GCFormField from './GCFormField';
export default class GCPhoneField extends GCFormField {
render() {
let phone = this.props.value
let formattedValue = `(${phone.slice(0, 3)}) ${phone.slice(3,6)}-${phone.slice(6)}`
return <TextField
{...this.props}
value={formattedValue}
floatingLabelText={this.floatingLabelText()}
errorStyle={BernieText.inputError}
hintText={this.props.label}
onChange={(event) => {
let val = event.target.value.replace(/\D/g,'')
this.props.onChange(val)
}}
/>
}
} |
app/js/views/Section.js | refugeetech/project_interactivemap | import React from 'react'
import { compose, mapProps } from 'recompose'
import { Link } from 'react-router'
import NavBar from './NavBar'
const enhance = compose(
mapProps(({ sections, params, ...props }) => ({
section: sections[params.sectionId],
...props
})),
mapProps(({ section, readPosts, ...props }) => {
const readPostsInCategory = section.categories
.map(id => props.categories[id])
.reduce((acc, c) => acc.concat(c.posts), [])
.filter(id => readPosts.includes(id))
const categoryPosts = section.categories
.map(id => props.categories[id])
.reduce((acc, c) => acc.concat(c.posts), [])
return {
section,
readCount: readPostsInCategory.length,
postCount: categoryPosts.length,
readPosts,
...props
}
}),
)
const Section = ({
section,
categories,
posts,
readCount,
postCount,
readPosts
}) =>
<div style={{paddingTop: '53px'}}>
<NavBar title={section.title}>
<div style={{fontSize: '0.8rem', color: 'white'}}>
{readCount} of {postCount} done
</div>
</NavBar>
<div>
<div style={{
backgroundImage: 'url('+section.image.url+')',
backgroundSize: 'cover'
}}>
<div
style={{
padding: '6rem 0 .05rem 0',
background: 'linear-gradient(rgba(0,0,0,0),rgba(0,0,0,0.3))'
}}>
<h2 style={{
fontWeight: '600',
fontSize: '1.8rem',
margin: '1rem',
color: '#ffffff',
textShadow: '1px 1px 2px #444'
}}
>
{section.title}
</h2>
</div>
</div>
{section.categories.map(id =>
<Category
key={id}
{...categories[id]}
postsById={posts}
readPosts={readPosts} />
)}
</div>
</div>
const Category = ({ title, posts, postsById, readPosts }) =>
<div style={{margin: '0 0 1.4rem'}}>
<h3 style={{
fontSize: '0.9rem',
color: '#999',
padding: '0.6rem 1rem',
margin: 0,
borderBottom: '1px solid #e5e5e5'}}
>
{title}
</h3>
<ul>
{posts.map((id, i) =>
<li key={id}>
<PostLink
id={id}
nextId={posts[i + 1]}
isRead={readPosts.includes(id)}
{...postsById[id]} />
</li>
)}
</ul>
</div>
const buildUrl = (id, next) =>
next ?
`/posts/${id}?n=${next}` :
`/posts/${id}`
const PostLink = ({ id, title, text, nextId, isRead }) =>
<Link
to={buildUrl(id, nextId)}
style={{
display: 'block',
padding: '0.6rem 1rem',
textDecoration: isRead ? 'line-through' : 'none',
color: isRead ? '#999' : '#333',
background: 'white',
borderBottom: '1px solid #e5e5e5'}}
>
{title}
</Link>
export default enhance(Section)
|
node_modules/perseus/node_modules/react-tools/src/core/ReactElementValidator.js | laurennicolaisen/laurennicolaisen.github.io | /**
* Copyright 2014, 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.
*
* @providesModule ReactElementValidator
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
"use strict";
var ReactElement = require('ReactElement');
var ReactPropTypeLocations = require('ReactPropTypeLocations');
var ReactCurrentOwner = require('ReactCurrentOwner');
var monitorCodeUse = require('monitorCodeUse');
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {
'react_key_warning': {},
'react_numeric_key_warning': {}
};
var ownerHasMonitoredObjectMap = {};
var loggedTypeFailures = {};
var NUMERIC_PROPERTY_REGEX = /^\d+$/;
/**
* Gets the current owner's displayName for use in warnings.
*
* @internal
* @return {?string} Display name or undefined
*/
function getCurrentOwnerDisplayName() {
var current = ReactCurrentOwner.current;
return current && current.constructor.displayName || undefined;
}
/**
* Warn if the component doesn't have an explicit key assigned to it.
* This component is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it.
*
* @internal
* @param {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function validateExplicitKey(component, parentType) {
if (component._store.validated || component.key != null) {
return;
}
component._store.validated = true;
warnAndMonitorForKeyUse(
'react_key_warning',
'Each child in an array should have a unique "key" prop.',
component,
parentType
);
}
/**
* Warn if the key is being defined as an object property but has an incorrect
* value.
*
* @internal
* @param {string} name Property name of the key.
* @param {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function validatePropertyKey(name, component, parentType) {
if (!NUMERIC_PROPERTY_REGEX.test(name)) {
return;
}
warnAndMonitorForKeyUse(
'react_numeric_key_warning',
'Child objects should have non-numeric keys so ordering is preserved.',
component,
parentType
);
}
/**
* Shared warning and monitoring code for the key warnings.
*
* @internal
* @param {string} warningID The id used when logging.
* @param {string} message The base warning that gets output.
* @param {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function warnAndMonitorForKeyUse(warningID, message, component, parentType) {
var ownerName = getCurrentOwnerDisplayName();
var parentName = parentType.displayName;
var useName = ownerName || parentName;
var memoizer = ownerHasKeyUseWarning[warningID];
if (memoizer.hasOwnProperty(useName)) {
return;
}
memoizer[useName] = true;
message += ownerName ?
` Check the render method of ${ownerName}.` :
` Check the renderComponent call using <${parentName}>.`;
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwnerName = null;
if (component._owner && component._owner !== ReactCurrentOwner.current) {
// Name of the component that originally created this child.
childOwnerName = component._owner.constructor.displayName;
message += ` It was passed a child from ${childOwnerName}.`;
}
message += ' See http://fb.me/react-warning-keys for more information.';
monitorCodeUse(warningID, {
component: useName,
componentOwner: childOwnerName
});
console.warn(message);
}
/**
* Log that we're using an object map. We're considering deprecating this
* feature and replace it with proper Map and ImmutableMap data structures.
*
* @internal
*/
function monitorUseOfObjectMap() {
var currentName = getCurrentOwnerDisplayName() || '';
if (ownerHasMonitoredObjectMap.hasOwnProperty(currentName)) {
return;
}
ownerHasMonitoredObjectMap[currentName] = true;
monitorCodeUse('react_object_map_children');
}
/**
* Ensure that every component either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {*} component Statically passed child of any type.
* @param {*} parentType component's parent's type.
* @return {boolean}
*/
function validateChildKeys(component, parentType) {
if (Array.isArray(component)) {
for (var i = 0; i < component.length; i++) {
var child = component[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(component)) {
// This component was passed in a valid location.
component._store.validated = true;
} else if (component && typeof component === 'object') {
monitorUseOfObjectMap();
for (var name in component) {
validatePropertyKey(name, component[name], parentType);
}
}
}
/**
* Assert that the props are valid
*
* @param {string} componentName Name of the component for error messages.
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
function checkPropTypes(componentName, propTypes, props, location) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
// This will soon use the warning module
monitorCodeUse(
'react_failed_descriptor_type_check',
{ message: error.message }
);
}
}
}
}
var ReactElementValidator = {
createElement: function(type, props, children) {
var element = ReactElement.createElement.apply(this, arguments);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
var name = type.displayName;
if (type.propTypes) {
checkPropTypes(
name,
type.propTypes,
element.props,
ReactPropTypeLocations.prop
);
}
if (type.contextTypes) {
checkPropTypes(
name,
type.contextTypes,
element._context,
ReactPropTypeLocations.context
);
}
return element;
},
createFactory: function(type) {
var validatedFactory = ReactElementValidator.createElement.bind(
null,
type
);
validatedFactory.type = type;
return validatedFactory;
}
};
module.exports = ReactElementValidator;
|
react/src/sui/NavBarComponent.js | ineffablep/simple-ui | import React from 'react';
import { Link, IndexLink } from 'react-router';
import uuidV4 from 'uuid/v4';
class NavBar extends React.Component {
constructor(props) {
super(props);
this.routeList = [];
this.handleMobileMenuClick = this.handleMobileMenuClick.bind(this);
this.state = { showMobileMenu: false };
}
_getDisplayName(route) {
let name = null;
if (typeof route.getDisplayName === 'function') {
name = route.getDisplayName();
}
if (route.indexRoute) {
name = name || route.indexRoute.displayName || null;
} else {
name = name || route.displayName || null;
}
//check to see if a custom name has been applied to the route
if (!name && !!route.name) {
name = route.name;
}
//if the name exists and it's in the excludes list exclude this route
//if (name && this.props.excludes.some(item => item === name)) return null;
if (!name) {
name = "";
}
return name;
}
_checkAddRoutes(route, isRoot) {
let name = this._getDisplayName(route);
let exist = this.routeList.find(y => y.path === route.path);
if (exist == null && name && route.path) {
if (!isRoot) {
route.path = '/' + route.path;
}
this.routeList.push({ "path": route.path, "name": name });
}
}
_buildRoutes(routes) {
routes.forEach((_route) => {
let isRoot = routes[1] && !routes[1].hasOwnProperty("path");
let route = Object.assign({}, _route);
if (typeof _route.prettifyParam === 'function') {
route.prettifyParam = _route.prettifyParam;
}
this._checkAddRoutes(route, isRoot);
if (isRoot && route.childRoutes && route.childRoutes.length) {
let cls = this;
route.childRoutes.forEach(chilRoute => {
cls._checkAddRoutes(chilRoute);
});
}
});
}
renderListItem(item) {
const liAlign = this.props.alignLinks == 'left' ? 'sui-left' : 'sui-right';
return <li key={uuidV4()} className={liAlign} > <Link to={item.path} className={this.props.classHyperLink} style={this.props.styleHyperLink} activeClassName="sui-active">{item.name}</Link> </li>;
}
renderList() {
if (this.routeList && this.routeList.length) {
return this.routeList.map(item => this.renderListItem(item));
}
return [];
}
handleMobileMenuClick() {
this.setState(prevState => ({
showMobileMenu: !prevState.showMobileMenu
}));
}
renderSideMenu() {
return (
<ul className={'sui-sidenav ' + this.props.classNavBar} style={this.props.styleNavBar} >
{this.routeList.map(item => {
return <li key={uuidV4()}> <Link to={item.path} className={this.props.classHyperLink} style={this.props.styleHyperLink} activeClassName="sui-active">{item.name}</Link> </li>;
})}
</ul>
);
}
render() {
this._buildRoutes(this.props.routes);
let indexContent;
if (this.props.showBothBrandAndLogo && this.props.brandLogoPath) {
indexContent = <span> <img className={this.props.classBrandLogo} style={this.props.styleBrandLogo} src={this.props.brandLogoPath} alt={this.props.brand ? this.props.brand : ''} /> <span className={this.props.classBrand} style={this.props.styleBrand}> {this.props.brand} </span> </span>;
} else if (this.props.brandLogoPath) {
indexContent = <img className={this.props.classBrandLogo} style={this.props.styleBrandLogo} src={this.props.brandLogoPath} alt={this.props.brand ? this.props.brand : ''} />;
} else if (this.props.brand) {
indexContent = <span className={this.props.classBrand} style={this.props.styleBrand}> {this.props.brand} </span>;
} else {
indexContent = <span className="sui-text-white"> Home </span>;
}
let mobileClass = this.props.showSideNav ? 'sui-navbar' : 'sui-navbar sui-hide-desktop-xl sui-hide-desktop ';
mobileClass = mobileClass + this.props.classNavBar;
let deskClass = this.props.showSideNav ? 'sui-hide' : ('sui-navbar sui-hide-mobile sui-hide-tablet ' + this.props.classNavBar);
return (
<div>
<ul className={deskClass} style={this.props.styleNavBar} >
<li key={uuidV4()} className="sui-left"> <IndexLink to="/" className={this.props.classHyperLink} style={this.props.styleHyperLink} activeClassName="sui-active"> {indexContent} </IndexLink> </li>
{this.renderList()}
{this.props.children}
</ul>
<ul className={mobileClass} style={this.props.styleNavBar} >
<li key={uuidV4()}>
<span className={' sui-pointer ' + this.props.classMobileBars} onClick={this.handleMobileMenuClick} > ☰ </span>
{indexContent}
</li>
</ul>
{this.state.showMobileMenu ? this.renderSideMenu() : ''}
</div>
);
}
}
NavBar.propTypes = {
routes: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
brandLogoPath: React.PropTypes.string,
brand: React.PropTypes.string,
showBothBrandAndLogo: React.PropTypes.bool,
alignLinks: React.PropTypes.string,
showSideNav: React.PropTypes.bool,
classBrandLogo: React.PropTypes.string,
styleBrandLogo: React.PropTypes.object,
classBrand: React.PropTypes.string,
styleBrand: React.PropTypes.object,
classMobileBars: React.PropTypes.string,
styleMobileBars: React.PropTypes.object,
classNavBar: React.PropTypes.string,
styleNavBar: React.PropTypes.object,
classHyperLink: React.PropTypes.string,
styleHyperLink: React.PropTypes.object,
children: React.PropTypes.node
};
NavBar.defaultProps = {
brandLogoPath: '',
brand: '',
showBothBrandAndLogo: false,
showSideNav: false,
// Allign left or right
alignLinks: 'right',
classNavBar: '',
styleNavBar: {},
classHyperLink: '',
styleHyperLink: {},
classBrandLogo: 'sui-image',
styleBrandLogo: {},
classBrand: 'sui-brand',
styleBrand: {},
classMobileBars: 'sui-text-white sui-right',
styleMobileBars: {}
};
export default NavBar;
|
packages/material-ui-icons/src/Drafts.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Drafts = props =>
<SvgIcon {...props}>
<path d="M21.99 8c0-.72-.37-1.35-.94-1.7L12 1 2.95 6.3C2.38 6.65 2 7.28 2 8v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2l-.01-10zM12 13L3.74 7.84 12 3l8.26 4.84L12 13z" />
</SvgIcon>;
Drafts = pure(Drafts);
Drafts.muiName = 'SvgIcon';
export default Drafts;
|
src/components/Spinner/index.js | ultimagriever/manager | import React from 'react';
import { View, ActivityIndicator } from 'react-native';
import styles from './styles';
const Spinner = props => (
<View style={styles.container}>
<ActivityIndicator {...props} />
</View>
);
Spinner.defaultProps = {
color: 'white',
size: 'large'
};
export default Spinner;
|
.storybook/includes/file-import.js | KissKissBankBank/kitten | import React from 'react'
import { Subheading } from '@storybook/addon-docs'
export const FileImport = ({ importString }) => (
<>
<Subheading>Import</Subheading>
<pre className="k-u-margin-top-singleHalf k-u-margin-bottom-quadruple">
import {`{ ${importString} }`} from '@kisskissbankbank/kitten'
</pre>
</>
)
|
src/icons/ModeCommentIcon.js | kiloe/ui | import React from 'react';
import Icon from '../Icon';
export default class ModeCommentIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M43.98 8c0-2.21-1.77-4-3.98-4H8C5.79 4 4 5.79 4 8v24c0 2.21 1.79 4 4 4h28l8 8-.02-36z"/></svg>;}
}; |
src/meta/CategoryList.js | guanzhou-zhao/calculate-cabinet-plan | import React, { Component } from 'react';
import _ from 'lodash';
import Category from '../model/Category';
import defaultState from './config';
import CalculatePlanList from './CalculatePlanList'
export default class CategoryList extends Component {
constructor(props) {
super(props);
this.getCategoryList = this.getCategoryList.bind(this);
}
getCategoryList() {
var categoryList = [];
return this.props.categories.reduce((accumulator, cat, currentIndex, array)=> {
if (cat._id.equals(this.props.categoryInEditing.id)) {
accumulator.push(
<div className='categoryAddingForm' key={currentIndex}>
<input type="text" name="category-name" placeholder="Category Name" defaultValue={cat.name}
onChange={(e)=>{
this.props.handleValueChange( {categoryInEditing: {obj: { name: {$set: e.target.value}}}})
}}
/>
<input type="text" name="category-desc" placeholder="Category Description" defaultValue={cat.desc}
onChange={(e)=>{
this.props.handleValueChange( {categoryInEditing: {obj: { desc: {$set: e.target.value}}}})
}}
/>
<input type="button" value="Save"
onClick={
() => {
cat.update(this.props.categoryInEditing.obj, ()=> {
this.props.handleValueChange( {categoryInEditing: {id: { $set: ''}}})
this.props.updateCategories();
})
}
}
/>
<input type="button" value="Calcel"
onClick={
() => {this.props.handleValueChange( {categoryInEditing: {id: { $set: ''}}}) }
}
/>
<CalculatePlanList config={this.props.config} />
</div>
);
} else {
accumulator.push(<div className="category" key={currentIndex}>
<h3 className="category-detail">
<span className="category-name">{cat.name} </span>
<span className="category-desc">{cat.desc}</span>
</h3>
<div className="category-action">
<input type="button" onClick={
()=>{
this.props.handleValueChange({'categoryInEditing': {'id': {$set: cat._id}}})
}
} value="Edit"/>
</div>
<CalculatePlanList cat={cat} config={this.props.config} />
</div>);
}
return accumulator;
}, categoryList);
}
render () {
return (
<div>
{this.getCategoryList()}
</div>
)
}
}
|
src/routes.js | Alastor4918/Heckmeck | import React from 'react';
import {IndexRoute, Route} from 'react-router';
import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth';
import {
App,
Login,
LoginSuccess,
NotFound,
LandingPage,
Rules,
Game,
Register,
Lobby,
LobbyRoom
} from 'containers';
export default (store) => {
const requireLogin = (nextState, replace, cb) => {
function checkAuth() {
const { auth: { user }} = store.getState();
if (!user) {
// oops, not logged in, so can't be here!
replace('/');
}
cb();
}
if (!isAuthLoaded(store.getState())) {
store.dispatch(loadAuth()).then(checkAuth);
} else {
checkAuth();
}
};
/**
* Please keep routes in alphabetical order
*/
return (
<Route path="/" component={App}>
{ /* Home (main) route */ }
<IndexRoute component={LandingPage}/>
{ /* Routes requiring login */ }
<Route onEnter={requireLogin}>
<Route path="loginSuccess" component={LoginSuccess}/>
<Route path="lobby" component={Lobby} />
<Route path="lobbyRoom" component={LobbyRoom} />
<Route path="game" component={Game}/>
</Route>
{ /* Routes */ }
<Route path="login" component={Login}/>
<Route path="rules" component={Rules}/>
<Route path="register" component={Register}/>
{ /* Catch all route */ }
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
app/javascript/mastodon/features/ui/components/column_subheading.js | verniy6462/mastodon | import React from 'react';
import PropTypes from 'prop-types';
const ColumnSubheading = ({ text }) => {
return (
<div className='column-subheading'>
{text}
</div>
);
};
ColumnSubheading.propTypes = {
text: PropTypes.string.isRequired,
};
export default ColumnSubheading;
|
src/components/Speakers/Speakers.js | ksevezich/DayOfBlueprint | import React from 'react'
import classes from './Speakers.scss'
import SpeakersSection from 'components/SpeakersSection'
import alex from 'static/Alex.png'
import stephen from 'static/Stephen.png'
import jason from 'static/Jason.png'
import dan from 'static/Dan.png'
export const Speakers = () => (
<div>
<div className={classes.speakers} >
<div className={'container text-center'}>
<h1 className={classes.header}> Speakers </h1>
<SpeakersSection title={'Alex Dehgan, Conservation X Labs'}
beforeText={'Alex Dehgan, CEO and founder of Conservation X Labs, will talk about Invasive Species. Contact him '}
link={'mailto:[email protected]'}
linkText={'here'}
imagePath={alex}
titleSecond={'Stephen Lee, U.S. Army Research Office'}
beforeTextSecond={'Dr. Stephen T. Lee, Chief Scientist at the U.S. Army Research Office will discuss Wildlife Trafficking. Contact him '}
linkSecond={'mailto:[email protected]'}
linkTextSecond={'here'}
imagePathSecond={stephen} />
<SpeakersSection title={'Jason Heckathorn, Forever Oceans'}
beforeText={'Jason Heckathorn, CEO of Forever Oceans, is our Keynote speaker. Contact him '}
link={'mailto:[email protected]'}
linkText={'here'}
imagePath={jason}
titleSecond={'Dan Fay, Microsoft Research'}
beforeTextSecond={'Daniel Fay, the Director of External Research for Earth, Energy, and Environment at Microsoft Research, will discuss Citizen Science. Contact him '}
linkSecond={'mailto:[email protected]'}
linkTextSecond={'here'}
imagePathSecond={dan} />
</div>
</div>
</div>
)
export default Speakers
|
assets/javascripts/kitten/components/layout/dashboard-layout/flow/index.js | KissKissBankBank/kitten | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import classNames from 'classnames'
import COLORS from '../../../../constants/colors-config'
import { mq } from '../../../../constants/screen-config'
import { pxToRem } from '../../../../helpers/utils/typography'
import { LightbulbIllustration as Lightbulb } from '../../../graphics/illustrations/lightbulb-illustration'
import { Loader } from '../../../graphics/animations/loader'
import { getReactElementsWithoutType } from '../../../../helpers/react/get-react-elements'
import { Title as KittenTitle } from '../../../typography/title'
import { SideCard } from './side-card'
import { MobileAside } from './side-modal'
const StyledFlow = styled.div`
position: relative;
display: flex;
flex-direction: column;
align-items: stretch;
min-height: 100%;
gap: ${pxToRem(20)};
@media ${mq.mobileAndTablet} {
margin-top: ${pxToRem(50)};
}
@media ${mq.desktop} {
min-height: calc(100vh - var(--dashboardLayout-siteHeaderHeight));
display: grid;
grid-template-rows: auto 1fr auto;
grid-template-columns: 35vw 20vw;
gap: ${pxToRem(30)} 5vw;
margin-top: ${pxToRem(80)};
}
&:not(.k-DashboardLayout__flow--isLoading) {
.k-DashboardLayout__flow__loading {
display: none;
}
}
&.k-DashboardLayout__flow--isLoading {
.k-DashboardLayout__flow__content {
display: none;
}
}
.k-DashboardLayout__flow__loading,
.k-DashboardLayout__flow__content {
background-color: ${COLORS.background1};
@media ${mq.tabletAndDesktop} {
padding-top: 0;
}
@media ${mq.desktop} {
grid-column: 1 / 2;
grid-row: 2 / span 1;
padding-bottom: ${pxToRem(20)};
}
}
@media ${mq.desktop} {
.k-DashboardLayout__flow__title {
grid-column: 1 / span 1;
grid-row: 1 / span 1;
align-self: center;
}
.k-DashboardLayout__flow__titleAside {
grid-column: 2 / span 1;
grid-row: 1 / span 1;
align-self: center;
justify-self: end;
}
}
.k-DashboardLayout__flow__nav {
flex: 0 0 auto;
background-color: ${COLORS.background1};
width: 100%;
@media ${mq.desktop} {
grid-column: 1 / 2;
grid-row: 3 / span 1;
bottom: 0;
position: sticky;
z-index: 1;
&::before {
position: absolute;
background: linear-gradient(
to bottom,
rgba(255, 255, 255, 0),
rgba(255, 255, 255, 1)
);
content: '';
top: ${pxToRem(-20)};
left: 0;
right: 0;
height: ${pxToRem(20)};
}
}
}
.k-DashboardLayout__flow__nav__actionsContainer {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: ${pxToRem(20)};
margin: ${pxToRem(20)} 0;
@media ${mq.desktop} {
gap: ${pxToRem(40)};
margin: ${pxToRem(20)} 0 ${pxToRem(30)};
}
& > .k-Button {
min-width: 0 !important;
max-width: ${pxToRem(180)};
width: 100%;
&:last-child {
justify-self: end;
}
&:first-child:last-child {
grid-column: 1 / span 2;
}
}
}
.k-DashboardLayout__flow__nav:not(.k-DashboardLayout__flow__nav--twoButtons) {
.k-DashboardLayout__flow__nav__actionsContainer > .k-Button {
@media ${mq.mobile} {
grid-column: 1 / span 2;
justify-self: stretch;
max-width: 100%;
}
}
}
.k-DashboardLayout__flow__aside {
@media ${mq.desktop} {
grid-column: 2 / 3;
grid-row: 2 / span 1;
}
}
.k-DashboardLayout__flow__aside__content {
position: sticky;
top: calc(${pxToRem(80)} + var(--dashboardLayout-siteHeaderHeight, 0));
padding-bottom: ${pxToRem(40)};
svg {
margin-bottom: ${pxToRem(20)};
}
@media ${mq.mobileAndTablet} {
display: none;
}
}
.k-DashboardLayout__flow__loading {
flex: 1 0 100%;
display: flex;
align-items: center;
justify-content: center;
}
`
const Content = ({ className, ...props }) => {
return (
<section
{...props}
className={classNames('k-DashboardLayout__flow__content', className)}
/>
)
}
const Title = ({ className, ...props }) => {
return (
<KittenTitle
noMargin
{...props}
className={classNames('k-DashboardLayout__flow__title', className)}
/>
)
}
const TitleAside = ({ className, ...props }) => {
return (
<div
{...props}
className={classNames('k-DashboardLayout__flow__titleAside', className)}
/>
)
}
const Nav = ({ className, children, twoButtons = false, ...props }) => {
return (
<nav
{...props}
className={classNames('k-DashboardLayout__flow__nav', className, {
'k-DashboardLayout__flow__nav--twoButtons': twoButtons,
})}
>
<div className="k-DashboardLayout__flow__nav__actionsContainer">
{children}
</div>
</nav>
)
}
const Aside = ({
className,
children,
withoutLight = false,
mobileAsideProps,
...props
}) => {
return (
<aside
{...props}
className={classNames('k-DashboardLayout__flow__aside', className)}
>
<MobileAside {...mobileAsideProps}>{children}</MobileAside>
<div className="k-DashboardLayout__flow__aside__content">
{!withoutLight && <Lightbulb />}
{children}
</div>
</aside>
)
}
export const Flow = ({
children,
className,
loading,
loaderComponent,
...props
}) => {
return (
<StyledFlow
className={classNames(
'k-DashboardLayout__flow',
className,
'k-DashboardLayout__fullHeight',
{
'k-DashboardLayout__flow--isLoading': loading,
},
)}
{...props}
>
<div className="k-DashboardLayout__flow__loading">
{!!loaderComponent ? loaderComponent : <Loader />}
</div>
{getReactElementsWithoutType({ children, type: 'Aside' })}
</StyledFlow>
)
}
Aside.propTypes = {
withoutLight: PropTypes.bool,
mobileAsideProps: PropTypes.shape({
openLabel: PropTypes.node.isRequired,
closeLabel: PropTypes.node.isRequired,
}),
}
Flow.propTypes = {
loading: PropTypes.bool,
loaderComponent: PropTypes.node,
}
Flow.Title = Title
Flow.TitleAside = TitleAside
Flow.Content = Content
Flow.Nav = Nav
Flow.Aside = Aside
Flow.AsideCard = SideCard
|
ajax/libs/jssip/0.6.29/jssip.js | LeaYeh/cdnjs | /*
* JsSIP v0.6.29
* the Javascript SIP library
* Copyright: 2012-2015 José Luis Millán <[email protected]> (https://github.com/jmillan)
* Homepage: http://jssip.net
* License: MIT
*/
(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.JsSIP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var pkg = require('../package.json');
var C = {
USER_AGENT: pkg.title + ' ' + pkg.version,
// SIP scheme
SIP: 'sip',
SIPS: 'sips',
// End and Failure causes
causes: {
// Generic error causes
CONNECTION_ERROR: 'Connection Error',
REQUEST_TIMEOUT: 'Request Timeout',
SIP_FAILURE_CODE: 'SIP Failure Code',
INTERNAL_ERROR: 'Internal Error',
// SIP error causes
BUSY: 'Busy',
REJECTED: 'Rejected',
REDIRECTED: 'Redirected',
UNAVAILABLE: 'Unavailable',
NOT_FOUND: 'Not Found',
ADDRESS_INCOMPLETE: 'Address Incomplete',
INCOMPATIBLE_SDP: 'Incompatible SDP',
MISSING_SDP: 'Missing SDP',
AUTHENTICATION_ERROR: 'Authentication Error',
// Session error causes
BYE: 'Terminated',
WEBRTC_ERROR: 'WebRTC Error',
CANCELED: 'Canceled',
NO_ANSWER: 'No Answer',
EXPIRES: 'Expires',
NO_ACK: 'No ACK',
DIALOG_ERROR: 'Dialog Error',
USER_DENIED_MEDIA_ACCESS: 'User Denied Media Access',
BAD_MEDIA_DESCRIPTION: 'Bad Media Description',
RTP_TIMEOUT: 'RTP Timeout'
},
SIP_ERROR_CAUSES: {
REDIRECTED: [300,301,302,305,380],
BUSY: [486,600],
REJECTED: [403,603],
NOT_FOUND: [404,604],
UNAVAILABLE: [480,410,408,430],
ADDRESS_INCOMPLETE: [484],
INCOMPATIBLE_SDP: [488,606],
AUTHENTICATION_ERROR:[401,407]
},
// SIP Methods
ACK: 'ACK',
BYE: 'BYE',
CANCEL: 'CANCEL',
INFO: 'INFO',
INVITE: 'INVITE',
MESSAGE: 'MESSAGE',
NOTIFY: 'NOTIFY',
OPTIONS: 'OPTIONS',
REGISTER: 'REGISTER',
UPDATE: 'UPDATE',
SUBSCRIBE: 'SUBSCRIBE',
/* SIP Response Reasons
* DOC: http://www.iana.org/assignments/sip-parameters
* Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7
*/
REASON_PHRASE: {
100: 'Trying',
180: 'Ringing',
181: 'Call Is Being Forwarded',
182: 'Queued',
183: 'Session Progress',
199: 'Early Dialog Terminated', // draft-ietf-sipcore-199
200: 'OK',
202: 'Accepted', // RFC 3265
204: 'No Notification', //RFC 5839
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Moved Temporarily',
305: 'Use Proxy',
380: 'Alternative Service',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
410: 'Gone',
412: 'Conditional Request Failed', // RFC 3903
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Unsupported URI Scheme',
417: 'Unknown Resource-Priority', // RFC 4412
420: 'Bad Extension',
421: 'Extension Required',
422: 'Session Interval Too Small', // RFC 4028
423: 'Interval Too Brief',
428: 'Use Identity Header', // RFC 4474
429: 'Provide Referrer Identity', // RFC 3892
430: 'Flow Failed', // RFC 5626
433: 'Anonymity Disallowed', // RFC 5079
436: 'Bad Identity-Info', // RFC 4474
437: 'Unsupported Certificate', // RFC 4744
438: 'Invalid Identity Header', // RFC 4744
439: 'First Hop Lacks Outbound Support', // RFC 5626
440: 'Max-Breadth Exceeded', // RFC 5393
469: 'Bad Info Package', // draft-ietf-sipcore-info-events
470: 'Consent Needed', // RFC 5360
478: 'Unresolvable Destination', // Custom code copied from Kamailio.
480: 'Temporarily Unavailable',
481: 'Call/Transaction Does Not Exist',
482: 'Loop Detected',
483: 'Too Many Hops',
484: 'Address Incomplete',
485: 'Ambiguous',
486: 'Busy Here',
487: 'Request Terminated',
488: 'Not Acceptable Here',
489: 'Bad Event', // RFC 3265
491: 'Request Pending',
493: 'Undecipherable',
494: 'Security Agreement Required', // RFC 3329
500: 'JsSIP Internal Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Server Time-out',
505: 'Version Not Supported',
513: 'Message Too Large',
580: 'Precondition Failure', // RFC 3312
600: 'Busy Everywhere',
603: 'Decline',
604: 'Does Not Exist Anywhere',
606: 'Not Acceptable'
},
ALLOWED_METHODS: 'INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS',
ACCEPTED_BODY_TYPES: 'application/sdp, application/dtmf-relay',
MAX_FORWARDS: 69,
SESSION_EXPIRES: 90,
MIN_SESSION_EXPIRES: 60
};
module.exports = C;
},{"../package.json":46}],2:[function(require,module,exports){
module.exports = Dialog;
var C = {
// Dialog states
STATUS_EARLY: 1,
STATUS_CONFIRMED: 2
};
/**
* Expose C object.
*/
Dialog.C = C;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:Dialog');
var SIPMessage = require('./SIPMessage');
var JsSIP_C = require('./Constants');
var Transactions = require('./Transactions');
var Dialog_RequestSender = require('./Dialog/RequestSender');
// RFC 3261 12.1
function Dialog(owner, message, type, state) {
var contact;
this.uac_pending_reply = false;
this.uas_pending_reply = false;
if(!message.hasHeader('contact')) {
return {
error: 'unable to create a Dialog without Contact header field'
};
}
if(message instanceof SIPMessage.IncomingResponse) {
state = (message.status_code < 200) ? C.STATUS_EARLY : C.STATUS_CONFIRMED;
} else {
// Create confirmed dialog if state is not defined
state = state || C.STATUS_CONFIRMED;
}
contact = message.parseHeader('contact');
// RFC 3261 12.1.1
if(type === 'UAS') {
this.id = {
call_id: message.call_id,
local_tag: message.to_tag,
remote_tag: message.from_tag,
toString: function() {
return this.call_id + this.local_tag + this.remote_tag;
}
};
this.state = state;
this.remote_seqnum = message.cseq;
this.local_uri = message.parseHeader('to').uri;
this.remote_uri = message.parseHeader('from').uri;
this.remote_target = contact.uri;
this.route_set = message.getHeaders('record-route');
}
// RFC 3261 12.1.2
else if(type === 'UAC') {
this.id = {
call_id: message.call_id,
local_tag: message.from_tag,
remote_tag: message.to_tag,
toString: function() {
return this.call_id + this.local_tag + this.remote_tag;
}
};
this.state = state;
this.local_seqnum = message.cseq;
this.local_uri = message.parseHeader('from').uri;
this.remote_uri = message.parseHeader('to').uri;
this.remote_target = contact.uri;
this.route_set = message.getHeaders('record-route').reverse();
}
this.owner = owner;
owner.ua.dialogs[this.id.toString()] = this;
debug('new ' + type + ' dialog created with status ' + (this.state === C.STATUS_EARLY ? 'EARLY': 'CONFIRMED'));
}
Dialog.prototype = {
update: function(message, type) {
this.state = C.STATUS_CONFIRMED;
debug('dialog '+ this.id.toString() +' changed to CONFIRMED state');
if(type === 'UAC') {
// RFC 3261 13.2.2.4
this.route_set = message.getHeaders('record-route').reverse();
}
},
terminate: function() {
debug('dialog ' + this.id.toString() + ' deleted');
delete this.owner.ua.dialogs[this.id.toString()];
},
// RFC 3261 12.2.1.1
createRequest: function(method, extraHeaders, body) {
var cseq, request;
extraHeaders = extraHeaders && extraHeaders.slice() || [];
if(!this.local_seqnum) { this.local_seqnum = Math.floor(Math.random() * 10000); }
cseq = (method === JsSIP_C.CANCEL || method === JsSIP_C.ACK) ? this.local_seqnum : this.local_seqnum += 1;
request = new SIPMessage.OutgoingRequest(
method,
this.remote_target,
this.owner.ua, {
'cseq': cseq,
'call_id': this.id.call_id,
'from_uri': this.local_uri,
'from_tag': this.id.local_tag,
'to_uri': this.remote_uri,
'to_tag': this.id.remote_tag,
'route_set': this.route_set
}, extraHeaders, body);
request.dialog = this;
return request;
},
// RFC 3261 12.2.2
checkInDialogRequest: function(request) {
var self = this;
if(!this.remote_seqnum) {
this.remote_seqnum = request.cseq;
} else if(request.cseq < this.remote_seqnum) {
//Do not try to reply to an ACK request.
if (request.method !== JsSIP_C.ACK) {
request.reply(500);
}
return false;
} else if(request.cseq > this.remote_seqnum) {
this.remote_seqnum = request.cseq;
}
// RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR-
if (request.method === JsSIP_C.INVITE || (request.method === JsSIP_C.UPDATE && request.body)) {
if (this.uac_pending_reply === true) {
request.reply(491);
} else if (this.uas_pending_reply === true) {
var retryAfter = (Math.random() * 10 | 0) + 1;
request.reply(500, null, ['Retry-After:'+ retryAfter]);
return false;
} else {
this.uas_pending_reply = true;
request.server_transaction.on('stateChanged', function stateChanged(){
if (this.state === Transactions.C.STATUS_ACCEPTED ||
this.state === Transactions.C.STATUS_COMPLETED ||
this.state === Transactions.C.STATUS_TERMINATED) {
request.server_transaction.removeListener('stateChanged', stateChanged);
self.uas_pending_reply = false;
}
});
}
// RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted
if(request.hasHeader('contact')) {
request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_ACCEPTED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
}
else if (request.method === JsSIP_C.NOTIFY) {
// RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted
if(request.hasHeader('contact')) {
request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_COMPLETED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
}
return true;
},
sendRequest: function(applicant, method, options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body || null,
request = this.createRequest(method, extraHeaders, body),
request_sender = new Dialog_RequestSender(this, applicant, request);
request_sender.send();
},
receiveRequest: function(request) {
//Check in-dialog request
if(!this.checkInDialogRequest(request)) {
return;
}
this.owner.receiveRequest(request);
}
};
},{"./Constants":1,"./Dialog/RequestSender":3,"./SIPMessage":16,"./Transactions":18,"debug":29}],3:[function(require,module,exports){
module.exports = DialogRequestSender;
/**
* Dependencies.
*/
var JsSIP_C = require('../Constants');
var Transactions = require('../Transactions');
var RTCSession = require('../RTCSession');
var RequestSender = require('../RequestSender');
function DialogRequestSender(dialog, applicant, request) {
this.dialog = dialog;
this.applicant = applicant;
this.request = request;
// RFC3261 14.1 Modifying an Existing Session. UAC Behavior.
this.reattempt = false;
this.reattemptTimer = null;
}
DialogRequestSender.prototype = {
send: function() {
var
self = this,
request_sender = new RequestSender(this, this.dialog.owner.ua);
request_sender.send();
// RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR-
if ((this.request.method === JsSIP_C.INVITE || (this.request.method === JsSIP_C.UPDATE && this.request.body)) &&
request_sender.clientTransaction.state !== Transactions.C.STATUS_TERMINATED) {
this.dialog.uac_pending_reply = true;
request_sender.clientTransaction.on('stateChanged', function stateChanged(){
if (this.state === Transactions.C.STATUS_ACCEPTED ||
this.state === Transactions.C.STATUS_COMPLETED ||
this.state === Transactions.C.STATUS_TERMINATED) {
request_sender.clientTransaction.removeListener('stateChanged', stateChanged);
self.dialog.uac_pending_reply = false;
}
});
}
},
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
onTransportError: function() {
this.applicant.onTransportError();
},
receiveResponse: function(response) {
var self = this;
// RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog.
if (response.status_code === 408 || response.status_code === 481) {
this.applicant.onDialogError(response);
} else if (response.method === JsSIP_C.INVITE && response.status_code === 491) {
if (this.reattempt) {
this.applicant.receiveResponse(response);
} else {
this.request.cseq.value = this.dialog.local_seqnum += 1;
this.reattemptTimer = setTimeout(function() {
if (self.applicant.owner.status !== RTCSession.C.STATUS_TERMINATED) {
self.reattempt = true;
self.request_sender.send();
}
}, 1000);
}
} else {
this.applicant.receiveResponse(response);
}
}
};
},{"../Constants":1,"../RTCSession":11,"../RequestSender":15,"../Transactions":18}],4:[function(require,module,exports){
module.exports = DigestAuthentication;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:DigestAuthentication');
var Utils = require('./Utils');
function DigestAuthentication(ua) {
this.username = ua.configuration.authorization_user;
this.password = ua.configuration.password;
this.cnonce = null;
this.nc = 0;
this.ncHex = '00000000';
this.response = null;
}
/**
* Performs Digest authentication given a SIP request and the challenge
* received in a response to that request.
* Returns true if credentials were successfully generated, false otherwise.
*/
DigestAuthentication.prototype.authenticate = function(request, challenge) {
// Inspect and validate the challenge.
this.algorithm = challenge.algorithm;
this.realm = challenge.realm;
this.nonce = challenge.nonce;
this.opaque = challenge.opaque;
this.stale = challenge.stale;
if (this.algorithm) {
if (this.algorithm !== 'MD5') {
debug('challenge with Digest algorithm different than "MD5", authentication aborted');
return false;
}
} else {
this.algorithm = 'MD5';
}
if (! this.realm) {
debug('challenge without Digest realm, authentication aborted');
return false;
}
if (! this.nonce) {
debug('challenge without Digest nonce, authentication aborted');
return false;
}
// 'qop' can contain a list of values (Array). Let's choose just one.
if (challenge.qop) {
if (challenge.qop.indexOf('auth') > -1) {
this.qop = 'auth';
} else if (challenge.qop.indexOf('auth-int') > -1) {
this.qop = 'auth-int';
} else {
// Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here.
debug('challenge without Digest qop different than "auth" or "auth-int", authentication aborted');
return false;
}
} else {
this.qop = null;
}
// Fill other attributes.
this.method = request.method;
this.uri = request.ruri;
this.cnonce = Utils.createRandomToken(12);
this.nc += 1;
this.updateNcHex();
// nc-value = 8LHEX. Max value = 'FFFFFFFF'.
if (this.nc === 4294967296) {
this.nc = 1;
this.ncHex = '00000001';
}
// Calculate the Digest "response" value.
this.calculateResponse();
return true;
};
/**
* Generate Digest 'response' value.
*/
DigestAuthentication.prototype.calculateResponse = function() {
var ha1, ha2;
// HA1 = MD5(A1) = MD5(username:realm:password)
ha1 = Utils.calculateMD5(this.username + ':' + this.realm + ':' + this.password);
if (this.qop === 'auth') {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ':' + this.uri);
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth:' + ha2);
} else if (this.qop === 'auth-int') {
// HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody))
ha2 = Utils.calculateMD5(this.method + ':' + this.uri + ':' + Utils.calculateMD5(this.body ? this.body : ''));
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth-int:' + ha2);
} else if (this.qop === null) {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ':' + this.uri);
// response = MD5(HA1:nonce:HA2)
this.response = Utils.calculateMD5(ha1 + ':' + this.nonce + ':' + ha2);
}
};
/**
* Return the Proxy-Authorization or WWW-Authorization header value.
*/
DigestAuthentication.prototype.toString = function() {
var auth_params = [];
if (! this.response) {
throw new Error('response field does not exist, cannot generate Authorization header');
}
auth_params.push('algorithm=' + this.algorithm);
auth_params.push('username="' + this.username + '"');
auth_params.push('realm="' + this.realm + '"');
auth_params.push('nonce="' + this.nonce + '"');
auth_params.push('uri="' + this.uri + '"');
auth_params.push('response="' + this.response + '"');
if (this.opaque) {
auth_params.push('opaque="' + this.opaque + '"');
}
if (this.qop) {
auth_params.push('qop=' + this.qop);
auth_params.push('cnonce="' + this.cnonce + '"');
auth_params.push('nc=' + this.ncHex);
}
return 'Digest ' + auth_params.join(', ');
};
/**
* Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc.
*/
DigestAuthentication.prototype.updateNcHex = function() {
var hex = Number(this.nc).toString(16);
this.ncHex = '00000000'.substr(0, 8-hex.length) + hex;
};
},{"./Utils":22,"debug":29}],5:[function(require,module,exports){
/**
* @namespace Exceptions
* @memberOf JsSIP
*/
var Exceptions = {
/**
* Exception thrown when a valid parameter is given to the JsSIP.UA constructor.
* @class ConfigurationError
* @memberOf JsSIP.Exceptions
*/
ConfigurationError: (function(){
var exception = function(parameter, value) {
this.code = 1;
this.name = 'CONFIGURATION_ERROR';
this.parameter = parameter;
this.value = value;
this.message = (!this.value)? 'Missing parameter: '+ this.parameter : 'Invalid value '+ JSON.stringify(this.value) +' for parameter "'+ this.parameter +'"';
};
exception.prototype = new Error();
return exception;
}()),
InvalidStateError: (function(){
var exception = function(status) {
this.code = 2;
this.name = 'INVALID_STATE_ERROR';
this.status = status;
this.message = 'Invalid status: '+ status;
};
exception.prototype = new Error();
return exception;
}()),
NotSupportedError: (function(){
var exception = function(message) {
this.code = 3;
this.name = 'NOT_SUPPORTED_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}()),
NotReadyError: (function(){
var exception = function(message) {
this.code = 4;
this.name = 'NOT_READY_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}())
};
module.exports = Exceptions;
},{}],6:[function(require,module,exports){
module.exports = (function(){
/*
* Generated by PEG.js 0.7.0.
*
* http://pegjs.majda.cz/
*/
function quote(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a
* string literal except for the closing quote character, backslash,
* carriage return, line separator, paragraph separator, and line feed.
* Any character may appear in the form of an escape sequence.
*
* For portability, we also escape escape all control and non-ASCII
* characters. Note that "\0" and "\v" escape sequences are not used
* because JSHint does not like the first and IE the second.
*/
return '"' + s
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // closing quote character
.replace(/\x08/g, '\\b') // backspace
.replace(/\t/g, '\\t') // horizontal tab
.replace(/\n/g, '\\n') // line feed
.replace(/\f/g, '\\f') // form feed
.replace(/\r/g, '\\r') // carriage return
.replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
+ '"';
}
var result = {
/*
* Parses the input with a generated parser. If the parsing is successfull,
* returns a value explicitly or implicitly specified by the grammar from
* which the parser was generated (see |PEG.buildParser|). If the parsing is
* unsuccessful, throws |PEG.parser.SyntaxError| describing the error.
*/
parse: function(input, startRule) {
var parseFunctions = {
"CRLF": parse_CRLF,
"DIGIT": parse_DIGIT,
"ALPHA": parse_ALPHA,
"HEXDIG": parse_HEXDIG,
"WSP": parse_WSP,
"OCTET": parse_OCTET,
"DQUOTE": parse_DQUOTE,
"SP": parse_SP,
"HTAB": parse_HTAB,
"alphanum": parse_alphanum,
"reserved": parse_reserved,
"unreserved": parse_unreserved,
"mark": parse_mark,
"escaped": parse_escaped,
"LWS": parse_LWS,
"SWS": parse_SWS,
"HCOLON": parse_HCOLON,
"TEXT_UTF8_TRIM": parse_TEXT_UTF8_TRIM,
"TEXT_UTF8char": parse_TEXT_UTF8char,
"UTF8_NONASCII": parse_UTF8_NONASCII,
"UTF8_CONT": parse_UTF8_CONT,
"LHEX": parse_LHEX,
"token": parse_token,
"token_nodot": parse_token_nodot,
"separators": parse_separators,
"word": parse_word,
"STAR": parse_STAR,
"SLASH": parse_SLASH,
"EQUAL": parse_EQUAL,
"LPAREN": parse_LPAREN,
"RPAREN": parse_RPAREN,
"RAQUOT": parse_RAQUOT,
"LAQUOT": parse_LAQUOT,
"COMMA": parse_COMMA,
"SEMI": parse_SEMI,
"COLON": parse_COLON,
"LDQUOT": parse_LDQUOT,
"RDQUOT": parse_RDQUOT,
"comment": parse_comment,
"ctext": parse_ctext,
"quoted_string": parse_quoted_string,
"quoted_string_clean": parse_quoted_string_clean,
"qdtext": parse_qdtext,
"quoted_pair": parse_quoted_pair,
"SIP_URI_noparams": parse_SIP_URI_noparams,
"SIP_URI": parse_SIP_URI,
"uri_scheme": parse_uri_scheme,
"userinfo": parse_userinfo,
"user": parse_user,
"user_unreserved": parse_user_unreserved,
"password": parse_password,
"hostport": parse_hostport,
"host": parse_host,
"hostname": parse_hostname,
"domainlabel": parse_domainlabel,
"toplabel": parse_toplabel,
"IPv6reference": parse_IPv6reference,
"IPv6address": parse_IPv6address,
"h16": parse_h16,
"ls32": parse_ls32,
"IPv4address": parse_IPv4address,
"dec_octet": parse_dec_octet,
"port": parse_port,
"uri_parameters": parse_uri_parameters,
"uri_parameter": parse_uri_parameter,
"transport_param": parse_transport_param,
"user_param": parse_user_param,
"method_param": parse_method_param,
"ttl_param": parse_ttl_param,
"maddr_param": parse_maddr_param,
"lr_param": parse_lr_param,
"other_param": parse_other_param,
"pname": parse_pname,
"pvalue": parse_pvalue,
"paramchar": parse_paramchar,
"param_unreserved": parse_param_unreserved,
"headers": parse_headers,
"header": parse_header,
"hname": parse_hname,
"hvalue": parse_hvalue,
"hnv_unreserved": parse_hnv_unreserved,
"Request_Response": parse_Request_Response,
"Request_Line": parse_Request_Line,
"Request_URI": parse_Request_URI,
"absoluteURI": parse_absoluteURI,
"hier_part": parse_hier_part,
"net_path": parse_net_path,
"abs_path": parse_abs_path,
"opaque_part": parse_opaque_part,
"uric": parse_uric,
"uric_no_slash": parse_uric_no_slash,
"path_segments": parse_path_segments,
"segment": parse_segment,
"param": parse_param,
"pchar": parse_pchar,
"scheme": parse_scheme,
"authority": parse_authority,
"srvr": parse_srvr,
"reg_name": parse_reg_name,
"query": parse_query,
"SIP_Version": parse_SIP_Version,
"INVITEm": parse_INVITEm,
"ACKm": parse_ACKm,
"OPTIONSm": parse_OPTIONSm,
"BYEm": parse_BYEm,
"CANCELm": parse_CANCELm,
"REGISTERm": parse_REGISTERm,
"SUBSCRIBEm": parse_SUBSCRIBEm,
"NOTIFYm": parse_NOTIFYm,
"Method": parse_Method,
"Status_Line": parse_Status_Line,
"Status_Code": parse_Status_Code,
"extension_code": parse_extension_code,
"Reason_Phrase": parse_Reason_Phrase,
"Allow_Events": parse_Allow_Events,
"Call_ID": parse_Call_ID,
"Contact": parse_Contact,
"contact_param": parse_contact_param,
"name_addr": parse_name_addr,
"display_name": parse_display_name,
"contact_params": parse_contact_params,
"c_p_q": parse_c_p_q,
"c_p_expires": parse_c_p_expires,
"delta_seconds": parse_delta_seconds,
"qvalue": parse_qvalue,
"generic_param": parse_generic_param,
"gen_value": parse_gen_value,
"Content_Disposition": parse_Content_Disposition,
"disp_type": parse_disp_type,
"disp_param": parse_disp_param,
"handling_param": parse_handling_param,
"Content_Encoding": parse_Content_Encoding,
"Content_Length": parse_Content_Length,
"Content_Type": parse_Content_Type,
"media_type": parse_media_type,
"m_type": parse_m_type,
"discrete_type": parse_discrete_type,
"composite_type": parse_composite_type,
"extension_token": parse_extension_token,
"x_token": parse_x_token,
"m_subtype": parse_m_subtype,
"m_parameter": parse_m_parameter,
"m_value": parse_m_value,
"CSeq": parse_CSeq,
"CSeq_value": parse_CSeq_value,
"Expires": parse_Expires,
"Event": parse_Event,
"event_type": parse_event_type,
"From": parse_From,
"from_param": parse_from_param,
"tag_param": parse_tag_param,
"Max_Forwards": parse_Max_Forwards,
"Min_Expires": parse_Min_Expires,
"Name_Addr_Header": parse_Name_Addr_Header,
"Proxy_Authenticate": parse_Proxy_Authenticate,
"challenge": parse_challenge,
"other_challenge": parse_other_challenge,
"auth_param": parse_auth_param,
"digest_cln": parse_digest_cln,
"realm": parse_realm,
"realm_value": parse_realm_value,
"domain": parse_domain,
"URI": parse_URI,
"nonce": parse_nonce,
"nonce_value": parse_nonce_value,
"opaque": parse_opaque,
"stale": parse_stale,
"algorithm": parse_algorithm,
"qop_options": parse_qop_options,
"qop_value": parse_qop_value,
"Proxy_Require": parse_Proxy_Require,
"Record_Route": parse_Record_Route,
"rec_route": parse_rec_route,
"Require": parse_Require,
"Route": parse_Route,
"route_param": parse_route_param,
"Subscription_State": parse_Subscription_State,
"substate_value": parse_substate_value,
"subexp_params": parse_subexp_params,
"event_reason_value": parse_event_reason_value,
"Subject": parse_Subject,
"Supported": parse_Supported,
"To": parse_To,
"to_param": parse_to_param,
"Via": parse_Via,
"via_param": parse_via_param,
"via_params": parse_via_params,
"via_ttl": parse_via_ttl,
"via_maddr": parse_via_maddr,
"via_received": parse_via_received,
"via_branch": parse_via_branch,
"response_port": parse_response_port,
"sent_protocol": parse_sent_protocol,
"protocol_name": parse_protocol_name,
"transport": parse_transport,
"sent_by": parse_sent_by,
"via_host": parse_via_host,
"via_port": parse_via_port,
"ttl": parse_ttl,
"WWW_Authenticate": parse_WWW_Authenticate,
"Session_Expires": parse_Session_Expires,
"s_e_expires": parse_s_e_expires,
"s_e_params": parse_s_e_params,
"s_e_refresher": parse_s_e_refresher,
"extension_header": parse_extension_header,
"header_value": parse_header_value,
"message_body": parse_message_body,
"uuid_URI": parse_uuid_URI,
"uuid": parse_uuid,
"hex4": parse_hex4,
"hex8": parse_hex8,
"hex12": parse_hex12
};
if (startRule !== undefined) {
if (parseFunctions[startRule] === undefined) {
throw new Error("Invalid rule name: " + quote(startRule) + ".");
}
} else {
startRule = "CRLF";
}
var pos = 0;
var reportFailures = 0;
var rightmostFailuresPos = 0;
var rightmostFailuresExpected = [];
function padLeft(input, padding, length) {
var result = input;
var padLength = length - input.length;
for (var i = 0; i < padLength; i++) {
result = padding + result;
}
return result;
}
function escape(ch) {
var charCode = ch.charCodeAt(0);
var escapeChar;
var length;
if (charCode <= 0xFF) {
escapeChar = 'x';
length = 2;
} else {
escapeChar = 'u';
length = 4;
}
return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}
function matchFailed(failure) {
if (pos < rightmostFailuresPos) {
return;
}
if (pos > rightmostFailuresPos) {
rightmostFailuresPos = pos;
rightmostFailuresExpected = [];
}
rightmostFailuresExpected.push(failure);
}
function parse_CRLF() {
var result0;
if (input.substr(pos, 2) === "\r\n") {
result0 = "\r\n";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\\n\"");
}
}
return result0;
}
function parse_DIGIT() {
var result0;
if (/^[0-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
return result0;
}
function parse_ALPHA() {
var result0;
if (/^[a-zA-Z]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z]");
}
}
return result0;
}
function parse_HEXDIG() {
var result0;
if (/^[0-9a-fA-F]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[0-9a-fA-F]");
}
}
return result0;
}
function parse_WSP() {
var result0;
result0 = parse_SP();
if (result0 === null) {
result0 = parse_HTAB();
}
return result0;
}
function parse_OCTET() {
var result0;
if (/^[\0-\xFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\0-\\xFF]");
}
}
return result0;
}
function parse_DQUOTE() {
var result0;
if (/^["]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\"]");
}
}
return result0;
}
function parse_SP() {
var result0;
if (input.charCodeAt(pos) === 32) {
result0 = " ";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\" \"");
}
}
return result0;
}
function parse_HTAB() {
var result0;
if (input.charCodeAt(pos) === 9) {
result0 = "\t";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\t\"");
}
}
return result0;
}
function parse_alphanum() {
var result0;
if (/^[a-zA-Z0-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9]");
}
}
return result0;
}
function parse_reserved() {
var result0;
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_unreserved() {
var result0;
result0 = parse_alphanum();
if (result0 === null) {
result0 = parse_mark();
}
return result0;
}
function parse_mark() {
var result0;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 95) {
result0 = "_";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 46) {
result0 = ".";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 42) {
result0 = "*";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 39) {
result0 = "'";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 41) {
result0 = ")";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_escaped() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 37) {
result0 = "%";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result0 !== null) {
result1 = parse_HEXDIG();
if (result1 !== null) {
result2 = parse_HEXDIG();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, escaped) {return escaped.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LWS() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
pos2 = pos;
result0 = [];
result1 = parse_WSP();
while (result1 !== null) {
result0.push(result1);
result1 = parse_WSP();
}
if (result0 !== null) {
result1 = parse_CRLF();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos2;
}
} else {
result0 = null;
pos = pos2;
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result2 = parse_WSP();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_WSP();
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return " "; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SWS() {
var result0;
result0 = parse_LWS();
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_HCOLON() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ':'; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_TEXT_UTF8_TRIM() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result1 = parse_TEXT_UTF8char();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_TEXT_UTF8char();
}
} else {
result0 = null;
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = [];
result3 = parse_LWS();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LWS();
}
if (result2 !== null) {
result3 = parse_TEXT_UTF8char();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = [];
result3 = parse_LWS();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LWS();
}
if (result2 !== null) {
result3 = parse_TEXT_UTF8char();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_TEXT_UTF8char() {
var result0;
if (/^[!-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[!-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
}
return result0;
}
function parse_UTF8_NONASCII() {
var result0;
if (/^[\x80-\uFFFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\x80-\\uFFFF]");
}
}
return result0;
}
function parse_UTF8_CONT() {
var result0;
if (/^[\x80-\xBF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\x80-\\xBF]");
}
}
return result0;
}
function parse_LHEX() {
var result0;
result0 = parse_DIGIT();
if (result0 === null) {
if (/^[a-f]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-f]");
}
}
}
return result0;
}
function parse_token() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_token_nodot() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_separators() {
var result0;
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 41) {
result0 = ")";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 60) {
result0 = "<";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 92) {
result0 = "\\";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result0 === null) {
result0 = parse_DQUOTE();
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 123) {
result0 = "{";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 125) {
result0 = "}";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
if (result0 === null) {
result0 = parse_SP();
if (result0 === null) {
result0 = parse_HTAB();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_word() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 62) {
result1 = ">";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 92) {
result1 = "\\";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result1 === null) {
result1 = parse_DQUOTE();
if (result1 === null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 93) {
result1 = "]";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 123) {
result1 = "{";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 125) {
result1 = "}";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 62) {
result1 = ">";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 92) {
result1 = "\\";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result1 === null) {
result1 = parse_DQUOTE();
if (result1 === null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 93) {
result1 = "]";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 123) {
result1 = "{";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 125) {
result1 = "}";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_STAR() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "*"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SLASH() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "/"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_EQUAL() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "="; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LPAREN() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "("; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RPAREN() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ")"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RAQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 !== null) {
result1 = parse_SWS();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ">"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LAQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "<"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_COMMA() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ","; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SEMI() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ";"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_COLON() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ":"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LDQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "\""; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RDQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DQUOTE();
if (result0 !== null) {
result1 = parse_SWS();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "\""; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_comment() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_LPAREN();
if (result0 !== null) {
result1 = [];
result2 = parse_ctext();
if (result2 === null) {
result2 = parse_quoted_pair();
if (result2 === null) {
result2 = parse_comment();
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_ctext();
if (result2 === null) {
result2 = parse_quoted_pair();
if (result2 === null) {
result2 = parse_comment();
}
}
}
if (result1 !== null) {
result2 = parse_RPAREN();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_ctext() {
var result0;
if (/^[!-']/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[!-']");
}
}
if (result0 === null) {
if (/^[*-[]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[*-[]");
}
}
if (result0 === null) {
if (/^[\]-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\]-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
if (result0 === null) {
result0 = parse_LWS();
}
}
}
}
return result0;
}
function parse_quoted_string() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result2 = [];
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
while (result3 !== null) {
result2.push(result3);
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
}
if (result2 !== null) {
result3 = parse_DQUOTE();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_quoted_string_clean() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result2 = [];
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
while (result3 !== null) {
result2.push(result3);
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
}
if (result2 !== null) {
result3 = parse_DQUOTE();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos-1, offset+1); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qdtext() {
var result0;
result0 = parse_LWS();
if (result0 === null) {
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 === null) {
if (/^[#-[]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[#-[]");
}
}
if (result0 === null) {
if (/^[\]-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\]-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
}
}
}
}
return result0;
}
function parse_quoted_pair() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 92) {
result0 = "\\";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result0 !== null) {
if (/^[\0-\t]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\0-\\t]");
}
}
if (result1 === null) {
if (/^[\x0B-\f]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\x0B-\\f]");
}
}
if (result1 === null) {
if (/^[\x0E-]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\x0E-]");
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SIP_URI_noparams() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_uri_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_userinfo();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_hostport();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data.uri = new URI(data.scheme, data.user, data.host, data.port);
delete data.scheme;
delete data.user;
delete data.host;
delete data.host_type;
delete data.port;
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SIP_URI() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_uri_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_userinfo();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_hostport();
if (result3 !== null) {
result4 = parse_uri_parameters();
if (result4 !== null) {
result5 = parse_headers();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
try {
data.uri = new URI(data.scheme, data.user, data.host, data.port, data.uri_params, data.uri_headers);
delete data.scheme;
delete data.user;
delete data.host;
delete data.host_type;
delete data.port;
delete data.uri_params;
if (startRule === 'SIP_URI') { data = data.uri;}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_scheme() {
var result0;
var pos0;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"sip\"");
}
}
if (result0 === null) {
pos0 = pos;
if (input.substr(pos, 4).toLowerCase() === "sips") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"sips\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.scheme = uri_scheme.toLowerCase(); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
}
return result0;
}
function parse_userinfo() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_user();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_password();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.charCodeAt(pos) === 64) {
result2 = "@";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.user = decodeURIComponent(input.substring(pos-1, offset));})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_user() {
var result0, result1;
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_user_unreserved();
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_user_unreserved();
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_user_unreserved() {
var result0;
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_password() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = [];
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.password = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hostport() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_host();
if (result0 !== null) {
pos1 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_port();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_host() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_IPv4address();
if (result0 === null) {
result0 = parse_IPv6reference();
if (result0 === null) {
result0 = parse_hostname();
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host = input.substring(pos, offset).toLowerCase();
return data.host; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hostname() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = [];
pos2 = pos;
result1 = parse_domainlabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
while (result1 !== null) {
result0.push(result1);
pos2 = pos;
result1 = parse_domainlabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
}
if (result0 !== null) {
result1 = parse_toplabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'domain';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_domainlabel() {
var result0, result1;
if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9_\\-]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9_\\-]");
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_toplabel() {
var result0, result1;
if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9_\\-]");
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9_\\-]");
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_IPv6reference() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 !== null) {
result1 = parse_IPv6address();
if (result1 !== null) {
if (input.charCodeAt(pos) === 93) {
result2 = "]";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv6';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_IPv6address() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_h16();
if (result8 !== null) {
if (input.charCodeAt(pos) === 58) {
result9 = ":";
pos++;
} else {
result9 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result9 !== null) {
result10 = parse_h16();
if (result10 !== null) {
if (input.charCodeAt(pos) === 58) {
result11 = ":";
pos++;
} else {
result11 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result11 !== null) {
result12 = parse_ls32();
if (result12 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_h16();
if (result9 !== null) {
if (input.charCodeAt(pos) === 58) {
result10 = ":";
pos++;
} else {
result10 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result10 !== null) {
result11 = parse_ls32();
if (result11 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_ls32();
if (result9 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_ls32();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_ls32();
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_ls32();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_ls32();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.substr(pos, 2) === "::") {
result1 = "::";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_h16();
if (result8 !== null) {
if (input.charCodeAt(pos) === 58) {
result9 = ":";
pos++;
} else {
result9 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result9 !== null) {
result10 = parse_ls32();
if (result10 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.substr(pos, 2) === "::") {
result2 = "::";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_ls32();
if (result9 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
if (input.substr(pos, 2) === "::") {
result3 = "::";
pos += 2;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_ls32();
if (result8 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
if (input.substr(pos, 2) === "::") {
result4 = "::";
pos += 2;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_ls32();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
if (input.substr(pos, 2) === "::") {
result5 = "::";
pos += 2;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result5 !== null) {
result6 = parse_ls32();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
if (input.substr(pos, 2) === "::") {
result6 = "::";
pos += 2;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
result6 = [result6, result7];
} else {
result6 = null;
pos = pos2;
}
} else {
result6 = null;
pos = pos2;
}
result6 = result6 !== null ? result6 : "";
if (result6 !== null) {
if (input.substr(pos, 2) === "::") {
result7 = "::";
pos += 2;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv6';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_h16() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_HEXDIG();
if (result0 !== null) {
result1 = parse_HEXDIG();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_HEXDIG();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_HEXDIG();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_ls32() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_IPv4address();
}
return result0;
}
function parse_IPv4address() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_dec_octet();
if (result0 !== null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_dec_octet();
if (result2 !== null) {
if (input.charCodeAt(pos) === 46) {
result3 = ".";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result3 !== null) {
result4 = parse_dec_octet();
if (result4 !== null) {
if (input.charCodeAt(pos) === 46) {
result5 = ".";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result5 !== null) {
result6 = parse_dec_octet();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv4';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_dec_octet() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "25") {
result0 = "25";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"25\"");
}
}
if (result0 !== null) {
if (/^[0-5]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-5]");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 50) {
result0 = "2";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"2\"");
}
}
if (result0 !== null) {
if (/^[0-4]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-4]");
}
}
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 49) {
result0 = "1";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"1\"");
}
}
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (/^[1-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[1-9]");
}
}
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_DIGIT();
}
}
}
}
return result0;
}
function parse_port() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, port) {
port = parseInt(port.join(''));
data.port = port;
return port; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_parameters() {
var result0, result1, result2;
var pos0;
result0 = [];
pos0 = pos;
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_uri_parameter();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos0;
}
} else {
result1 = null;
pos = pos0;
}
while (result1 !== null) {
result0.push(result1);
pos0 = pos;
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_uri_parameter();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos0;
}
} else {
result1 = null;
pos = pos0;
}
}
return result0;
}
function parse_uri_parameter() {
var result0;
result0 = parse_transport_param();
if (result0 === null) {
result0 = parse_user_param();
if (result0 === null) {
result0 = parse_method_param();
if (result0 === null) {
result0 = parse_ttl_param();
if (result0 === null) {
result0 = parse_maddr_param();
if (result0 === null) {
result0 = parse_lr_param();
if (result0 === null) {
result0 = parse_other_param();
}
}
}
}
}
}
return result0;
}
function parse_transport_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 10).toLowerCase() === "transport=") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"transport=\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 3).toLowerCase() === "udp") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"udp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 3).toLowerCase() === "tcp") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"tcp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 4).toLowerCase() === "sctp") {
result1 = input.substr(pos, 4);
pos += 4;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"sctp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 3).toLowerCase() === "tls") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"tls\"");
}
}
if (result1 === null) {
result1 = parse_token();
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, transport) {
if(!data.uri_params) data.uri_params={};
data.uri_params['transport'] = transport.toLowerCase(); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_user_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "user=") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"user=\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 5).toLowerCase() === "phone") {
result1 = input.substr(pos, 5);
pos += 5;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"phone\"");
}
}
if (result1 === null) {
if (input.substr(pos, 2).toLowerCase() === "ip") {
result1 = input.substr(pos, 2);
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"ip\"");
}
}
if (result1 === null) {
result1 = parse_token();
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, user) {
if(!data.uri_params) data.uri_params={};
data.uri_params['user'] = user.toLowerCase(); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_method_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "method=") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"method=\"");
}
}
if (result0 !== null) {
result1 = parse_Method();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, method) {
if(!data.uri_params) data.uri_params={};
data.uri_params['method'] = method; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ttl_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 4).toLowerCase() === "ttl=") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ttl=\"");
}
}
if (result0 !== null) {
result1 = parse_ttl();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, ttl) {
if(!data.params) data.params={};
data.params['ttl'] = ttl; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_maddr_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "maddr=") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"maddr=\"");
}
}
if (result0 !== null) {
result1 = parse_host();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, maddr) {
if(!data.uri_params) data.uri_params={};
data.uri_params['maddr'] = maddr; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_lr_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 2).toLowerCase() === "lr") {
result0 = input.substr(pos, 2);
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"lr\"");
}
}
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
if(!data.uri_params) data.uri_params={};
data.uri_params['lr'] = undefined; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_other_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_pname();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_pvalue();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, param, value) {
if(!data.uri_params) data.uri_params = {};
if (typeof value === 'undefined'){
value = undefined;
}
else {
value = value[1];
}
data.uri_params[param.toLowerCase()] = value && value.toLowerCase();})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_pname() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_paramchar();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_paramchar();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, pname) {return pname.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_pvalue() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_paramchar();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_paramchar();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, pvalue) {return pvalue.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_paramchar() {
var result0;
result0 = parse_param_unreserved();
if (result0 === null) {
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
}
}
return result0;
}
function parse_param_unreserved() {
var result0;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
}
}
}
}
}
}
return result0;
}
function parse_headers() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 !== null) {
result1 = parse_header();
if (result1 !== null) {
result2 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 38) {
result3 = "&";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result3 !== null) {
result4 = parse_header();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
while (result3 !== null) {
result2.push(result3);
pos1 = pos;
if (input.charCodeAt(pos) === 38) {
result3 = "&";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result3 !== null) {
result4 = parse_header();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_header() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_hname();
if (result0 !== null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_hvalue();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, hname, hvalue) {
hname = hname.join('').toLowerCase();
hvalue = hvalue.join('');
if(!data.uri_headers) data.uri_headers = {};
if (!data.uri_headers[hname]) {
data.uri_headers[hname] = [hvalue];
} else {
data.uri_headers[hname].push(hvalue);
}})(pos0, result0[0], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hname() {
var result0, result1;
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_hvalue() {
var result0, result1;
result0 = [];
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
}
return result0;
}
function parse_hnv_unreserved() {
var result0;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
}
}
}
}
}
}
return result0;
}
function parse_Request_Response() {
var result0;
result0 = parse_Status_Line();
if (result0 === null) {
result0 = parse_Request_Line();
}
return result0;
}
function parse_Request_Line() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_Method();
if (result0 !== null) {
result1 = parse_SP();
if (result1 !== null) {
result2 = parse_Request_URI();
if (result2 !== null) {
result3 = parse_SP();
if (result3 !== null) {
result4 = parse_SIP_Version();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Request_URI() {
var result0;
result0 = parse_SIP_URI();
if (result0 === null) {
result0 = parse_absoluteURI();
}
return result0;
}
function parse_absoluteURI() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_hier_part();
if (result2 === null) {
result2 = parse_opaque_part();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hier_part() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_net_path();
if (result0 === null) {
result0 = parse_abs_path();
}
if (result0 !== null) {
pos1 = pos;
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 !== null) {
result2 = parse_query();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_net_path() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "//") {
result0 = "//";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"//\"");
}
}
if (result0 !== null) {
result1 = parse_authority();
if (result1 !== null) {
result2 = parse_abs_path();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_abs_path() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 !== null) {
result1 = parse_path_segments();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_opaque_part() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_uric_no_slash();
if (result0 !== null) {
result1 = [];
result2 = parse_uric();
while (result2 !== null) {
result1.push(result2);
result2 = parse_uric();
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_uric() {
var result0;
result0 = parse_reserved();
if (result0 === null) {
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
}
}
return result0;
}
function parse_uric_no_slash() {
var result0;
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_path_segments() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_segment();
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 47) {
result2 = "/";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result2 !== null) {
result3 = parse_segment();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 47) {
result2 = "/";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result2 !== null) {
result3 = parse_segment();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_segment() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = [];
result1 = parse_pchar();
while (result1 !== null) {
result0.push(result1);
result1 = parse_pchar();
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 59) {
result2 = ";";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result2 !== null) {
result3 = parse_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 59) {
result2 = ";";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result2 !== null) {
result3 = parse_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_param() {
var result0, result1;
result0 = [];
result1 = parse_pchar();
while (result1 !== null) {
result0.push(result1);
result1 = parse_pchar();
}
return result0;
}
function parse_pchar() {
var result0;
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_scheme() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_ALPHA();
if (result0 !== null) {
result1 = [];
result2 = parse_ALPHA();
if (result2 === null) {
result2 = parse_DIGIT();
if (result2 === null) {
if (input.charCodeAt(pos) === 43) {
result2 = "+";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_ALPHA();
if (result2 === null) {
result2 = parse_DIGIT();
if (result2 === null) {
if (input.charCodeAt(pos) === 43) {
result2 = "+";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.scheme= input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_authority() {
var result0;
result0 = parse_srvr();
if (result0 === null) {
result0 = parse_reg_name();
}
return result0;
}
function parse_srvr() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_userinfo();
if (result0 !== null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_hostport();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_reg_name() {
var result0, result1;
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_query() {
var result0, result1;
result0 = [];
result1 = parse_uric();
while (result1 !== null) {
result0.push(result1);
result1 = parse_uric();
}
return result0;
}
function parse_SIP_Version() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 !== null) {
result3 = parse_DIGIT();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
} else {
result2 = null;
}
if (result2 !== null) {
if (input.charCodeAt(pos) === 46) {
result3 = ".";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result3 !== null) {
result5 = parse_DIGIT();
if (result5 !== null) {
result4 = [];
while (result5 !== null) {
result4.push(result5);
result5 = parse_DIGIT();
}
} else {
result4 = null;
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.sip_version = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_INVITEm() {
var result0;
if (input.substr(pos, 6) === "INVITE") {
result0 = "INVITE";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"INVITE\"");
}
}
return result0;
}
function parse_ACKm() {
var result0;
if (input.substr(pos, 3) === "ACK") {
result0 = "ACK";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ACK\"");
}
}
return result0;
}
function parse_OPTIONSm() {
var result0;
if (input.substr(pos, 7) === "OPTIONS") {
result0 = "OPTIONS";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"OPTIONS\"");
}
}
return result0;
}
function parse_BYEm() {
var result0;
if (input.substr(pos, 3) === "BYE") {
result0 = "BYE";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"BYE\"");
}
}
return result0;
}
function parse_CANCELm() {
var result0;
if (input.substr(pos, 6) === "CANCEL") {
result0 = "CANCEL";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"CANCEL\"");
}
}
return result0;
}
function parse_REGISTERm() {
var result0;
if (input.substr(pos, 8) === "REGISTER") {
result0 = "REGISTER";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REGISTER\"");
}
}
return result0;
}
function parse_SUBSCRIBEm() {
var result0;
if (input.substr(pos, 9) === "SUBSCRIBE") {
result0 = "SUBSCRIBE";
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SUBSCRIBE\"");
}
}
return result0;
}
function parse_NOTIFYm() {
var result0;
if (input.substr(pos, 6) === "NOTIFY") {
result0 = "NOTIFY";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"NOTIFY\"");
}
}
return result0;
}
function parse_Method() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_INVITEm();
if (result0 === null) {
result0 = parse_ACKm();
if (result0 === null) {
result0 = parse_OPTIONSm();
if (result0 === null) {
result0 = parse_BYEm();
if (result0 === null) {
result0 = parse_CANCELm();
if (result0 === null) {
result0 = parse_REGISTERm();
if (result0 === null) {
result0 = parse_SUBSCRIBEm();
if (result0 === null) {
result0 = parse_NOTIFYm();
if (result0 === null) {
result0 = parse_token();
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.method = input.substring(pos, offset);
return data.method; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Status_Line() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_SIP_Version();
if (result0 !== null) {
result1 = parse_SP();
if (result1 !== null) {
result2 = parse_Status_Code();
if (result2 !== null) {
result3 = parse_SP();
if (result3 !== null) {
result4 = parse_Reason_Phrase();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Status_Code() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_extension_code();
if (result0 !== null) {
result0 = (function(offset, status_code) {
data.status_code = parseInt(status_code.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_extension_code() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_DIGIT();
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Reason_Phrase() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = [];
result1 = parse_reserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_UTF8_NONASCII();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
}
}
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_reserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_UTF8_NONASCII();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.reason_phrase = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Allow_Events() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_event_type();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_event_type();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_event_type();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Call_ID() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_word();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result2 = parse_word();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Contact() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
result0 = parse_STAR();
if (result0 === null) {
pos1 = pos;
result0 = parse_contact_param();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_contact_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_contact_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
}
if (result0 !== null) {
result0 = (function(offset) {
var idx, length;
length = data.multi_header.length;
for (idx = 0; idx < length; idx++) {
if (data.multi_header[idx].parsed === null) {
data = null;
break;
}
}
if (data !== null) {
data = data.multi_header;
} else {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_contact_param() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_contact_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_contact_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
if(!data.multi_header) data.multi_header = [];
try {
header = new NameAddrHeader(data.uri, data.display_name, data.params);
delete data.uri;
delete data.display_name;
delete data.params;
} catch(e) {
header = null;
}
data.multi_header.push( { 'possition': pos,
'offset': offset,
'parsed': header
});})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_name_addr() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_display_name();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_LAQUOT();
if (result1 !== null) {
result2 = parse_SIP_URI();
if (result2 !== null) {
result3 = parse_RAQUOT();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_display_name() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_LWS();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_LWS();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
result0 = parse_quoted_string();
}
if (result0 !== null) {
result0 = (function(offset, display_name) {
display_name = input.substring(pos, offset).trim();
if (display_name[0] === '\"') {
display_name = display_name.substring(1, display_name.length-1);
}
data.display_name = display_name; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_contact_params() {
var result0;
result0 = parse_c_p_q();
if (result0 === null) {
result0 = parse_c_p_expires();
if (result0 === null) {
result0 = parse_generic_param();
}
}
return result0;
}
function parse_c_p_q() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 1).toLowerCase() === "q") {
result0 = input.substr(pos, 1);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"q\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_qvalue();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, q) {
if(!data.params) data.params = {};
data.params['q'] = q; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_c_p_expires() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "expires") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"expires\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expires) {
if(!data.params) data.params = {};
data.params['expires'] = expires; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_delta_seconds() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, delta_seconds) {
return parseInt(delta_seconds.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qvalue() {
var result0, result1, result2, result3, result4;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 48) {
result0 = "0";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"0\"");
}
}
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result1 = [result1, result2, result3, result4];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return parseFloat(input.substring(pos, offset)); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_generic_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_token();
if (result0 !== null) {
pos2 = pos;
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_gen_value();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, param, value) {
if(!data.params) data.params = {};
if (typeof value === 'undefined'){
value = undefined;
}
else {
value = value[1];
}
data.params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_gen_value() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_host();
if (result0 === null) {
result0 = parse_quoted_string();
}
}
return result0;
}
function parse_Content_Disposition() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_disp_type();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_disp_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_disp_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_disp_type() {
var result0;
if (input.substr(pos, 6).toLowerCase() === "render") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"render\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "session") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"session\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "icon") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"icon\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "alert") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"alert\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
return result0;
}
function parse_disp_param() {
var result0;
result0 = parse_handling_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_handling_param() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 8).toLowerCase() === "handling") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"handling\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 8).toLowerCase() === "optional") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"optional\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8).toLowerCase() === "required") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"required\"");
}
}
if (result2 === null) {
result2 = parse_token();
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Content_Encoding() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Content_Length() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, length) {
data = parseInt(length.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Content_Type() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_media_type();
if (result0 !== null) {
result0 = (function(offset) {
data = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_media_type() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_m_type();
if (result0 !== null) {
result1 = parse_SLASH();
if (result1 !== null) {
result2 = parse_m_subtype();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_m_parameter();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_m_parameter();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_type() {
var result0;
result0 = parse_discrete_type();
if (result0 === null) {
result0 = parse_composite_type();
}
return result0;
}
function parse_discrete_type() {
var result0;
if (input.substr(pos, 4).toLowerCase() === "text") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"text\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "image") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"image\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "audio") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"audio\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "video") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"video\"");
}
}
if (result0 === null) {
if (input.substr(pos, 11).toLowerCase() === "application") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"application\"");
}
}
if (result0 === null) {
result0 = parse_extension_token();
}
}
}
}
}
return result0;
}
function parse_composite_type() {
var result0;
if (input.substr(pos, 7).toLowerCase() === "message") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"message\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "multipart") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"multipart\"");
}
}
if (result0 === null) {
result0 = parse_extension_token();
}
}
return result0;
}
function parse_extension_token() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_x_token();
}
return result0;
}
function parse_x_token() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.substr(pos, 2).toLowerCase() === "x-") {
result0 = input.substr(pos, 2);
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"x-\"");
}
}
if (result0 !== null) {
result1 = parse_token();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_subtype() {
var result0;
result0 = parse_extension_token();
if (result0 === null) {
result0 = parse_token();
}
return result0;
}
function parse_m_parameter() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_m_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_value() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_quoted_string();
}
return result0;
}
function parse_CSeq() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_CSeq_value();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_Method();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_CSeq_value() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, cseq_value) {
data.value=parseInt(cseq_value.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, expires) {data = expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Event() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_event_type();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, event_type) {
data.event = event_type.join('').toLowerCase(); })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_event_type() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token_nodot();
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result3 = parse_token_nodot();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result3 = parse_token_nodot();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_From() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_from_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_from_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var tag = data.tag;
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
if (tag) {data.setParam('tag',tag)}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_from_param() {
var result0;
result0 = parse_tag_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_tag_param() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "tag") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, tag) {data.tag = tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Max_Forwards() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, forwards) {
data = parseInt(forwards.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Min_Expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, min_expires) {data = min_expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Name_Addr_Header() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_display_name();
while (result1 !== null) {
result0.push(result1);
result1 = parse_display_name();
}
if (result0 !== null) {
result1 = parse_LAQUOT();
if (result1 !== null) {
result2 = parse_SIP_URI();
if (result2 !== null) {
result3 = parse_RAQUOT();
if (result3 !== null) {
result4 = [];
pos2 = pos;
result5 = parse_SEMI();
if (result5 !== null) {
result6 = parse_generic_param();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
while (result5 !== null) {
result4.push(result5);
pos2 = pos;
result5 = parse_SEMI();
if (result5 !== null) {
result6 = parse_generic_param();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Proxy_Authenticate() {
var result0;
result0 = parse_challenge();
return result0;
}
function parse_challenge() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "digest") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Digest\"");
}
}
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_digest_cln();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_digest_cln();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_digest_cln();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_other_challenge();
}
return result0;
}
function parse_other_challenge() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_auth_param();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_auth_param();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_auth_param();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_auth_param() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 === null) {
result2 = parse_quoted_string();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_digest_cln() {
var result0;
result0 = parse_realm();
if (result0 === null) {
result0 = parse_domain();
if (result0 === null) {
result0 = parse_nonce();
if (result0 === null) {
result0 = parse_opaque();
if (result0 === null) {
result0 = parse_stale();
if (result0 === null) {
result0 = parse_algorithm();
if (result0 === null) {
result0 = parse_qop_options();
if (result0 === null) {
result0 = parse_auth_param();
}
}
}
}
}
}
}
return result0;
}
function parse_realm() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "realm") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"realm\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_realm_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_realm_value() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_quoted_string_clean();
if (result0 !== null) {
result0 = (function(offset, realm) { data.realm = realm; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_domain() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "domain") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"domain\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_LDQUOT();
if (result2 !== null) {
result3 = parse_URI();
if (result3 !== null) {
result4 = [];
pos1 = pos;
result6 = parse_SP();
if (result6 !== null) {
result5 = [];
while (result6 !== null) {
result5.push(result6);
result6 = parse_SP();
}
} else {
result5 = null;
}
if (result5 !== null) {
result6 = parse_URI();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos1;
}
} else {
result5 = null;
pos = pos1;
}
while (result5 !== null) {
result4.push(result5);
pos1 = pos;
result6 = parse_SP();
if (result6 !== null) {
result5 = [];
while (result6 !== null) {
result5.push(result6);
result6 = parse_SP();
}
} else {
result5 = null;
}
if (result5 !== null) {
result6 = parse_URI();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos1;
}
} else {
result5 = null;
pos = pos1;
}
}
if (result4 !== null) {
result5 = parse_RDQUOT();
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_URI() {
var result0;
result0 = parse_absoluteURI();
if (result0 === null) {
result0 = parse_abs_path();
}
return result0;
}
function parse_nonce() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "nonce") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"nonce\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_nonce_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_nonce_value() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_quoted_string_clean();
if (result0 !== null) {
result0 = (function(offset, nonce) { data.nonce=nonce; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_opaque() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "opaque") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"opaque\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_quoted_string_clean();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, opaque) { data.opaque=opaque; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_stale() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "stale") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"stale\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
pos1 = pos;
if (input.substr(pos, 4).toLowerCase() === "true") {
result2 = input.substr(pos, 4);
pos += 4;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"true\"");
}
}
if (result2 !== null) {
result2 = (function(offset) { data.stale=true; })(pos1);
}
if (result2 === null) {
pos = pos1;
}
if (result2 === null) {
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "false") {
result2 = input.substr(pos, 5);
pos += 5;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"false\"");
}
}
if (result2 !== null) {
result2 = (function(offset) { data.stale=false; })(pos1);
}
if (result2 === null) {
pos = pos1;
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_algorithm() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 9).toLowerCase() === "algorithm") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"algorithm\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 3).toLowerCase() === "md5") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"MD5\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8).toLowerCase() === "md5-sess") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"MD5-sess\"");
}
}
if (result2 === null) {
result2 = parse_token();
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, algorithm) {
data.algorithm=algorithm.toUpperCase(); })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qop_options() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "qop") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"qop\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_LDQUOT();
if (result2 !== null) {
pos1 = pos;
result3 = parse_qop_value();
if (result3 !== null) {
result4 = [];
pos2 = pos;
if (input.charCodeAt(pos) === 44) {
result5 = ",";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result5 !== null) {
result6 = parse_qop_value();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
while (result5 !== null) {
result4.push(result5);
pos2 = pos;
if (input.charCodeAt(pos) === 44) {
result5 = ",";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result5 !== null) {
result6 = parse_qop_value();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
}
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
if (result3 !== null) {
result4 = parse_RDQUOT();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_qop_value() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 8).toLowerCase() === "auth-int") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"auth-int\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "auth") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"auth\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
if (result0 !== null) {
result0 = (function(offset, qop_value) {
data.qop || (data.qop=[]);
data.qop.push(qop_value.toLowerCase()); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Proxy_Require() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Record_Route() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_rec_route();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_rec_route();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_rec_route();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var idx, length;
length = data.multi_header.length;
for (idx = 0; idx < length; idx++) {
if (data.multi_header[idx].parsed === null) {
data = null;
break;
}
}
if (data !== null) {
data = data.multi_header;
} else {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_rec_route() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_name_addr();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
if(!data.multi_header) data.multi_header = [];
try {
header = new NameAddrHeader(data.uri, data.display_name, data.params);
delete data.uri;
delete data.display_name;
delete data.params;
} catch(e) {
header = null;
}
data.multi_header.push( { 'possition': pos,
'offset': offset,
'parsed': header
});})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Require() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Route() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_route_param();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_route_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_route_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_route_param() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_name_addr();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Subscription_State() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_substate_value();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_subexp_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_subexp_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_substate_value() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "active") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"active\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "pending") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"pending\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10).toLowerCase() === "terminated") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"terminated\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.state = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_subexp_params() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "reason") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"reason\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_event_reason_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, reason) {
if (typeof reason !== 'undefined') data.reason = reason; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "expires") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"expires\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expires) {
if (typeof expires !== 'undefined') data.expires = expires; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 11).toLowerCase() === "retry_after") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"retry_after\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, retry_after) {
if (typeof retry_after !== 'undefined') data.retry_after = retry_after; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
return result0;
}
function parse_event_reason_value() {
var result0;
if (input.substr(pos, 11).toLowerCase() === "deactivated") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"deactivated\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "probation") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"probation\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8).toLowerCase() === "rejected") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"rejected\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "timeout") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"timeout\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6).toLowerCase() === "giveup") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"giveup\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10).toLowerCase() === "noresource") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"noresource\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "invariant") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"invariant\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
}
}
}
return result0;
}
function parse_Subject() {
var result0;
result0 = parse_TEXT_UTF8_TRIM();
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_Supported() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_To() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_to_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_to_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var tag = data.tag;
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
if (tag) {data.setParam('tag',tag)}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_to_param() {
var result0;
result0 = parse_tag_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_Via() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_via_param();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_via_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_via_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_param() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_sent_protocol();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_sent_by();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_via_params();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_via_params();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_params() {
var result0;
result0 = parse_via_ttl();
if (result0 === null) {
result0 = parse_via_maddr();
if (result0 === null) {
result0 = parse_via_received();
if (result0 === null) {
result0 = parse_via_branch();
if (result0 === null) {
result0 = parse_response_port();
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
}
}
return result0;
}
function parse_via_ttl() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "ttl") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ttl\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_ttl();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_ttl_value) {
data.ttl = via_ttl_value; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_maddr() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "maddr") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"maddr\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_host();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_maddr) {
data.maddr = via_maddr; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_received() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 8).toLowerCase() === "received") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"received\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_IPv4address();
if (result2 === null) {
result2 = parse_IPv6address();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_received) {
data.received = via_received; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_branch() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "branch") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"branch\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_branch) {
data.branch = via_branch; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_response_port() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "rport") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"rport\"");
}
}
if (result0 !== null) {
pos2 = pos;
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = [];
result3 = parse_DIGIT();
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
if(typeof response_port !== 'undefined')
data.rport = response_port.join(''); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_sent_protocol() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_protocol_name();
if (result0 !== null) {
result1 = parse_SLASH();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result3 = parse_SLASH();
if (result3 !== null) {
result4 = parse_transport();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_protocol_name() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
if (result0 !== null) {
result0 = (function(offset, via_protocol) {
data.protocol = via_protocol; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_transport() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "udp") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"UDP\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3).toLowerCase() === "tcp") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"TCP\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3).toLowerCase() === "tls") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"TLS\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "sctp") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SCTP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
if (result0 !== null) {
result0 = (function(offset, via_transport) {
data.transport = via_transport; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_sent_by() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_via_host();
if (result0 !== null) {
pos1 = pos;
result1 = parse_COLON();
if (result1 !== null) {
result2 = parse_via_port();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_host() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_IPv4address();
if (result0 === null) {
result0 = parse_IPv6reference();
if (result0 === null) {
result0 = parse_hostname();
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_port() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_sent_by_port) {
data.port = parseInt(via_sent_by_port.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ttl() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, ttl) {
return parseInt(ttl.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_WWW_Authenticate() {
var result0;
result0 = parse_challenge();
return result0;
}
function parse_Session_Expires() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_s_e_expires();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_s_e_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_s_e_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_s_e_expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, expires) { data.expires = expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_s_e_params() {
var result0;
result0 = parse_s_e_refresher();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_s_e_refresher() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 9).toLowerCase() === "refresher") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"refresher\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 3).toLowerCase() === "uac") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"uac\"");
}
}
if (result2 === null) {
if (input.substr(pos, 3).toLowerCase() === "uas") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"uas\"");
}
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, s_e_refresher_value) { data.refresher = s_e_refresher_value.toLowerCase(); })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_extension_header() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_HCOLON();
if (result1 !== null) {
result2 = parse_header_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_header_value() {
var result0, result1;
result0 = [];
result1 = parse_TEXT_UTF8char();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_LWS();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_TEXT_UTF8char();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_LWS();
}
}
}
return result0;
}
function parse_message_body() {
var result0, result1;
result0 = [];
result1 = parse_OCTET();
while (result1 !== null) {
result0.push(result1);
result1 = parse_OCTET();
}
return result0;
}
function parse_uuid_URI() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.substr(pos, 5) === "uuid:") {
result0 = "uuid:";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"uuid:\"");
}
}
if (result0 !== null) {
result1 = parse_uuid();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_uuid() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_hex8();
if (result0 !== null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 !== null) {
result2 = parse_hex4();
if (result2 !== null) {
if (input.charCodeAt(pos) === 45) {
result3 = "-";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result3 !== null) {
result4 = parse_hex4();
if (result4 !== null) {
if (input.charCodeAt(pos) === 45) {
result5 = "-";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result5 !== null) {
result6 = parse_hex4();
if (result6 !== null) {
if (input.charCodeAt(pos) === 45) {
result7 = "-";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result7 !== null) {
result8 = parse_hex12();
if (result8 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, uuid) {
data = input.substring(pos+5, offset); })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hex4() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_HEXDIG();
if (result0 !== null) {
result1 = parse_HEXDIG();
if (result1 !== null) {
result2 = parse_HEXDIG();
if (result2 !== null) {
result3 = parse_HEXDIG();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hex8() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = parse_hex4();
if (result0 !== null) {
result1 = parse_hex4();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hex12() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_hex4();
if (result0 !== null) {
result1 = parse_hex4();
if (result1 !== null) {
result2 = parse_hex4();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function cleanupExpected(expected) {
expected.sort();
var lastExpected = null;
var cleanExpected = [];
for (var i = 0; i < expected.length; i++) {
if (expected[i] !== lastExpected) {
cleanExpected.push(expected[i]);
lastExpected = expected[i];
}
}
return cleanExpected;
}
function computeErrorPosition() {
/*
* The first idea was to use |String.split| to break the input up to the
* error position along newlines and derive the line and column from
* there. However IE's |split| implementation is so broken that it was
* enough to prevent it.
*/
var line = 1;
var column = 1;
var seenCR = false;
for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {
var ch = input.charAt(i);
if (ch === "\n") {
if (!seenCR) { line++; }
column = 1;
seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
line++;
column = 1;
seenCR = true;
} else {
column++;
seenCR = false;
}
}
return { line: line, column: column };
}
var URI = require('./URI');
var NameAddrHeader = require('./NameAddrHeader');
var data = {};
var result = parseFunctions[startRule]();
/*
* The parser is now in one of the following three states:
*
* 1. The parser successfully parsed the whole input.
*
* - |result !== null|
* - |pos === input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 2. The parser successfully parsed only a part of the input.
*
* - |result !== null|
* - |pos < input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 3. The parser did not successfully parse any part of the input.
*
* - |result === null|
* - |pos === 0|
* - |rightmostFailuresExpected| contains at least one failure
*
* All code following this comment (including called functions) must
* handle these states.
*/
if (result === null || pos !== input.length) {
var offset = Math.max(pos, rightmostFailuresPos);
var found = offset < input.length ? input.charAt(offset) : null;
var errorPosition = computeErrorPosition();
new this.SyntaxError(
cleanupExpected(rightmostFailuresExpected),
found,
offset,
errorPosition.line,
errorPosition.column
);
return -1;
}
return data;
},
/* Returns the parser source code. */
toSource: function() { return this._source; }
};
/* Thrown when a parser encounters a syntax error. */
result.SyntaxError = function(expected, found, offset, line, column) {
function buildMessage(expected, found) {
var expectedHumanized, foundHumanized;
switch (expected.length) {
case 0:
expectedHumanized = "end of input";
break;
case 1:
expectedHumanized = expected[0];
break;
default:
expectedHumanized = expected.slice(0, expected.length - 1).join(", ")
+ " or "
+ expected[expected.length - 1];
}
foundHumanized = found ? quote(found) : "end of input";
return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";
}
this.name = "SyntaxError";
this.expected = expected;
this.found = found;
this.message = buildMessage(expected, found);
this.offset = offset;
this.line = line;
this.column = column;
};
result.SyntaxError.prototype = Error.prototype;
return result;
})();
},{"./NameAddrHeader":9,"./URI":21}],7:[function(require,module,exports){
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP');
var pkg = require('../package.json');
debug('version %s', pkg.version);
var rtcninja = require('rtcninja');
var C = require('./Constants');
var Exceptions = require('./Exceptions');
var Utils = require('./Utils');
var UA = require('./UA');
var URI = require('./URI');
var NameAddrHeader = require('./NameAddrHeader');
var Grammar = require('./Grammar');
/**
* Expose the JsSIP module.
*/
var JsSIP = module.exports = {
C: C,
Exceptions: Exceptions,
Utils: Utils,
UA: UA,
URI: URI,
NameAddrHeader: NameAddrHeader,
Grammar: Grammar,
// Expose the debug module.
debug: require('debug'),
// Expose the rtcninja module.
rtcninja: rtcninja
};
Object.defineProperties(JsSIP, {
name: {
get: function() { return pkg.title; }
},
version: {
get: function() { return pkg.version; }
}
});
},{"../package.json":46,"./Constants":1,"./Exceptions":5,"./Grammar":6,"./NameAddrHeader":9,"./UA":20,"./URI":21,"./Utils":22,"debug":29,"rtcninja":34}],8:[function(require,module,exports){
module.exports = Message;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var Utils = require('./Utils');
var RequestSender = require('./RequestSender');
var Transactions = require('./Transactions');
var Exceptions = require('./Exceptions');
function Message(ua) {
this.ua = ua;
// Custom message empty object for high level use
this.data = {};
events.EventEmitter.call(this);
}
util.inherits(Message, events.EventEmitter);
Message.prototype.send = function(target, body, options) {
var request_sender, event, contentType, eventHandlers, extraHeaders,
originalTarget = target;
if (target === undefined || body === undefined) {
throw new TypeError('Not enough arguments');
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
// Get call options
options = options || {};
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
eventHandlers = options.eventHandlers || {};
contentType = options.contentType || 'text/plain';
this.content_type = contentType;
// Set event handlers
for (event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
this.closed = false;
this.ua.applicants[this] = this;
extraHeaders.push('Content-Type: '+ contentType);
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.MESSAGE, target, this.ua, null, extraHeaders);
if(body) {
this.request.body = body;
this.content = body;
} else {
this.content = null;
}
request_sender = new RequestSender(this, this.ua);
this.newMessage('local', this.request);
request_sender.send();
};
Message.prototype.receiveResponse = function(response) {
var cause;
if(this.closed) {
return;
}
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
delete this.ua.applicants[this];
this.emit('succeeded', {
originator: 'remote',
response: response
});
break;
default:
delete this.ua.applicants[this];
cause = Utils.sipErrorCause(response.status_code);
this.emit('failed', {
originator: 'remote',
response: response,
cause: cause
});
break;
}
};
Message.prototype.onRequestTimeout = function() {
if(this.closed) {
return;
}
this.emit('failed', {
originator: 'system',
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
};
Message.prototype.onTransportError = function() {
if(this.closed) {
return;
}
this.emit('failed', {
originator: 'system',
cause: JsSIP_C.causes.CONNECTION_ERROR
});
};
Message.prototype.close = function() {
this.closed = true;
delete this.ua.applicants[this];
};
Message.prototype.init_incoming = function(request) {
var transaction;
this.request = request;
this.content_type = request.getHeader('Content-Type');
if (request.body) {
this.content = request.body;
} else {
this.content = null;
}
this.newMessage('remote', request);
transaction = this.ua.transactions.nist[request.via_branch];
if (transaction && (transaction.state === Transactions.C.STATUS_TRYING || transaction.state === Transactions.C.STATUS_PROCEEDING)) {
request.reply(200);
}
};
/**
* Accept the incoming Message
* Only valid for incoming Messages
*/
Message.prototype.accept = function(options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body;
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"accept" not supported for outgoing Message');
}
this.request.reply(200, null, extraHeaders, body);
};
/**
* Reject the incoming Message
* Only valid for incoming Messages
*/
Message.prototype.reject = function(options) {
options = options || {};
var
status_code = options.status_code || 480,
reason_phrase = options.reason_phrase,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body;
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"reject" not supported for outgoing Message');
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
this.request.reply(status_code, reason_phrase, extraHeaders, body);
};
/**
* Internal Callbacks
*/
Message.prototype.newMessage = function(originator, request) {
if (originator === 'remote') {
this.direction = 'incoming';
this.local_identity = request.to;
this.remote_identity = request.from;
} else if (originator === 'local'){
this.direction = 'outgoing';
this.local_identity = request.from;
this.remote_identity = request.to;
}
this.ua.newMessage({
originator: originator,
message: this,
request: request
});
};
},{"./Constants":1,"./Exceptions":5,"./RequestSender":15,"./SIPMessage":16,"./Transactions":18,"./Utils":22,"events":24,"util":28}],9:[function(require,module,exports){
module.exports = NameAddrHeader;
/**
* Dependencies.
*/
var URI = require('./URI');
var Grammar = require('./Grammar');
function NameAddrHeader(uri, display_name, parameters) {
var param;
// Checks
if(!uri || !(uri instanceof URI)) {
throw new TypeError('missing or invalid "uri" parameter');
}
// Initialize parameters
this.uri = uri;
this.parameters = {};
for (param in parameters) {
this.setParam(param, parameters[param]);
}
Object.defineProperties(this, {
display_name: {
get: function() { return display_name; },
set: function(value) {
display_name = (value === 0) ? '0' : value;
}
}
});
}
NameAddrHeader.prototype = {
setParam: function(key, value) {
if (key) {
this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString();
}
},
getParam: function(key) {
if(key) {
return this.parameters[key.toLowerCase()];
}
},
hasParam: function(key) {
if(key) {
return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false;
}
},
deleteParam: function(parameter) {
var value;
parameter = parameter.toLowerCase();
if (this.parameters.hasOwnProperty(parameter)) {
value = this.parameters[parameter];
delete this.parameters[parameter];
return value;
}
},
clearParams: function() {
this.parameters = {};
},
clone: function() {
return new NameAddrHeader(
this.uri.clone(),
this.display_name,
JSON.parse(JSON.stringify(this.parameters)));
},
toString: function() {
var body, parameter;
body = (this.display_name || this.display_name === 0) ? '"' + this.display_name + '" ' : '';
body += '<' + this.uri.toString() + '>';
for (parameter in this.parameters) {
body += ';' + parameter;
if (this.parameters[parameter] !== null) {
body += '='+ this.parameters[parameter];
}
}
return body;
}
};
/**
* Parse the given string and returns a NameAddrHeader instance or undefined if
* it is an invalid NameAddrHeader.
*/
NameAddrHeader.parse = function(name_addr_header) {
name_addr_header = Grammar.parse(name_addr_header,'Name_Addr_Header');
if (name_addr_header !== -1) {
return name_addr_header;
} else {
return undefined;
}
};
},{"./Grammar":6,"./URI":21}],10:[function(require,module,exports){
var Parser = {};
module.exports = Parser;
/**
* Dependencies.
*/
var debugerror = require('debug')('JsSIP:ERROR:Parser');
debugerror.log = console.warn.bind(console);
var sdp_transform = require('sdp-transform');
var Grammar = require('./Grammar');
var SIPMessage = require('./SIPMessage');
/**
* Extract and parse every header of a SIP message.
*/
function getHeader(data, headerStart) {
var
// 'start' position of the header.
start = headerStart,
// 'end' position of the header.
end = 0,
// 'partial end' position of the header.
partialEnd = 0;
//End of message.
if (data.substring(start, start + 2).match(/(^\r\n)/)) {
return -2;
}
while(end === 0) {
// Partial End of Header.
partialEnd = data.indexOf('\r\n', start);
// 'indexOf' returns -1 if the value to be found never occurs.
if (partialEnd === -1) {
return partialEnd;
}
if(!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/)) {
// Not the end of the message. Continue from the next position.
start = partialEnd + 2;
} else {
end = partialEnd;
}
}
return end;
}
function parseHeader(message, data, headerStart, headerEnd) {
var header, idx, length, parsed,
hcolonIndex = data.indexOf(':', headerStart),
headerName = data.substring(headerStart, hcolonIndex).trim(),
headerValue = data.substring(hcolonIndex + 1, headerEnd).trim();
// If header-field is well-known, parse it.
switch(headerName.toLowerCase()) {
case 'via':
case 'v':
message.addHeader('via', headerValue);
if(message.getHeaders('via').length === 1) {
parsed = message.parseHeader('Via');
if(parsed) {
message.via = parsed;
message.via_branch = parsed.branch;
}
} else {
parsed = 0;
}
break;
case 'from':
case 'f':
message.setHeader('from', headerValue);
parsed = message.parseHeader('from');
if(parsed) {
message.from = parsed;
message.from_tag = parsed.getParam('tag');
}
break;
case 'to':
case 't':
message.setHeader('to', headerValue);
parsed = message.parseHeader('to');
if(parsed) {
message.to = parsed;
message.to_tag = parsed.getParam('tag');
}
break;
case 'record-route':
parsed = Grammar.parse(headerValue, 'Record_Route');
if (parsed === -1) {
parsed = undefined;
}
length = parsed.length;
for (idx = 0; idx < length; idx++) {
header = parsed[idx];
message.addHeader('record-route', headerValue.substring(header.possition, header.offset));
message.headers['Record-Route'][message.getHeaders('record-route').length - 1].parsed = header.parsed;
}
break;
case 'call-id':
case 'i':
message.setHeader('call-id', headerValue);
parsed = message.parseHeader('call-id');
if(parsed) {
message.call_id = headerValue;
}
break;
case 'contact':
case 'm':
parsed = Grammar.parse(headerValue, 'Contact');
if (parsed === -1) {
parsed = undefined;
}
length = parsed.length;
for (idx = 0; idx < length; idx++) {
header = parsed[idx];
message.addHeader('contact', headerValue.substring(header.possition, header.offset));
message.headers.Contact[message.getHeaders('contact').length - 1].parsed = header.parsed;
}
break;
case 'content-length':
case 'l':
message.setHeader('content-length', headerValue);
parsed = message.parseHeader('content-length');
break;
case 'content-type':
case 'c':
message.setHeader('content-type', headerValue);
parsed = message.parseHeader('content-type');
break;
case 'cseq':
message.setHeader('cseq', headerValue);
parsed = message.parseHeader('cseq');
if(parsed) {
message.cseq = parsed.value;
}
if(message instanceof SIPMessage.IncomingResponse) {
message.method = parsed.method;
}
break;
case 'max-forwards':
message.setHeader('max-forwards', headerValue);
parsed = message.parseHeader('max-forwards');
break;
case 'www-authenticate':
message.setHeader('www-authenticate', headerValue);
parsed = message.parseHeader('www-authenticate');
break;
case 'proxy-authenticate':
message.setHeader('proxy-authenticate', headerValue);
parsed = message.parseHeader('proxy-authenticate');
break;
case 'session-expires':
case 'x':
message.setHeader('session-expires', headerValue);
parsed = message.parseHeader('session-expires');
if (parsed) {
message.session_expires = parsed.expires;
message.session_expires_refresher = parsed.refresher;
}
break;
default:
// Do not parse this header.
message.setHeader(headerName, headerValue);
parsed = 0;
}
if (parsed === undefined) {
return {
error: 'error parsing header "'+ headerName +'"'
};
} else {
return true;
}
}
/**
* Parse SIP Message
*/
Parser.parseMessage = function(data, ua) {
var message, firstLine, contentLength, bodyStart, parsed,
headerStart = 0,
headerEnd = data.indexOf('\r\n');
if(headerEnd === -1) {
debugerror('parseMessage() | no CRLF found, not a SIP message');
return;
}
// Parse first line. Check if it is a Request or a Reply.
firstLine = data.substring(0, headerEnd);
parsed = Grammar.parse(firstLine, 'Request_Response');
if(parsed === -1) {
debugerror('parseMessage() | error parsing first line of SIP message: "' + firstLine + '"');
return;
} else if(!parsed.status_code) {
message = new SIPMessage.IncomingRequest(ua);
message.method = parsed.method;
message.ruri = parsed.uri;
} else {
message = new SIPMessage.IncomingResponse();
message.status_code = parsed.status_code;
message.reason_phrase = parsed.reason_phrase;
}
message.data = data;
headerStart = headerEnd + 2;
/* Loop over every line in data. Detect the end of each header and parse
* it or simply add to the headers collection.
*/
while(true) {
headerEnd = getHeader(data, headerStart);
// The SIP message has normally finished.
if(headerEnd === -2) {
bodyStart = headerStart + 2;
break;
}
// data.indexOf returned -1 due to a malformed message.
else if(headerEnd === -1) {
parsed.error('parseMessage() | malformed message');
return;
}
parsed = parseHeader(message, data, headerStart, headerEnd);
if(parsed !== true) {
debugerror('parseMessage() |', parsed.error);
return;
}
headerStart = headerEnd + 2;
}
/* RFC3261 18.3.
* If there are additional bytes in the transport packet
* beyond the end of the body, they MUST be discarded.
*/
if(message.hasHeader('content-length')) {
contentLength = message.getHeader('content-length');
message.body = data.substr(bodyStart, contentLength);
} else {
message.body = data.substring(bodyStart);
}
return message;
};
/**
* sdp-transform features.
*/
Parser.parseSDP = sdp_transform.parse;
Parser.writeSDP = sdp_transform.write;
Parser.parseFmtpConfig = sdp_transform.parseFmtpConfig;
Parser.parsePayloads = sdp_transform.parsePayloads;
Parser.parseRemoteCandidates = sdp_transform.parseRemoteCandidates;
},{"./Grammar":6,"./SIPMessage":16,"debug":29,"sdp-transform":40}],11:[function(require,module,exports){
module.exports = RTCSession;
var C = {
// RTCSession states
STATUS_NULL: 0,
STATUS_INVITE_SENT: 1,
STATUS_1XX_RECEIVED: 2,
STATUS_INVITE_RECEIVED: 3,
STATUS_WAITING_FOR_ANSWER: 4,
STATUS_ANSWERED: 5,
STATUS_WAITING_FOR_ACK: 6,
STATUS_CANCELED: 7,
STATUS_TERMINATED: 8,
STATUS_CONFIRMED: 9
};
/**
* Expose C object.
*/
RTCSession.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession');
debugerror.log = console.warn.bind(console);
var rtcninja = require('rtcninja');
var JsSIP_C = require('./Constants');
var Exceptions = require('./Exceptions');
var Transactions = require('./Transactions');
var Parser = require('./Parser');
var Utils = require('./Utils');
var Timers = require('./Timers');
var SIPMessage = require('./SIPMessage');
var Dialog = require('./Dialog');
var RequestSender = require('./RequestSender');
var RTCSession_Request = require('./RTCSession/Request');
var RTCSession_DTMF = require('./RTCSession/DTMF');
function RTCSession(ua) {
debug('new');
this.ua = ua;
this.status = C.STATUS_NULL;
this.dialog = null;
this.earlyDialogs = {};
this.connection = null; // The rtcninja.RTCPeerConnection instance (public attribute).
// RTCSession confirmation flag
this.is_confirmed = false;
// is late SDP being negotiated
this.late_sdp = false;
// Default rtcOfferConstraints and rtcAnswerConstrainsts (passed in connect() or answer()).
this.rtcOfferConstraints = null;
this.rtcAnswerConstraints = null;
// Local MediaStream.
this.localMediaStream = null;
this.localMediaStreamLocallyGenerated = false;
// Flag to indicate PeerConnection ready for new actions.
this.rtcReady = true;
// SIP Timers
this.timers = {
ackTimer: null,
expiresTimer: null,
invite2xxTimer: null,
userNoAnswerTimer: null
};
// Session info
this.direction = null;
this.local_identity = null;
this.remote_identity = null;
this.start_time = null;
this.end_time = null;
this.tones = null;
// Mute/Hold state
this.audioMuted = false;
this.videoMuted = false;
this.localHold = false;
this.remoteHold = false;
// Session Timers (RFC 4028)
this.sessionTimers = {
enabled: this.ua.configuration.session_timers,
defaultExpires: JsSIP_C.SESSION_EXPIRES,
currentExpires: null,
running: false,
refresher: false,
timer: null // A setTimeout.
};
// Custom session empty object for high level use
this.data = {};
events.EventEmitter.call(this);
}
util.inherits(RTCSession, events.EventEmitter);
/**
* User API
*/
RTCSession.prototype.isInProgress = function() {
switch(this.status) {
case C.STATUS_NULL:
case C.STATUS_INVITE_SENT:
case C.STATUS_1XX_RECEIVED:
case C.STATUS_INVITE_RECEIVED:
case C.STATUS_WAITING_FOR_ANSWER:
return true;
default:
return false;
}
};
RTCSession.prototype.isEstablished = function() {
switch(this.status) {
case C.STATUS_ANSWERED:
case C.STATUS_WAITING_FOR_ACK:
case C.STATUS_CONFIRMED:
return true;
default:
return false;
}
};
RTCSession.prototype.isEnded = function() {
switch(this.status) {
case C.STATUS_CANCELED:
case C.STATUS_TERMINATED:
return true;
default:
return false;
}
};
RTCSession.prototype.isMuted = function() {
return {
audio: this.audioMuted,
video: this.videoMuted
};
};
RTCSession.prototype.isOnHold = function() {
return {
local: this.localHold,
remote: this.remoteHold
};
};
/**
* Check if RTCSession is ready for an outgoing re-INVITE or UPDATE with SDP.
*/
RTCSession.prototype.isReadyToReOffer = function() {
if (! this.rtcReady) {
debug('isReadyToReOffer() | internal WebRTC status not ready');
return false;
}
// No established yet.
if (! this.dialog) {
debug('isReadyToReOffer() | session not established yet');
return false;
}
// Another INVITE transaction is in progress
if (this.dialog.uac_pending_reply === true || this.dialog.uas_pending_reply === true) {
debug('isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress');
return false;
}
return true;
};
RTCSession.prototype.connect = function(target, options) {
debug('connect()');
options = options || {};
var event, requestParams,
originalTarget = target,
eventHandlers = options.eventHandlers || {},
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
mediaConstraints = options.mediaConstraints || {audio: true, video: true},
mediaStream = options.mediaStream || null,
pcConfig = options.pcConfig || {iceServers:[]},
rtcConstraints = options.rtcConstraints || null,
rtcOfferConstraints = options.rtcOfferConstraints || null;
this.rtcOfferConstraints = rtcOfferConstraints;
this.rtcAnswerConstraints = options.rtcAnswerConstraints || null;
// Session Timers.
if (this.sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.defaultExpires = options.sessionTimersExpires;
}
else {
this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
this.data = options.data || this.data;
if (target === undefined) {
throw new TypeError('Not enough arguments');
}
// Check WebRTC support.
if (! rtcninja.hasWebRTC()) {
throw new Exceptions.NotSupportedError('WebRTC not supported');
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
// Check Session Status
if (this.status !== C.STATUS_NULL) {
throw new Exceptions.InvalidStateError(this.status);
}
// Set event handlers
for (event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
// Session parameter initialization
this.from_tag = Utils.newTag();
// Set anonymous property
this.anonymous = options.anonymous || false;
// OutgoingSession specific parameters
this.isCanceled = false;
requestParams = {from_tag: this.from_tag};
this.contact = this.ua.contact.toString({
anonymous: this.anonymous,
outbound: true
});
if (this.anonymous) {
requestParams.from_display_name = 'Anonymous';
requestParams.from_uri = 'sip:[email protected]';
extraHeaders.push('P-Preferred-Identity: '+ this.ua.configuration.uri.toString());
extraHeaders.push('Privacy: id');
}
extraHeaders.push('Contact: '+ this.contact);
extraHeaders.push('Content-Type: application/sdp');
if (this.sessionTimers.enabled) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.defaultExpires);
}
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.INVITE, target, this.ua, requestParams, extraHeaders);
this.id = this.request.call_id + this.from_tag;
// Create a new rtcninja.RTCPeerConnection instance.
createRTCConnection.call(this, pcConfig, rtcConstraints);
// Save the session into the ua sessions collection.
this.ua.sessions[this.id] = this;
newRTCSession.call(this, 'local', this.request);
sendInitialRequest.call(this, mediaConstraints, rtcOfferConstraints, mediaStream);
};
RTCSession.prototype.init_incoming = function(request) {
debug('init_incoming()');
var expires,
self = this,
contentType = request.getHeader('Content-Type');
// Check body and content type
if (request.body && (contentType !== 'application/sdp')) {
request.reply(415);
return;
}
// Session parameter initialization
this.status = C.STATUS_INVITE_RECEIVED;
this.from_tag = request.from_tag;
this.id = request.call_id + this.from_tag;
this.request = request;
this.contact = this.ua.contact.toString();
// Save the session into the ua sessions collection.
this.ua.sessions[this.id] = this;
// Get the Expires header value if exists
if (request.hasHeader('expires')) {
expires = request.getHeader('expires') * 1000;
}
/* Set the to_tag before
* replying a response code that will create a dialog.
*/
request.to_tag = Utils.newTag();
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, request, 'UAS', true)) {
request.reply(500, 'Missing Contact header field');
return;
}
if (request.body) {
this.late_sdp = false;
}
else {
this.late_sdp = true;
}
this.status = C.STATUS_WAITING_FOR_ANSWER;
// Set userNoAnswerTimer
this.timers.userNoAnswerTimer = setTimeout(function() {
request.reply(408);
failed.call(self, 'local',null, JsSIP_C.causes.NO_ANSWER);
}, this.ua.configuration.no_answer_timeout
);
/* Set expiresTimer
* RFC3261 13.3.1
*/
if (expires) {
this.timers.expiresTimer = setTimeout(function() {
if(self.status === C.STATUS_WAITING_FOR_ANSWER) {
request.reply(487);
failed.call(self, 'system', null, JsSIP_C.causes.EXPIRES);
}
}, expires
);
}
// Fire 'newRTCSession' event.
newRTCSession.call(this, 'remote', request);
// The user may have rejected the call in the 'newRTCSession' event.
if (this.status === C.STATUS_TERMINATED) {
return;
}
// Reply 180.
request.reply(180, null, ['Contact: ' + self.contact]);
// Fire 'progress' event.
// TODO: Document that 'response' field in 'progress' event is null for
// incoming calls.
progress.call(self, 'local', null);
};
/**
* Answer the call.
*/
RTCSession.prototype.answer = function(options) {
debug('answer()');
options = options || {};
var idx, length, sdp, tracks,
peerHasAudioLine = false,
peerHasVideoLine = false,
peerOffersFullAudio = false,
peerOffersFullVideo = false,
self = this,
request = this.request,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
mediaConstraints = options.mediaConstraints || {},
mediaStream = options.mediaStream || null,
pcConfig = options.pcConfig || {iceServers:[]},
rtcConstraints = options.rtcConstraints || null,
rtcAnswerConstraints = options.rtcAnswerConstraints || null;
this.rtcAnswerConstraints = rtcAnswerConstraints;
this.rtcOfferConstraints = options.rtcOfferConstraints || null;
// Session Timers.
if (this.sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.defaultExpires = options.sessionTimersExpires;
}
else {
this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
this.data = options.data || this.data;
// Check Session Direction and Status
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"answer" not supported for outgoing RTCSession');
} else if (this.status !== C.STATUS_WAITING_FOR_ANSWER) {
throw new Exceptions.InvalidStateError(this.status);
}
this.status = C.STATUS_ANSWERED;
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, request, 'UAS')) {
request.reply(500, 'Error creating dialog');
return;
}
clearTimeout(this.timers.userNoAnswerTimer);
extraHeaders.unshift('Contact: ' + self.contact);
// Determine incoming media from incoming SDP offer (if any).
sdp = Parser.parseSDP(request.body || '');
// Make sure sdp.media is an array, not the case if there is only one media
if (! Array.isArray(sdp.media)) {
sdp.media = [sdp.media];
}
// Go through all medias in SDP to find offered capabilities to answer with
idx = sdp.media.length;
while(idx--) {
var m = sdp.media[idx];
if (m.type === 'audio') {
peerHasAudioLine = true;
if (!m.direction || m.direction === 'sendrecv') {
peerOffersFullAudio = true;
}
}
if (m.type === 'video') {
peerHasVideoLine = true;
if (!m.direction || m.direction === 'sendrecv') {
peerOffersFullVideo = true;
}
}
}
// Remove audio from mediaStream if suggested by mediaConstraints
if (mediaStream && mediaConstraints.audio === false) {
tracks = mediaStream.getAudioTracks();
length = tracks.length;
for (idx=0; idx<length; idx++) {
mediaStream.removeTrack(tracks[idx]);
}
}
// Remove video from mediaStream if suggested by mediaConstraints
if (mediaStream && mediaConstraints.video === false) {
tracks = mediaStream.getVideoTracks();
length = tracks.length;
for (idx=0; idx<length; idx++) {
mediaStream.removeTrack(tracks[idx]);
}
}
// Set audio constraints based on incoming stream if not supplied
if (!mediaStream && mediaConstraints.audio === undefined) {
mediaConstraints.audio = peerOffersFullAudio;
}
// Set video constraints based on incoming stream if not supplied
if (!mediaStream && mediaConstraints.video === undefined) {
mediaConstraints.video = peerOffersFullVideo;
}
// Don't ask for audio if the incoming offer has no audio section
if (!mediaStream && !peerHasAudioLine) {
mediaConstraints.audio = false;
}
// Don't ask for video if the incoming offer has no video section
if (!mediaStream && !peerHasVideoLine) {
mediaConstraints.video = false;
}
// Create a new rtcninja.RTCPeerConnection instance.
// TODO: This may throw an error, should react.
createRTCConnection.call(this, pcConfig, rtcConstraints);
if (mediaStream) {
userMediaSucceeded(mediaStream);
} else {
self.localMediaStreamLocallyGenerated = true;
rtcninja.getUserMedia(
mediaConstraints,
userMediaSucceeded,
userMediaFailed
);
}
// User media succeeded
function userMediaSucceeded(stream) {
if (self.status === C.STATUS_TERMINATED) { return; }
self.localMediaStream = stream;
self.connection.addStream(stream);
if (! self.late_sdp) {
self.connection.setRemoteDescription(
new rtcninja.RTCSessionDescription({type:'offer', sdp:request.body}),
// success
remoteDescriptionSucceededOrNotNeeded,
// failure
function() {
request.reply(488);
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
}
);
}
else {
remoteDescriptionSucceededOrNotNeeded();
}
}
// User media failed
function userMediaFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
request.reply(480);
failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS);
}
function remoteDescriptionSucceededOrNotNeeded() {
connecting.call(self, request);
if (! self.late_sdp) {
createLocalDescription.call(self, 'answer', rtcSucceeded, rtcFailed, rtcAnswerConstraints);
} else {
createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, self.rtcOfferConstraints);
}
}
function rtcSucceeded(sdp) {
if (self.status === C.STATUS_TERMINATED) { return; }
// run for reply success callback
function replySucceeded() {
self.status = C.STATUS_WAITING_FOR_ACK;
setInvite2xxTimer.call(self, request, sdp);
setACKTimer.call(self);
accepted.call(self, 'local');
}
// run for reply failure callback
function replyFailed() {
failed.call(self, 'system', null, JsSIP_C.causes.CONNECTION_ERROR);
}
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
request.reply(200, null, extraHeaders,
sdp,
replySucceeded,
replyFailed
);
}
function rtcFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
request.reply(500);
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
}
};
/**
* Terminate the call.
*/
RTCSession.prototype.terminate = function(options) {
debug('terminate()');
options = options || {};
var cancel_reason, dialog,
cause = options.cause || JsSIP_C.causes.BYE,
status_code = options.status_code,
reason_phrase = options.reason_phrase,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body,
self = this;
// Check Session Status
if (this.status === C.STATUS_TERMINATED) {
throw new Exceptions.InvalidStateError(this.status);
}
switch(this.status) {
// - UAC -
case C.STATUS_NULL:
case C.STATUS_INVITE_SENT:
case C.STATUS_1XX_RECEIVED:
debug('canceling sesssion');
if (status_code && (status_code < 200 || status_code >= 700)) {
throw new TypeError('Invalid status_code: '+ status_code);
} else if (status_code) {
reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
cancel_reason = 'SIP ;cause=' + status_code + ' ;text="' + reason_phrase + '"';
}
// Check Session Status
if (this.status === C.STATUS_NULL) {
this.isCanceled = true;
this.cancelReason = cancel_reason;
} else if (this.status === C.STATUS_INVITE_SENT) {
this.isCanceled = true;
this.cancelReason = cancel_reason;
} else if(this.status === C.STATUS_1XX_RECEIVED) {
this.request.cancel(cancel_reason);
}
this.status = C.STATUS_CANCELED;
failed.call(this, 'local', null, JsSIP_C.causes.CANCELED);
break;
// - UAS -
case C.STATUS_WAITING_FOR_ANSWER:
case C.STATUS_ANSWERED:
debug('rejecting session');
status_code = status_code || 480;
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
this.request.reply(status_code, reason_phrase, extraHeaders, body);
failed.call(this, 'local', null, JsSIP_C.causes.REJECTED);
break;
case C.STATUS_WAITING_FOR_ACK:
case C.STATUS_CONFIRMED:
debug('terminating session');
reason_phrase = options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
if (status_code && (status_code < 200 || status_code >= 700)) {
throw new TypeError('Invalid status_code: '+ status_code);
} else if (status_code) {
extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"');
}
/* RFC 3261 section 15 (Terminating a session):
*
* "...the callee's UA MUST NOT send a BYE on a confirmed dialog
* until it has received an ACK for its 2xx response or until the server
* transaction times out."
*/
if (this.status === C.STATUS_WAITING_FOR_ACK &&
this.direction === 'incoming' &&
this.request.server_transaction.state !== Transactions.C.STATUS_TERMINATED) {
// Save the dialog for later restoration
dialog = this.dialog;
// Send the BYE as soon as the ACK is received...
this.receiveRequest = function(request) {
if(request.method === JsSIP_C.ACK) {
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
dialog.terminate();
}
};
// .., or when the INVITE transaction times out
this.request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_TERMINATED) {
sendRequest.call(self, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
dialog.terminate();
}
});
ended.call(this, 'local', null, cause);
// Restore the dialog into 'this' in order to be able to send the in-dialog BYE :-)
this.dialog = dialog;
// Restore the dialog into 'ua' so the ACK can reach 'this' session
this.ua.dialogs[dialog.id.toString()] = dialog;
} else {
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
ended.call(this, 'local', null, cause);
}
}
};
RTCSession.prototype.close = function() {
debug('close()');
var idx;
if (this.status === C.STATUS_TERMINATED) {
return;
}
// Terminate RTC.
if (this.connection) {
try {
this.connection.close();
}
catch(error) {
debugerror('close() | error closing the RTCPeerConnection: %o', error);
}
}
// Close local MediaStream if it was not given by the user.
if (this.localMediaStream && this.localMediaStreamLocallyGenerated) {
debug('close() | closing local MediaStream');
rtcninja.closeMediaStream(this.localMediaStream);
}
// Terminate signaling.
// Clear SIP timers
for(idx in this.timers) {
clearTimeout(this.timers[idx]);
}
// Clear Session Timers.
clearTimeout(this.sessionTimers.timer);
// Terminate confirmed dialog
if (this.dialog) {
this.dialog.terminate();
delete this.dialog;
}
// Terminate early dialogs
for(idx in this.earlyDialogs) {
this.earlyDialogs[idx].terminate();
delete this.earlyDialogs[idx];
}
this.status = C.STATUS_TERMINATED;
delete this.ua.sessions[this.id];
};
RTCSession.prototype.sendDTMF = function(tones, options) {
debug('sendDTMF() | tones: %s', tones);
var duration, interToneGap,
position = 0,
self = this;
options = options || {};
duration = options.duration || null;
interToneGap = options.interToneGap || null;
if (tones === undefined) {
throw new TypeError('Not enough arguments');
}
// Check Session Status
if (this.status !== C.STATUS_CONFIRMED && this.status !== C.STATUS_WAITING_FOR_ACK) {
throw new Exceptions.InvalidStateError(this.status);
}
// Convert to string
if(typeof tones === 'number') {
tones = tones.toString();
}
// Check tones
if (!tones || typeof tones !== 'string' || !tones.match(/^[0-9A-D#*,]+$/i)) {
throw new TypeError('Invalid tones: '+ tones);
}
// Check duration
if (duration && !Utils.isDecimal(duration)) {
throw new TypeError('Invalid tone duration: '+ duration);
} else if (!duration) {
duration = RTCSession_DTMF.C.DEFAULT_DURATION;
} else if (duration < RTCSession_DTMF.C.MIN_DURATION) {
debug('"duration" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_DURATION+ ' milliseconds');
duration = RTCSession_DTMF.C.MIN_DURATION;
} else if (duration > RTCSession_DTMF.C.MAX_DURATION) {
debug('"duration" value is greater than the maximum allowed, setting it to '+ RTCSession_DTMF.C.MAX_DURATION +' milliseconds');
duration = RTCSession_DTMF.C.MAX_DURATION;
} else {
duration = Math.abs(duration);
}
options.duration = duration;
// Check interToneGap
if (interToneGap && !Utils.isDecimal(interToneGap)) {
throw new TypeError('Invalid interToneGap: '+ interToneGap);
} else if (!interToneGap) {
interToneGap = RTCSession_DTMF.C.DEFAULT_INTER_TONE_GAP;
} else if (interToneGap < RTCSession_DTMF.C.MIN_INTER_TONE_GAP) {
debug('"interToneGap" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_INTER_TONE_GAP +' milliseconds');
interToneGap = RTCSession_DTMF.C.MIN_INTER_TONE_GAP;
} else {
interToneGap = Math.abs(interToneGap);
}
if (this.tones) {
// Tones are already queued, just add to the queue
this.tones += tones;
return;
}
this.tones = tones;
// Send the first tone
_sendDTMF();
function _sendDTMF() {
var tone, timeout;
if (self.status === C.STATUS_TERMINATED || !self.tones || position >= self.tones.length) {
// Stop sending DTMF
self.tones = null;
return;
}
tone = self.tones[position];
position += 1;
if (tone === ',') {
timeout = 2000;
} else {
var dtmf = new RTCSession_DTMF(self);
options.eventHandlers = {
failed: function() { self.tones = null; }
};
dtmf.send(tone, options);
timeout = duration + interToneGap;
}
// Set timeout for the next tone
setTimeout(_sendDTMF, timeout);
}
};
/**
* Mute
*/
RTCSession.prototype.mute = function(options) {
debug('mute()');
options = options || {audio:true, video:false};
var
audioMuted = false,
videoMuted = false;
if (this.audioMuted === false && options.audio) {
audioMuted = true;
this.audioMuted = true;
toogleMuteAudio.call(this, true);
}
if (this.videoMuted === false && options.video) {
videoMuted = true;
this.videoMuted = true;
toogleMuteVideo.call(this, true);
}
if (audioMuted === true || videoMuted === true) {
onmute.call(this, {
audio: audioMuted,
video: videoMuted
});
}
};
/**
* Unmute
*/
RTCSession.prototype.unmute = function(options) {
debug('unmute()');
options = options || {audio:true, video:true};
var
audioUnMuted = false,
videoUnMuted = false;
if (this.audioMuted === true && options.audio) {
audioUnMuted = true;
this.audioMuted = false;
if (this.localHold === false) {
toogleMuteAudio.call(this, false);
}
}
if (this.videoMuted === true && options.video) {
videoUnMuted = true;
this.videoMuted = false;
if (this.localHold === false) {
toogleMuteVideo.call(this, false);
}
}
if (audioUnMuted === true || videoUnMuted === true) {
onunmute.call(this, {
audio: audioUnMuted,
video: videoUnMuted
});
}
};
/**
* Hold
*/
RTCSession.prototype.hold = function(options, done) {
debug('hold()');
options = options || {};
var self = this,
eventHandlers;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (this.localHold === true) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
this.localHold = true;
onhold.call(this, 'local');
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Hold Failed'
});
}
};
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
}
return true;
};
RTCSession.prototype.unhold = function(options, done) {
debug('unhold()');
options = options || {};
var self = this,
eventHandlers;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (this.localHold === false) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
this.localHold = false;
onunhold.call(this, 'local');
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Unhold Failed'
});
}
};
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
}
return true;
};
RTCSession.prototype.renegotiate = function(options, done) {
debug('renegotiate()');
options = options || {};
var self = this,
eventHandlers,
rtcOfferConstraints = options.rtcOfferConstraints || null;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Media Renegotiation Failed'
});
}
};
setLocalMediaStatus.call(this);
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
rtcOfferConstraints: rtcOfferConstraints,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
rtcOfferConstraints: rtcOfferConstraints,
extraHeaders: options.extraHeaders
});
}
return true;
};
/**
* In dialog Request Reception
*/
RTCSession.prototype.receiveRequest = function(request) {
debug('receiveRequest()');
var contentType,
self = this;
if(request.method === JsSIP_C.CANCEL) {
/* RFC3261 15 States that a UAS may have accepted an invitation while a CANCEL
* was in progress and that the UAC MAY continue with the session established by
* any 2xx response, or MAY terminate with BYE. JsSIP does continue with the
* established session. So the CANCEL is processed only if the session is not yet
* established.
*/
/*
* Terminate the whole session in case the user didn't accept (or yet send the answer)
* nor reject the request opening the session.
*/
if(this.status === C.STATUS_WAITING_FOR_ANSWER || this.status === C.STATUS_ANSWERED) {
this.status = C.STATUS_CANCELED;
this.request.reply(487);
failed.call(this, 'remote', request, JsSIP_C.causes.CANCELED);
}
} else {
// Requests arriving here are in-dialog requests.
switch(request.method) {
case JsSIP_C.ACK:
if(this.status === C.STATUS_WAITING_FOR_ACK) {
clearTimeout(this.timers.ackTimer);
clearTimeout(this.timers.invite2xxTimer);
if (this.late_sdp) {
if (!request.body) {
ended.call(this, 'remote', request, JsSIP_C.causes.MISSING_SDP);
break;
}
this.connection.setRemoteDescription(
new rtcninja.RTCSessionDescription({type:'answer', sdp:request.body}),
// success
function() {
self.status = C.STATUS_CONFIRMED;
},
// failure
function() {
ended.call(self, 'remote', request, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION);
}
);
}
else {
this.status = C.STATUS_CONFIRMED;
}
if (this.status === C.STATUS_CONFIRMED && !this.is_confirmed) {
confirmed.call(this, 'remote', request);
}
}
break;
case JsSIP_C.BYE:
if(this.status === C.STATUS_CONFIRMED) {
request.reply(200);
ended.call(this, 'remote', request, JsSIP_C.causes.BYE);
}
else if (this.status === C.STATUS_INVITE_RECEIVED) {
request.reply(200);
this.request.reply(487, 'BYE Received');
ended.call(this, 'remote', request, JsSIP_C.causes.BYE);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.INVITE:
if(this.status === C.STATUS_CONFIRMED) {
receiveReinvite.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.INFO:
if(this.status === C.STATUS_CONFIRMED || this.status === C.STATUS_WAITING_FOR_ACK || this.status === C.STATUS_INVITE_RECEIVED) {
contentType = request.getHeader('content-type');
if (contentType && (contentType.match(/^application\/dtmf-relay/i))) {
new RTCSession_DTMF(this).init_incoming(request);
}
else {
request.reply(415);
}
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.UPDATE:
if(this.status === C.STATUS_CONFIRMED) {
receiveUpdate.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
default:
request.reply(501);
}
}
};
/**
* Session Callbacks
*/
RTCSession.prototype.onTransportError = function() {
debugerror('onTransportError()');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.CONNECTION_ERROR,
cause: JsSIP_C.causes.CONNECTION_ERROR
});
}
};
RTCSession.prototype.onRequestTimeout = function() {
debug('onRequestTimeout');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 408,
reason_phrase: JsSIP_C.causes.REQUEST_TIMEOUT,
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
}
};
RTCSession.prototype.onDialogError = function() {
debugerror('onDialogError()');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.DIALOG_ERROR,
cause: JsSIP_C.causes.DIALOG_ERROR
});
}
};
// Called from DTMF handler.
RTCSession.prototype.newDTMF = function(data) {
debug('newDTMF()');
this.emit('newDTMF', data);
};
/**
* Private API.
*/
/**
* RFC3261 13.3.1.4
* Response retransmissions cannot be accomplished by transaction layer
* since it is destroyed when receiving the first 2xx answer
*/
function setInvite2xxTimer(request, body) {
var
self = this,
timeout = Timers.T1;
this.timers.invite2xxTimer = setTimeout(function invite2xxRetransmission() {
if (self.status !== C.STATUS_WAITING_FOR_ACK) {
return;
}
request.reply(200, null, ['Contact: '+ self.contact], body);
if (timeout < Timers.T2) {
timeout = timeout * 2;
if (timeout > Timers.T2) {
timeout = Timers.T2;
}
}
self.timers.invite2xxTimer = setTimeout(
invite2xxRetransmission, timeout
);
}, timeout);
}
/**
* RFC3261 14.2
* If a UAS generates a 2xx response and never receives an ACK,
* it SHOULD generate a BYE to terminate the dialog.
*/
function setACKTimer() {
var self = this;
this.timers.ackTimer = setTimeout(function() {
if(self.status === C.STATUS_WAITING_FOR_ACK) {
debug('no ACK received, terminating the session');
clearTimeout(self.timers.invite2xxTimer);
sendRequest.call(self, JsSIP_C.BYE);
ended.call(self, 'remote', null, JsSIP_C.causes.NO_ACK);
}
}, Timers.TIMER_H);
}
function createRTCConnection(pcConfig, rtcConstraints) {
var self = this;
this.connection = new rtcninja.RTCPeerConnection(pcConfig, rtcConstraints);
this.connection.onaddstream = function(event, stream) {
self.emit('addstream', {stream: stream});
};
this.connection.onremovestream = function(event, stream) {
self.emit('removestream', {stream: stream});
};
this.connection.oniceconnectionstatechange = function(event, state) {
self.emit('iceconnetionstatechange', {state: state});
// TODO: Do more with different states.
if (state === 'failed') {
self.terminate({
cause: JsSIP_C.causes.RTP_TIMEOUT,
status_code: 200,
reason_phrase: JsSIP_C.causes.RTP_TIMEOUT
});
}
};
}
function createLocalDescription(type, onSuccess, onFailure, constraints) {
debug('createLocalDescription()');
var self = this;
var connection = this.connection;
this.rtcReady = false;
if (type === 'offer') {
connection.createOffer(
// success
createSucceeded,
// failure
function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
},
// constraints
constraints
);
}
else if (type === 'answer') {
connection.createAnswer(
// success
createSucceeded,
// failure
function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
},
// constraints
constraints
);
}
else {
throw new Error('createLocalDescription() | type must be "offer" or "answer", but "' +type+ '" was given');
}
// createAnswer or createOffer succeeded
function createSucceeded(desc) {
connection.onicecandidate = function(event, candidate) {
if (! candidate) {
connection.onicecandidate = null;
self.rtcReady = true;
if (onSuccess) { onSuccess(connection.localDescription.sdp); }
onSuccess = null;
}
};
connection.setLocalDescription(desc,
// success
function() {
if (connection.iceGatheringState === 'complete') {
self.rtcReady = true;
if (onSuccess) { onSuccess(connection.localDescription.sdp); }
onSuccess = null;
}
},
// failure
function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
}
);
}
}
/**
* Dialog Management
*/
function createDialog(message, type, early) {
var dialog, early_dialog,
local_tag = (type === 'UAS') ? message.to_tag : message.from_tag,
remote_tag = (type === 'UAS') ? message.from_tag : message.to_tag,
id = message.call_id + local_tag + remote_tag;
early_dialog = this.earlyDialogs[id];
// Early Dialog
if (early) {
if (early_dialog) {
return true;
} else {
early_dialog = new Dialog(this, message, type, Dialog.C.STATUS_EARLY);
// Dialog has been successfully created.
if(early_dialog.error) {
debug(early_dialog.error);
failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
} else {
this.earlyDialogs[id] = early_dialog;
return true;
}
}
}
// Confirmed Dialog
else {
// In case the dialog is in _early_ state, update it
if (early_dialog) {
early_dialog.update(message, type);
this.dialog = early_dialog;
delete this.earlyDialogs[id];
return true;
}
// Otherwise, create a _confirmed_ dialog
dialog = new Dialog(this, message, type);
if(dialog.error) {
debug(dialog.error);
failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
} else {
this.dialog = dialog;
return true;
}
}
}
/**
* In dialog INVITE Reception
*/
function receiveReinvite(request) {
debug('receiveReinvite()');
var
sdp, idx, direction,
self = this,
contentType = request.getHeader('Content-Type'),
hold = false;
// Emit 'reinvite'.
this.emit('reinvite', {request: request});
if (request.body) {
this.late_sdp = false;
if (contentType !== 'application/sdp') {
debug('invalid Content-Type');
request.reply(415);
return;
}
sdp = Parser.parseSDP(request.body);
for (idx=0; idx < sdp.media.length; idx++) {
direction = sdp.media[idx].direction || sdp.direction || 'sendrecv';
if (direction === 'sendonly' || direction === 'inactive') {
hold = true;
}
// If at least one of the streams is active don't emit 'hold'.
else {
hold = false;
break;
}
}
this.connection.setRemoteDescription(
new rtcninja.RTCSessionDescription({type:'offer', sdp:request.body}),
// success
answer,
// failure
function() {
request.reply(488);
}
);
}
else {
this.late_sdp = true;
answer();
}
function answer() {
createSdp(
// onSuccess
function(sdp) {
var extraHeaders = ['Contact: ' + self.contact];
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
if (self.late_sdp) {
sdp = mangleOffer.call(self, sdp);
}
request.reply(200, null, extraHeaders, sdp,
function() {
self.status = C.STATUS_WAITING_FOR_ACK;
setInvite2xxTimer.call(self, request, sdp);
setACKTimer.call(self);
}
);
},
// onFailure
function() {
request.reply(500);
}
);
}
function createSdp(onSuccess, onFailure) {
if (! self.late_sdp) {
if (self.remoteHold === true && hold === false) {
self.remoteHold = false;
onunhold.call(self, 'remote');
} else if (self.remoteHold === false && hold === true) {
self.remoteHold = true;
onhold.call(self, 'remote');
}
createLocalDescription.call(self, 'answer', onSuccess, onFailure, self.rtcAnswerConstraints);
} else {
createLocalDescription.call(self, 'offer', onSuccess, onFailure, self.rtcOfferConstraints);
}
}
}
/**
* In dialog UPDATE Reception
*/
function receiveUpdate(request) {
debug('receiveUpdate()');
var
sdp, idx, direction,
self = this,
contentType = request.getHeader('Content-Type'),
hold = false;
// Emit 'update'.
this.emit('update', {request: request});
if (! request.body) {
var extraHeaders = [];
handleSessionTimersInIncomingRequest.call(this, request, extraHeaders);
request.reply(200, null, extraHeaders);
return;
}
if (contentType !== 'application/sdp') {
debug('invalid Content-Type');
request.reply(415);
return;
}
sdp = Parser.parseSDP(request.body);
for (idx=0; idx < sdp.media.length; idx++) {
direction = sdp.media[idx].direction || sdp.direction || 'sendrecv';
if (direction === 'sendonly' || direction === 'inactive') {
hold = true;
}
// If at least one of the streams is active don't emit 'hold'.
else {
hold = false;
break;
}
}
this.connection.setRemoteDescription(
new rtcninja.RTCSessionDescription({type:'offer', sdp:request.body}),
// success
function() {
if (self.remoteHold === true && hold === false) {
self.remoteHold = false;
onunhold.call(self, 'remote');
} else if (self.remoteHold === false && hold === true) {
self.remoteHold = true;
onhold.call(self, 'remote');
}
createLocalDescription.call(self, 'answer',
// success
function(sdp) {
var extraHeaders = ['Contact: ' + self.contact];
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
request.reply(200, null, extraHeaders, sdp);
},
// failure
function() {
request.reply(500);
}
);
},
// failure
function() {
request.reply(488);
},
// Constraints.
this.rtcAnswerConstraints
);
}
/**
* Initial Request Sender
*/
function sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) {
var self = this;
var request_sender = new RequestSender(self, this.ua);
this.receiveResponse = function(response) {
receiveInviteResponse.call(self, response);
};
// If a local MediaStream is given use it.
if (mediaStream) {
userMediaSucceeded(mediaStream);
// If at least audio or video is requested prompt getUserMedia.
} else if (mediaConstraints.audio || mediaConstraints.video) {
this.localMediaStreamLocallyGenerated = true;
rtcninja.getUserMedia(
mediaConstraints,
userMediaSucceeded,
userMediaFailed
);
}
// Otherwise don't prompt getUserMedia.
else {
userMediaSucceeded(null);
}
// User media succeeded
function userMediaSucceeded(stream) {
if (self.status === C.STATUS_TERMINATED) { return; }
self.localMediaStream = stream;
if (stream) {
self.connection.addStream(stream);
}
connecting.call(self, self.request);
createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, rtcOfferConstraints);
}
// User media failed
function userMediaFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS);
}
function rtcSucceeded(sdp) {
if (self.isCanceled || self.status === C.STATUS_TERMINATED) { return; }
self.request.body = sdp;
self.status = C.STATUS_INVITE_SENT;
request_sender.send();
}
function rtcFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
}
}
/**
* Reception of Response for Initial INVITE
*/
function receiveInviteResponse(response) {
debug('receiveInviteResponse()');
var cause, dialog,
self = this;
// Handle 2XX retransmissions and responses from forked requests
if (this.dialog && (response.status_code >=200 && response.status_code <=299)) {
/*
* If it is a retransmission from the endpoint that established
* the dialog, send an ACK
*/
if (this.dialog.id.call_id === response.call_id &&
this.dialog.id.local_tag === response.from_tag &&
this.dialog.id.remote_tag === response.to_tag) {
sendRequest.call(this, JsSIP_C.ACK);
return;
}
// If not, send an ACK and terminate
else {
dialog = new Dialog(this, response, 'UAC');
if (dialog.error !== undefined) {
debug(dialog.error);
return;
}
dialog.sendRequest({
owner: {status: C.STATUS_TERMINATED},
onRequestTimeout: function(){},
onTransportError: function(){},
onDialogError: function(){},
receiveResponse: function(){}
}, JsSIP_C.ACK);
dialog.sendRequest({
owner: {status: C.STATUS_TERMINATED},
onRequestTimeout: function(){},
onTransportError: function(){},
onDialogError: function(){},
receiveResponse: function(){}
}, JsSIP_C.BYE);
return;
}
}
// Proceed to cancellation if the user requested.
if(this.isCanceled) {
// Remove the flag. We are done.
this.isCanceled = false;
if(response.status_code >= 100 && response.status_code < 200) {
this.request.cancel(this.cancelReason);
} else if(response.status_code >= 200 && response.status_code < 299) {
acceptAndTerminate.call(this, response);
}
return;
}
if(this.status !== C.STATUS_INVITE_SENT && this.status !== C.STATUS_1XX_RECEIVED) {
return;
}
switch(true) {
case /^100$/.test(response.status_code):
this.status = C.STATUS_1XX_RECEIVED;
break;
case /^1[0-9]{2}$/.test(response.status_code):
// Do nothing with 1xx responses without To tag.
if (!response.to_tag) {
debug('1xx response received without to tag');
break;
}
// Create Early Dialog if 1XX comes with contact
if (response.hasHeader('contact')) {
// An error on dialog creation will fire 'failed' event
if(! createDialog.call(this, response, 'UAC', true)) {
break;
}
}
this.status = C.STATUS_1XX_RECEIVED;
progress.call(this, 'remote', response);
if (!response.body) {
break;
}
this.connection.setRemoteDescription(
new rtcninja.RTCSessionDescription({type:'pranswer', sdp:response.body}),
// success
null,
// failure
null
);
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.status = C.STATUS_CONFIRMED;
if(!response.body) {
acceptAndTerminate.call(this, response, 400, JsSIP_C.causes.MISSING_SDP);
failed.call(this, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION);
break;
}
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, response, 'UAC')) {
break;
}
this.connection.setRemoteDescription(
new rtcninja.RTCSessionDescription({type:'answer', sdp:response.body}),
// success
function() {
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
accepted.call(self, 'remote', response);
sendRequest.call(self, JsSIP_C.ACK);
confirmed.call(self, 'local', null);
},
// failure
function() {
acceptAndTerminate.call(self, response, 488, 'Not Acceptable Here');
failed.call(self, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION);
}
);
break;
default:
cause = Utils.sipErrorCause(response.status_code);
failed.call(this, 'remote', response, cause);
}
}
/**
* Send Re-INVITE
*/
function sendReinvite(options) {
debug('sendReinvite()');
options = options || {};
var
self = this,
extraHeaders = options.extraHeaders || [],
eventHandlers = options.eventHandlers || {},
rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null,
succeeded = false;
extraHeaders.push('Contact: ' + this.contact);
extraHeaders.push('Content-Type: application/sdp');
// Session Timers.
if (this.sessionTimers.running) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas'));
}
createLocalDescription.call(this, 'offer',
// success
function(sdp) {
sdp = mangleOffer.call(self, sdp);
var request = new RTCSession_Request(self, JsSIP_C.INVITE);
request.send({
extraHeaders: extraHeaders,
body: sdp,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
succeeded = true;
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
},
// failure
function() {
onFailed();
},
// RTC constraints.
rtcOfferConstraints
);
function onSucceeded(response) {
if (self.status === C.STATUS_TERMINATED) {
return;
}
sendRequest.call(self, JsSIP_C.ACK);
// If it is a 2XX retransmission exit now.
if (succeeded) { return; }
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
// Must have SDP answer.
if(! response.body) {
onFailed();
return;
} else if (response.getHeader('Content-Type') !== 'application/sdp') {
onFailed();
return;
}
self.connection.setRemoteDescription(
new rtcninja.RTCSessionDescription({type:'answer', sdp:response.body}),
// success
function() {
if (eventHandlers.succeeded) { eventHandlers.succeeded(response); }
},
// failure
function() {
onFailed();
}
);
}
function onFailed(response) {
if (eventHandlers.failed) { eventHandlers.failed(response); }
}
}
/**
* Send UPDATE
*/
function sendUpdate(options) {
debug('sendUpdate()');
options = options || {};
var
self = this,
extraHeaders = options.extraHeaders || [],
eventHandlers = options.eventHandlers || {},
rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null,
sdpOffer = options.sdpOffer || false,
succeeded = false;
extraHeaders.push('Contact: ' + this.contact);
// Session Timers.
if (this.sessionTimers.running) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas'));
}
if (sdpOffer) {
extraHeaders.push('Content-Type: application/sdp');
createLocalDescription.call(this, 'offer',
// success
function(sdp) {
sdp = mangleOffer.call(self, sdp);
var request = new RTCSession_Request(self, JsSIP_C.UPDATE);
request.send({
extraHeaders: extraHeaders,
body: sdp,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
succeeded = true;
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
},
// failure
function() {
onFailed();
},
// RTC constraints.
rtcOfferConstraints
);
}
// No SDP.
else {
var request = new RTCSession_Request(self, JsSIP_C.UPDATE);
request.send({
extraHeaders: extraHeaders,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
}
function onSucceeded(response) {
if (self.status === C.STATUS_TERMINATED) {
return;
}
// If it is a 2XX retransmission exit now.
if (succeeded) { return; }
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
// Must have SDP answer.
if (sdpOffer) {
if(! response.body) {
onFailed();
return;
} else if (response.getHeader('Content-Type') !== 'application/sdp') {
onFailed();
return;
}
self.connection.setRemoteDescription(
new rtcninja.RTCSessionDescription({type:'answer', sdp:response.body}),
// success
function() {
if (eventHandlers.succeeded) { eventHandlers.succeeded(response); }
},
// failure
function() {
onFailed();
}
);
}
// No SDP answer.
else {
if (eventHandlers.succeeded) { eventHandlers.succeeded(response); }
}
}
function onFailed(response) {
if (eventHandlers.failed) { eventHandlers.failed(response); }
}
}
function acceptAndTerminate(response, status_code, reason_phrase) {
debug('acceptAndTerminate()');
var extraHeaders = [];
if (status_code) {
reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"');
}
// An error on dialog creation will fire 'failed' event
if (this.dialog || createDialog.call(this, response, 'UAC')) {
sendRequest.call(this, JsSIP_C.ACK);
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders
});
}
// Update session status.
this.status = C.STATUS_TERMINATED;
}
/**
* Send a generic in-dialog Request
*/
function sendRequest(method, options) {
debug('sendRequest()');
var request = new RTCSession_Request(this, method);
request.send(options);
}
/**
* Correctly set the SDP direction attributes if the call is on local hold
*/
function mangleOffer(sdp) {
var idx, length, m;
if (! this.localHold && ! this.remoteHold) {
return sdp;
}
sdp = Parser.parseSDP(sdp);
// Local hold.
if (this.localHold && ! this.remoteHold) {
debug('mangleOffer() | me on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (!m.direction) {
m.direction = 'sendonly';
} else if (m.direction === 'sendrecv') {
m.direction = 'sendonly';
} else if (m.direction === 'recvonly') {
m.direction = 'inactive';
}
}
}
// Local and remote hold.
else if (this.localHold && this.remoteHold) {
debug('mangleOffer() | both on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
m.direction = 'inactive';
}
}
// Remote hold.
else if (this.remoteHold) {
debug('mangleOffer() | remote on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (!m.direction) {
m.direction = 'recvonly';
} else if (m.direction === 'sendrecv') {
m.direction = 'recvonly';
} else if (m.direction === 'recvonly') {
m.direction = 'inactive';
}
}
}
return Parser.writeSDP(sdp);
}
function setLocalMediaStatus() {
if (this.localHold) {
debug('setLocalMediaStatus() | me on hold, mutting my media');
toogleMuteAudio.call(this, true);
toogleMuteVideo.call(this, true);
return;
}
else if (this.remoteHold) {
debug('setLocalMediaStatus() | remote on hold, mutting my media');
toogleMuteAudio.call(this, true);
toogleMuteVideo.call(this, true);
return;
}
if (this.audioMuted) {
toogleMuteAudio.call(this, true);
} else {
toogleMuteAudio.call(this, false);
}
if (this.videoMuted) {
toogleMuteVideo.call(this, true);
} else {
toogleMuteVideo.call(this, false);
}
}
/**
* Handle SessionTimers for an incoming INVITE or UPDATE.
* @param {IncomingRequest} request
* @param {Array} responseExtraHeaders Extra headers for the 200 response.
*/
function handleSessionTimersInIncomingRequest(request, responseExtraHeaders) {
if (! this.sessionTimers.enabled) { return; }
var session_expires_refresher;
if (request.session_expires && request.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.currentExpires = request.session_expires;
session_expires_refresher = request.session_expires_refresher || 'uas';
}
else {
this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires;
session_expires_refresher = 'uas';
}
responseExtraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + session_expires_refresher);
this.sessionTimers.refresher = (session_expires_refresher === 'uas');
runSessionTimer.call(this);
}
/**
* Handle SessionTimers for an incoming response to INVITE or UPDATE.
* @param {IncomingResponse} response
*/
function handleSessionTimersInIncomingResponse(response) {
if (! this.sessionTimers.enabled) { return; }
var session_expires_refresher;
if (response.session_expires && response.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.currentExpires = response.session_expires;
session_expires_refresher = response.session_expires_refresher || 'uac';
}
else {
this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires;
session_expires_refresher = 'uac';
}
this.sessionTimers.refresher = (session_expires_refresher === 'uac');
runSessionTimer.call(this);
}
function runSessionTimer() {
var self = this;
var expires = this.sessionTimers.currentExpires;
this.sessionTimers.running = true;
clearTimeout(this.sessionTimers.timer);
// I'm the refresher.
if (this.sessionTimers.refresher) {
this.sessionTimers.timer = setTimeout(function() {
if (self.status === C.STATUS_TERMINATED) { return; }
debug('runSessionTimer() | sending session refresh request');
sendUpdate.call(self, {
eventHandlers: {
succeeded: function(response) {
handleSessionTimersInIncomingResponse.call(self, response);
}
}
});
}, expires * 500); // Half the given interval (as the RFC states).
}
// I'm not the refresher.
else {
this.sessionTimers.timer = setTimeout(function() {
if (self.status === C.STATUS_TERMINATED) { return; }
debugerror('runSessionTimer() | timer expired, terminating the session');
self.terminate({
cause: JsSIP_C.causes.REQUEST_TIMEOUT,
status_code: 408,
reason_phrase: 'Session Timer Expired'
});
}, expires * 1100);
}
}
function toogleMuteAudio(mute) {
var streamIdx, trackIdx, streamsLength, tracksLength, tracks,
localStreams = this.connection.getLocalStreams();
streamsLength = localStreams.length;
for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) {
tracks = localStreams[streamIdx].getAudioTracks();
tracksLength = tracks.length;
for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) {
tracks[trackIdx].enabled = !mute;
}
}
}
function toogleMuteVideo(mute) {
var streamIdx, trackIdx, streamsLength, tracksLength, tracks,
localStreams = this.connection.getLocalStreams();
streamsLength = localStreams.length;
for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) {
tracks = localStreams[streamIdx].getVideoTracks();
tracksLength = tracks.length;
for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) {
tracks[trackIdx].enabled = !mute;
}
}
}
function newRTCSession(originator, request) {
debug('newRTCSession');
if (originator === 'remote') {
this.direction = 'incoming';
this.local_identity = request.to;
this.remote_identity = request.from;
} else if (originator === 'local'){
this.direction = 'outgoing';
this.local_identity = request.from;
this.remote_identity = request.to;
}
this.ua.newRTCSession({
originator: originator,
session: this,
request: request
});
}
function connecting(request) {
debug('session connecting');
this.emit('connecting', {
request: request
});
}
function progress(originator, response) {
debug('session progress');
this.emit('progress', {
originator: originator,
response: response || null
});
}
function accepted(originator, message) {
debug('session accepted');
this.start_time = new Date();
this.emit('accepted', {
originator: originator,
response: message || null
});
}
function confirmed(originator, ack) {
debug('session confirmed');
this.is_confirmed = true;
this.emit('confirmed', {
originator: originator,
ack: ack || null
});
}
function ended(originator, message, cause) {
debug('session ended');
this.end_time = new Date();
this.close();
this.emit('ended', {
originator: originator,
message: message || null,
cause: cause
});
}
function failed(originator, message, cause) {
debug('session failed');
this.close();
this.emit('failed', {
originator: originator,
message: message || null,
cause: cause
});
}
function onhold(originator) {
debug('session onhold');
setLocalMediaStatus.call(this);
this.emit('hold', {
originator: originator
});
}
function onunhold(originator) {
debug('session onunhold');
setLocalMediaStatus.call(this);
this.emit('unhold', {
originator: originator
});
}
function onmute(options) {
debug('session onmute');
setLocalMediaStatus.call(this);
this.emit('muted', {
audio: options.audio,
video: options.video
});
}
function onunmute(options) {
debug('session onunmute');
setLocalMediaStatus.call(this);
this.emit('unmuted', {
audio: options.audio,
video: options.video
});
}
},{"./Constants":1,"./Dialog":2,"./Exceptions":5,"./Parser":10,"./RTCSession/DTMF":12,"./RTCSession/Request":13,"./RequestSender":15,"./SIPMessage":16,"./Timers":17,"./Transactions":18,"./Utils":22,"debug":29,"events":24,"rtcninja":34,"util":28}],12:[function(require,module,exports){
module.exports = DTMF;
var C = {
MIN_DURATION: 70,
MAX_DURATION: 6000,
DEFAULT_DURATION: 100,
MIN_INTER_TONE_GAP: 50,
DEFAULT_INTER_TONE_GAP: 500
};
/**
* Expose C object.
*/
DTMF.C = C;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RTCSession:DTMF');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession:DTMF');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('../Constants');
var Exceptions = require('../Exceptions');
var RTCSession = require('../RTCSession');
function DTMF(session) {
this.owner = session;
this.direction = null;
this.tone = null;
this.duration = null;
}
DTMF.prototype.send = function(tone, options) {
var extraHeaders, body;
if (tone === undefined) {
throw new TypeError('Not enough arguments');
}
this.direction = 'outgoing';
// Check RTCSession Status
if (this.owner.status !== RTCSession.C.STATUS_CONFIRMED &&
this.owner.status !== RTCSession.C.STATUS_WAITING_FOR_ACK) {
throw new Exceptions.InvalidStateError(this.owner.status);
}
// Get DTMF options
options = options || {};
extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : [];
this.eventHandlers = options.eventHandlers || {};
// Check tone type
if (typeof tone === 'string' ) {
tone = tone.toUpperCase();
} else if (typeof tone === 'number') {
tone = tone.toString();
} else {
throw new TypeError('Invalid tone: '+ tone);
}
// Check tone value
if (!tone.match(/^[0-9A-D#*]$/)) {
throw new TypeError('Invalid tone: '+ tone);
} else {
this.tone = tone;
}
// Duration is checked/corrected in RTCSession
this.duration = options.duration;
extraHeaders.push('Content-Type: application/dtmf-relay');
body = 'Signal=' + this.tone + '\r\n';
body += 'Duration=' + this.duration;
this.owner.newDTMF({
originator: 'local',
dtmf: this,
request: this.request
});
this.owner.dialog.sendRequest(this, JsSIP_C.INFO, {
extraHeaders: extraHeaders,
body: body
});
};
DTMF.prototype.receiveResponse = function(response) {
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
debug('onSuccessResponse');
if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); }
break;
default:
if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); }
break;
}
};
DTMF.prototype.onRequestTimeout = function() {
debugerror('onRequestTimeout');
if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); }
};
DTMF.prototype.onTransportError = function() {
debugerror('onTransportError');
if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); }
};
DTMF.prototype.onDialogError = function() {
debugerror('onDialogError');
if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); }
};
DTMF.prototype.init_incoming = function(request) {
var body,
reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,
reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;
this.direction = 'incoming';
this.request = request;
request.reply(200);
if (request.body) {
body = request.body.split('\n');
if (body.length >= 1) {
if (reg_tone.test(body[0])) {
this.tone = body[0].replace(reg_tone,'$2');
}
}
if (body.length >=2) {
if (reg_duration.test(body[1])) {
this.duration = parseInt(body[1].replace(reg_duration,'$2'), 10);
}
}
}
if (!this.duration) {
this.duration = C.DEFAULT_DURATION;
}
if (!this.tone) {
debug('invalid INFO DTMF received, discarded');
} else {
this.owner.newDTMF({
originator: 'remote',
dtmf: this,
request: request
});
}
};
},{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":29}],13:[function(require,module,exports){
module.exports = Request;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RTCSession:Request');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession:Request');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('../Constants');
var Exceptions = require('../Exceptions');
var RTCSession = require('../RTCSession');
function Request(session, method) {
debug('new | %s', method);
this.session = session;
this.method = method;
// Check RTCSession Status
if (this.session.status !== RTCSession.C.STATUS_1XX_RECEIVED &&
this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ANSWER &&
this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ACK &&
this.session.status !== RTCSession.C.STATUS_CONFIRMED &&
this.session.status !== RTCSession.C.STATUS_TERMINATED) {
throw new Exceptions.InvalidStateError(this.session.status);
}
/*
* Allow sending BYE in TERMINATED status since the RTCSession
* could had been terminated before the ACK had arrived.
* RFC3261 Section 15, Paragraph 2
*/
else if (this.session.status === RTCSession.C.STATUS_TERMINATED && method !== JsSIP_C.BYE) {
throw new Exceptions.InvalidStateError(this.session.status);
}
}
Request.prototype.send = function(options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body || null;
this.eventHandlers = options.eventHandlers || {};
this.session.dialog.sendRequest(this, this.method, {
extraHeaders: extraHeaders,
body: body
});
};
Request.prototype.receiveResponse = function(response) {
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
debug('onProgressResponse');
if (this.eventHandlers.onProgressResponse) { this.eventHandlers.onProgressResponse(response); }
break;
case /^2[0-9]{2}$/.test(response.status_code):
debug('onSuccessResponse');
if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); }
break;
default:
debug('onErrorResponse');
if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); }
break;
}
};
Request.prototype.onRequestTimeout = function() {
debugerror('onRequestTimeout');
if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); }
};
Request.prototype.onTransportError = function() {
debugerror('onTransportError');
if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); }
};
Request.prototype.onDialogError = function() {
debugerror('onDialogError');
if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); }
};
},{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":29}],14:[function(require,module,exports){
module.exports = Registrator;
/**
* Dependecies
*/
var debug = require('debug')('JsSIP:Registrator');
var Utils = require('./Utils');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var RequestSender = require('./RequestSender');
function Registrator(ua, transport) {
var reg_id=1; //Force reg_id to 1.
this.ua = ua;
this.transport = transport;
this.registrar = ua.configuration.registrar_server;
this.expires = ua.configuration.register_expires;
// Call-ID and CSeq values RFC3261 10.2
this.call_id = Utils.createRandomToken(22);
this.cseq = 0;
// this.to_uri
this.to_uri = ua.configuration.uri;
this.registrationTimer = null;
// Set status
this.registered = false;
// Contact header
this.contact = this.ua.contact.toString();
// sip.ice media feature tag (RFC 5768)
this.contact += ';+sip.ice';
// Custom headers for REGISTER and un-REGISTER.
this.extraHeaders = [];
// Custom Contact header params for REGISTER and un-REGISTER.
this.extraContactParams = '';
if(reg_id) {
this.contact += ';reg-id='+ reg_id;
this.contact += ';+sip.instance="<urn:uuid:'+ this.ua.configuration.instance_id+'>"';
}
}
Registrator.prototype = {
setExtraHeaders: function(extraHeaders) {
if (! Array.isArray(extraHeaders)) {
extraHeaders = [];
}
this.extraHeaders = extraHeaders.slice();
},
setExtraContactParams: function(extraContactParams) {
if (! (extraContactParams instanceof Object)) {
extraContactParams = {};
}
// Reset it.
this.extraContactParams = '';
for(var param_key in extraContactParams) {
var param_value = extraContactParams[param_key];
this.extraContactParams += (';' + param_key);
if (param_value) {
this.extraContactParams += ('=' + param_value);
}
}
},
register: function() {
var request_sender, cause, extraHeaders,
self = this;
extraHeaders = this.extraHeaders.slice();
extraHeaders.push('Contact: ' + this.contact + ';expires=' + this.expires + this.extraContactParams);
extraHeaders.push('Expires: '+ this.expires);
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
request_sender = new RequestSender(this, this.ua);
this.receiveResponse = function(response) {
var contact, expires,
contacts = response.getHeaders('contact').length;
// Discard responses to older REGISTER/un-REGISTER requests.
if(response.cseq !== this.cseq) {
return;
}
// Clear registration timer
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
if(response.hasHeader('expires')) {
expires = response.getHeader('expires');
}
// Search the Contact pointing to us and update the expires value accordingly.
if (!contacts) {
debug('no Contact header in response to REGISTER, response ignored');
break;
}
while(contacts--) {
contact = response.parseHeader('contact', contacts);
if(contact.uri.user === this.ua.contact.uri.user) {
expires = contact.getParam('expires');
break;
} else {
contact = null;
}
}
if (!contact) {
debug('no Contact header pointing to us, response ignored');
break;
}
if(!expires) {
expires = this.expires;
}
// Re-Register before the expiration interval has elapsed.
// For that, decrease the expires value. ie: 3 seconds
this.registrationTimer = setTimeout(function() {
self.registrationTimer = null;
self.register();
}, (expires * 1000) - 3000);
//Save gruu values
if (contact.hasParam('temp-gruu')) {
this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,'');
}
if (contact.hasParam('pub-gruu')) {
this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,'');
}
if (! this.registered) {
this.registered = true;
this.ua.registered({
response: response
});
}
break;
// Interval too brief RFC3261 10.2.8
case /^423$/.test(response.status_code):
if(response.hasHeader('min-expires')) {
// Increase our registration interval to the suggested minimum
this.expires = response.getHeader('min-expires');
// Attempt the registration again immediately
this.register();
} else { //This response MUST contain a Min-Expires header field
debug('423 response received for REGISTER without Min-Expires');
this.registrationFailure(response, JsSIP_C.causes.SIP_FAILURE_CODE);
}
break;
default:
cause = Utils.sipErrorCause(response.status_code);
this.registrationFailure(response, cause);
}
};
this.onRequestTimeout = function() {
this.registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT);
};
this.onTransportError = function() {
this.registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR);
};
request_sender.send();
},
unregister: function(options) {
var extraHeaders;
if(!this.registered) {
debug('already unregistered');
return;
}
options = options || {};
this.registered = false;
// Clear the registration timer.
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
extraHeaders = this.extraHeaders.slice();
if(options.all) {
extraHeaders.push('Contact: *' + this.extraContactParams);
extraHeaders.push('Expires: 0');
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
} else {
extraHeaders.push('Contact: '+ this.contact + ';expires=0' + this.extraContactParams);
extraHeaders.push('Expires: 0');
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
}
var request_sender = new RequestSender(this, this.ua);
this.receiveResponse = function(response) {
var cause;
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.unregistered(response);
break;
default:
cause = Utils.sipErrorCause(response.status_code);
this.unregistered(response, cause);
}
};
this.onRequestTimeout = function() {
this.unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT);
};
this.onTransportError = function() {
this.unregistered(null, JsSIP_C.causes.CONNECTION_ERROR);
};
request_sender.send();
},
registrationFailure: function(response, cause) {
this.ua.registrationFailed({
response: response || null,
cause: cause
});
if (this.registered) {
this.registered = false;
this.ua.unregistered({
response: response || null,
cause: cause
});
}
},
unregistered: function(response, cause) {
this.registered = false;
this.ua.unregistered({
response: response || null,
cause: cause || null
});
},
onTransportClosed: function() {
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
if(this.registered) {
this.registered = false;
this.ua.unregistered({});
}
},
close: function() {
if (this.registered) {
this.unregister();
}
}
};
},{"./Constants":1,"./RequestSender":15,"./SIPMessage":16,"./Utils":22,"debug":29}],15:[function(require,module,exports){
module.exports = RequestSender;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RequestSender');
var JsSIP_C = require('./Constants');
var UA = require('./UA');
var DigestAuthentication = require('./DigestAuthentication');
var Transactions = require('./Transactions');
function RequestSender(applicant, ua) {
this.ua = ua;
this.applicant = applicant;
this.method = applicant.request.method;
this.request = applicant.request;
this.credentials = null;
this.challenged = false;
this.staled = false;
// If ua is in closing process or even closed just allow sending Bye and ACK
if (ua.status === UA.C.STATUS_USER_CLOSED && (this.method !== JsSIP_C.BYE || this.method !== JsSIP_C.ACK)) {
this.onTransportError();
}
}
/**
* Create the client transaction and send the message.
*/
RequestSender.prototype = {
send: function() {
switch(this.method) {
case 'INVITE':
this.clientTransaction = new Transactions.InviteClientTransaction(this, this.request, this.ua.transport);
break;
case 'ACK':
this.clientTransaction = new Transactions.AckClientTransaction(this, this.request, this.ua.transport);
break;
default:
this.clientTransaction = new Transactions.NonInviteClientTransaction(this, this.request, this.ua.transport);
}
this.clientTransaction.send();
},
/**
* Callback fired when receiving a request timeout error from the client transaction.
* To be re-defined by the applicant.
*/
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
/**
* Callback fired when receiving a transport error from the client transaction.
* To be re-defined by the applicant.
*/
onTransportError: function() {
this.applicant.onTransportError();
},
/**
* Called from client transaction when receiving a correct response to the request.
* Authenticate request if needed or pass the response back to the applicant.
*/
receiveResponse: function(response) {
var cseq, challenge, authorization_header_name,
status_code = response.status_code;
/*
* Authentication
* Authenticate once. _challenged_ flag used to avoid infinite authentications.
*/
if ((status_code === 401 || status_code === 407) && this.ua.configuration.password !== null) {
// Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header.
if (response.status_code === 401) {
challenge = response.parseHeader('www-authenticate');
authorization_header_name = 'authorization';
} else {
challenge = response.parseHeader('proxy-authenticate');
authorization_header_name = 'proxy-authorization';
}
// Verify it seems a valid challenge.
if (! challenge) {
debug(response.status_code + ' with wrong or missing challenge, cannot authenticate');
this.applicant.receiveResponse(response);
return;
}
if (!this.challenged || (!this.staled && challenge.stale === true)) {
if (!this.credentials) {
this.credentials = new DigestAuthentication(this.ua);
}
// Verify that the challenge is really valid.
if (!this.credentials.authenticate(this.request, challenge)) {
this.applicant.receiveResponse(response);
return;
}
this.challenged = true;
if (challenge.stale) {
this.staled = true;
}
if (response.method === JsSIP_C.REGISTER) {
cseq = this.applicant.cseq += 1;
} else if (this.request.dialog){
cseq = this.request.dialog.local_seqnum += 1;
} else {
cseq = this.request.cseq + 1;
this.request.cseq = cseq;
}
this.request.setHeader('cseq', cseq +' '+ this.method);
this.request.setHeader(authorization_header_name, this.credentials.toString());
this.send();
} else {
this.applicant.receiveResponse(response);
}
} else {
this.applicant.receiveResponse(response);
}
}
};
},{"./Constants":1,"./DigestAuthentication":4,"./Transactions":18,"./UA":20,"debug":29}],16:[function(require,module,exports){
module.exports = {
OutgoingRequest: OutgoingRequest,
IncomingRequest: IncomingRequest,
IncomingResponse: IncomingResponse
};
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:SIPMessage');
var JsSIP_C = require('./Constants');
var Utils = require('./Utils');
var NameAddrHeader = require('./NameAddrHeader');
var Grammar = require('./Grammar');
/**
* -param {String} method request method
* -param {String} ruri request uri
* -param {UA} ua
* -param {Object} params parameters that will have priority over ua.configuration parameters:
* <br>
* - cseq, call_id, from_tag, from_uri, from_display_name, to_uri, to_tag, route_set
* -param {Object} [headers] extra headers
* -param {String} [body]
*/
function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) {
var
to,
from,
call_id,
cseq;
params = params || {};
// Mandatory parameters check
if(!method || !ruri || !ua) {
return null;
}
this.ua = ua;
this.headers = {};
this.method = method;
this.ruri = ruri;
this.body = body;
this.extraHeaders = extraHeaders && extraHeaders.slice() || [];
// Fill the Common SIP Request Headers
// Route
if (params.route_set) {
this.setHeader('route', params.route_set);
} else if (ua.configuration.use_preloaded_route){
this.setHeader('route', ua.transport.server.sip_uri);
}
// Via
// Empty Via header. Will be filled by the client transaction.
this.setHeader('via', '');
// Max-Forwards
this.setHeader('max-forwards', JsSIP_C.MAX_FORWARDS);
// To
to = (params.to_display_name || params.to_display_name === 0) ? '"' + params.to_display_name + '" ' : '';
to += '<' + (params.to_uri || ruri) + '>';
to += params.to_tag ? ';tag=' + params.to_tag : '';
this.to = new NameAddrHeader.parse(to);
this.setHeader('to', to);
// From
if (params.from_display_name || params.from_display_name === 0) {
from = '"' + params.from_display_name + '" ';
} else if (ua.configuration.display_name) {
from = '"' + ua.configuration.display_name + '" ';
} else {
from = '';
}
from += '<' + (params.from_uri || ua.configuration.uri) + '>;tag=';
from += params.from_tag || Utils.newTag();
this.from = new NameAddrHeader.parse(from);
this.setHeader('from', from);
// Call-ID
call_id = params.call_id || (ua.configuration.jssip_id + Utils.createRandomToken(15));
this.call_id = call_id;
this.setHeader('call-id', call_id);
// CSeq
cseq = params.cseq || Math.floor(Math.random() * 10000);
this.cseq = cseq;
this.setHeader('cseq', cseq + ' ' + method);
}
OutgoingRequest.prototype = {
/**
* Replace the the given header by the given value.
* -param {String} name header name
* -param {String | Array} value header value
*/
setHeader: function(name, value) {
this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value];
},
/**
* Get the value of the given header name at the given position.
* -param {String} name header name
* -returns {String|undefined} Returns the specified header, null if header doesn't exist.
*/
getHeader: function(name) {
var regexp, idx,
length = this.extraHeaders.length,
header = this.headers[Utils.headerize(name)];
if(header) {
if(header[0]) {
return header[0];
}
} else {
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
header = this.extraHeaders[idx];
if (regexp.test(header)) {
return header.substring(header.indexOf(':')+1).trim();
}
}
}
return;
},
/**
* Get the header/s of the given name.
* -param {String} name header name
* -returns {Array} Array with all the headers of the specified name.
*/
getHeaders: function(name) {
var idx, length, regexp,
header = this.headers[Utils.headerize(name)],
result = [];
if (header) {
length = header.length;
for (idx = 0; idx < length; idx++) {
result.push(header[idx]);
}
return result;
} else {
length = this.extraHeaders.length;
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
header = this.extraHeaders[idx];
if (regexp.test(header)) {
result.push(header.substring(header.indexOf(':')+1).trim());
}
}
return result;
}
},
/**
* Verify the existence of the given header.
* -param {String} name header name
* -returns {boolean} true if header with given name exists, false otherwise
*/
hasHeader: function(name) {
var regexp, idx,
length = this.extraHeaders.length;
if (this.headers[Utils.headerize(name)]) {
return true;
} else {
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
if (regexp.test(this.extraHeaders[idx])) {
return true;
}
}
}
return false;
},
toString: function() {
var msg = '', header, length, idx,
supported = [];
msg += this.method + ' ' + this.ruri + ' SIP/2.0\r\n';
for (header in this.headers) {
length = this.headers[header].length;
for (idx = 0; idx < length; idx++) {
msg += header + ': ' + this.headers[header][idx] + '\r\n';
}
}
length = this.extraHeaders.length;
for (idx = 0; idx < length; idx++) {
msg += this.extraHeaders[idx].trim() +'\r\n';
}
// Supported
switch (this.method) {
case JsSIP_C.REGISTER:
supported.push('path', 'gruu');
break;
case JsSIP_C.INVITE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) {
supported.push('gruu');
}
supported.push('ice');
break;
case JsSIP_C.UPDATE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
supported.push('ice');
break;
}
supported.push('outbound');
// Allow
msg += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
msg += 'Supported: ' + supported +'\r\n';
msg += 'User-Agent: ' + JsSIP_C.USER_AGENT +'\r\n';
if (this.body) {
length = Utils.str_utf8_length(this.body);
msg += 'Content-Length: ' + length + '\r\n\r\n';
msg += this.body;
} else {
msg += 'Content-Length: 0\r\n\r\n';
}
return msg;
}
};
function IncomingMessage(){
this.data = null;
this.headers = null;
this.method = null;
this.via = null;
this.via_branch = null;
this.call_id = null;
this.cseq = null;
this.from = null;
this.from_tag = null;
this.to = null;
this.to_tag = null;
this.body = null;
}
IncomingMessage.prototype = {
/**
* Insert a header of the given name and value into the last position of the
* header array.
*/
addHeader: function(name, value) {
var header = { raw: value };
name = Utils.headerize(name);
if(this.headers[name]) {
this.headers[name].push(header);
} else {
this.headers[name] = [header];
}
},
/**
* Get the value of the given header name at the given position.
*/
getHeader: function(name) {
var header = this.headers[Utils.headerize(name)];
if(header) {
if(header[0]) {
return header[0].raw;
}
} else {
return;
}
},
/**
* Get the header/s of the given name.
*/
getHeaders: function(name) {
var idx, length,
header = this.headers[Utils.headerize(name)],
result = [];
if(!header) {
return [];
}
length = header.length;
for (idx = 0; idx < length; idx++) {
result.push(header[idx].raw);
}
return result;
},
/**
* Verify the existence of the given header.
*/
hasHeader: function(name) {
return(this.headers[Utils.headerize(name)]) ? true : false;
},
/**
* Parse the given header on the given index.
* -param {String} name header name
* -param {Number} [idx=0] header index
* -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error.
*/
parseHeader: function(name, idx) {
var header, value, parsed;
name = Utils.headerize(name);
idx = idx || 0;
if(!this.headers[name]) {
debug('header "' + name + '" not present');
return;
} else if(idx >= this.headers[name].length) {
debug('not so many "' + name + '" headers present');
return;
}
header = this.headers[name][idx];
value = header.raw;
if(header.parsed) {
return header.parsed;
}
//substitute '-' by '_' for grammar rule matching.
parsed = Grammar.parse(value, name.replace(/-/g, '_'));
if(parsed === -1) {
this.headers[name].splice(idx, 1); //delete from headers
debug('error parsing "' + name + '" header field with value "' + value + '"');
return;
} else {
header.parsed = parsed;
return parsed;
}
},
/**
* Message Header attribute selector. Alias of parseHeader.
* -param {String} name header name
* -param {Number} [idx=0] header index
* -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error.
*
* -example
* message.s('via',3).port
*/
s: function(name, idx) {
return this.parseHeader(name, idx);
},
/**
* Replace the value of the given header by the value.
* -param {String} name header name
* -param {String} value header value
*/
setHeader: function(name, value) {
var header = { raw: value };
this.headers[Utils.headerize(name)] = [header];
},
toString: function() {
return this.data;
}
};
function IncomingRequest(ua) {
this.ua = ua;
this.headers = {};
this.ruri = null;
this.transport = null;
this.server_transaction = null;
}
IncomingRequest.prototype = new IncomingMessage();
/**
* Stateful reply.
* -param {Number} code status code
* -param {String} reason reason phrase
* -param {Object} headers extra headers
* -param {String} body body
* -param {Function} [onSuccess] onSuccess callback
* -param {Function} [onFailure] onFailure callback
*/
IncomingRequest.prototype.reply = function(code, reason, extraHeaders, body, onSuccess, onFailure) {
var rr, vias, length, idx, response,
supported = [],
to = this.getHeader('To'),
r = 0,
v = 0;
code = code || null;
reason = reason || null;
// Validate code and reason values
if (!code || (code < 100 || code > 699)) {
throw new TypeError('Invalid status_code: '+ code);
} else if (reason && typeof reason !== 'string' && !(reason instanceof String)) {
throw new TypeError('Invalid reason_phrase: '+ reason);
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
extraHeaders = extraHeaders && extraHeaders.slice() || [];
response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n';
if(this.method === JsSIP_C.INVITE && code > 100 && code <= 200) {
rr = this.getHeaders('record-route');
length = rr.length;
for(r; r < length; r++) {
response += 'Record-Route: ' + rr[r] + '\r\n';
}
}
vias = this.getHeaders('via');
length = vias.length;
for(v; v < length; v++) {
response += 'Via: ' + vias[v] + '\r\n';
}
if(!this.to_tag && code > 100) {
to += ';tag=' + Utils.newTag();
} else if(this.to_tag && !this.s('to').hasParam('tag')) {
to += ';tag=' + this.to_tag;
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + this.getHeader('From') + '\r\n';
response += 'Call-ID: ' + this.call_id + '\r\n';
response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n';
length = extraHeaders.length;
for (idx = 0; idx < length; idx++) {
response += extraHeaders[idx].trim() +'\r\n';
}
// Supported
switch (this.method) {
case JsSIP_C.INVITE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) {
supported.push('gruu');
}
supported.push('ice');
break;
case JsSIP_C.UPDATE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (body) {
supported.push('ice');
}
}
supported.push('outbound');
// Allow and Accept
if (this.method === JsSIP_C.OPTIONS) {
response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n';
} else if (code === 405) {
response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
} else if (code === 415 ) {
response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n';
}
response += 'Supported: ' + supported +'\r\n';
if(body) {
length = Utils.str_utf8_length(body);
response += 'Content-Type: application/sdp\r\n';
response += 'Content-Length: ' + length + '\r\n\r\n';
response += body;
} else {
response += 'Content-Length: ' + 0 + '\r\n\r\n';
}
this.server_transaction.receiveResponse(code, response, onSuccess, onFailure);
};
/**
* Stateless reply.
* -param {Number} code status code
* -param {String} reason reason phrase
*/
IncomingRequest.prototype.reply_sl = function(code, reason) {
var to, response,
v = 0,
vias = this.getHeaders('via'),
length = vias.length;
code = code || null;
reason = reason || null;
// Validate code and reason values
if (!code || (code < 100 || code > 699)) {
throw new TypeError('Invalid status_code: '+ code);
} else if (reason && typeof reason !== 'string' && !(reason instanceof String)) {
throw new TypeError('Invalid reason_phrase: '+ reason);
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n';
for(v; v < length; v++) {
response += 'Via: ' + vias[v] + '\r\n';
}
to = this.getHeader('To');
if(!this.to_tag && code > 100) {
to += ';tag=' + Utils.newTag();
} else if(this.to_tag && !this.s('to').hasParam('tag')) {
to += ';tag=' + this.to_tag;
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + this.getHeader('From') + '\r\n';
response += 'Call-ID: ' + this.call_id + '\r\n';
response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n';
response += 'Content-Length: ' + 0 + '\r\n\r\n';
this.transport.send(response);
};
function IncomingResponse() {
this.headers = {};
this.status_code = null;
this.reason_phrase = null;
}
IncomingResponse.prototype = new IncomingMessage();
},{"./Constants":1,"./Grammar":6,"./NameAddrHeader":9,"./Utils":22,"debug":29}],17:[function(require,module,exports){
var T1 = 500,
T2 = 4000,
T4 = 5000;
var Timers = {
T1: T1,
T2: T2,
T4: T4,
TIMER_B: 64 * T1,
TIMER_D: 0 * T1,
TIMER_F: 64 * T1,
TIMER_H: 64 * T1,
TIMER_I: 0 * T1,
TIMER_J: 0 * T1,
TIMER_K: 0 * T4,
TIMER_L: 64 * T1,
TIMER_M: 64 * T1,
PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1
};
module.exports = Timers;
},{}],18:[function(require,module,exports){
module.exports = {
C: null,
NonInviteClientTransaction: NonInviteClientTransaction,
InviteClientTransaction: InviteClientTransaction,
AckClientTransaction: AckClientTransaction,
NonInviteServerTransaction: NonInviteServerTransaction,
InviteServerTransaction: InviteServerTransaction,
checkTransaction: checkTransaction
};
var C = {
// Transaction states
STATUS_TRYING: 1,
STATUS_PROCEEDING: 2,
STATUS_CALLING: 3,
STATUS_ACCEPTED: 4,
STATUS_COMPLETED: 5,
STATUS_TERMINATED: 6,
STATUS_CONFIRMED: 7,
// Transaction types
NON_INVITE_CLIENT: 'nict',
NON_INVITE_SERVER: 'nist',
INVITE_CLIENT: 'ict',
INVITE_SERVER: 'ist'
};
/**
* Expose C object.
*/
module.exports.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debugnict = require('debug')('JsSIP:NonInviteClientTransaction');
var debugict = require('debug')('JsSIP:InviteClientTransaction');
var debugact = require('debug')('JsSIP:AckClientTransaction');
var debugnist = require('debug')('JsSIP:NonInviteServerTransaction');
var debugist = require('debug')('JsSIP:InviteServerTransaction');
var JsSIP_C = require('./Constants');
var Timers = require('./Timers');
function NonInviteClientTransaction(request_sender, request, transport) {
var via,
via_transport;
this.type = C.NON_INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
if (request_sender.ua.configuration.hack_via_tcp) {
via_transport = 'TCP';
}
else if (request_sender.ua.configuration.hack_via_ws) {
via_transport = 'WS';
}
else {
via_transport = transport.server.scheme;
}
via = 'SIP/2.0/' + via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
events.EventEmitter.call(this);
}
util.inherits(NonInviteClientTransaction, events.EventEmitter);
NonInviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
NonInviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_TRYING);
this.F = setTimeout(function() {tr.timer_F();}, Timers.TIMER_F);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
NonInviteClientTransaction.prototype.onTransportError = function() {
debugnict('transport error occurred, deleting transaction ' + this.id);
clearTimeout(this.F);
clearTimeout(this.K);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onTransportError();
};
NonInviteClientTransaction.prototype.timer_F = function() {
debugnict('Timer F expired for transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
};
NonInviteClientTransaction.prototype.timer_K = function() {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
NonInviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code < 200) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
}
} else {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
clearTimeout(this.F);
if(status_code === 408) {
this.request_sender.onRequestTimeout();
} else {
this.request_sender.receiveResponse(response);
}
this.K = setTimeout(function() {tr.timer_K();}, Timers.TIMER_K);
break;
case C.STATUS_COMPLETED:
break;
}
}
};
function InviteClientTransaction(request_sender, request, transport) {
var via,
tr = this,
via_transport;
this.type = C.INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
if (request_sender.ua.configuration.hack_via_tcp) {
via_transport = 'TCP';
}
else if (request_sender.ua.configuration.hack_via_ws) {
via_transport = 'WS';
}
else {
via_transport = transport.server.scheme;
}
via = 'SIP/2.0/' + via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
// TODO: Adding here the cancel() method is a hack that must be fixed.
// Add the cancel property to the request.
//Will be called from the request instance, not the transaction itself.
this.request.cancel = function(reason) {
tr.cancel_request(tr, reason);
};
events.EventEmitter.call(this);
}
util.inherits(InviteClientTransaction, events.EventEmitter);
InviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
InviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_CALLING);
this.B = setTimeout(function() {
tr.timer_B();
}, Timers.TIMER_B);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
InviteClientTransaction.prototype.onTransportError = function() {
clearTimeout(this.B);
clearTimeout(this.D);
clearTimeout(this.M);
if (this.state !== C.STATUS_ACCEPTED) {
debugict('transport error occurred, deleting transaction ' + this.id);
this.request_sender.onTransportError();
}
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
// RFC 6026 7.2
InviteClientTransaction.prototype.timer_M = function() {
debugict('Timer M expired for transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
}
};
// RFC 3261 17.1.1
InviteClientTransaction.prototype.timer_B = function() {
debugict('Timer B expired for transaction ' + this.id);
if(this.state === C.STATUS_CALLING) {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
}
};
InviteClientTransaction.prototype.timer_D = function() {
debugict('Timer D expired for transaction ' + this.id);
clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
InviteClientTransaction.prototype.sendACK = function(response) {
var tr = this;
this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n';
this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n';
}
this.ack += 'To: ' + response.getHeader('to') + '\r\n';
this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n';
this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n';
this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0];
this.ack += ' ACK\r\n';
this.ack += 'Content-Length: 0\r\n\r\n';
this.D = setTimeout(function() {tr.timer_D();}, Timers.TIMER_D);
this.transport.send(this.ack);
};
InviteClientTransaction.prototype.cancel_request = function(tr, reason) {
var request = tr.request;
this.cancel = JsSIP_C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n';
this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n';
}
this.cancel += 'To: ' + request.headers.To.toString() + '\r\n';
this.cancel += 'From: ' + request.headers.From.toString() + '\r\n';
this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n';
this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] +
' CANCEL\r\n';
if(reason) {
this.cancel += 'Reason: ' + reason + '\r\n';
}
this.cancel += 'Content-Length: 0\r\n\r\n';
// Send only if a provisional response (>100) has been received.
if(this.state === C.STATUS_PROCEEDING) {
this.transport.send(this.cancel);
}
};
InviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_CALLING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_PROCEEDING:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.M = setTimeout(function() {
tr.timer_M();
}, Timers.TIMER_M);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_ACCEPTED:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.sendACK(response);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_COMPLETED:
this.sendACK(response);
break;
}
}
};
function AckClientTransaction(request_sender, request, transport) {
var via,
via_transport;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
if (request_sender.ua.configuration.hack_via_tcp) {
via_transport = 'TCP';
}
else if (request_sender.ua.configuration.hack_via_ws) {
via_transport = 'WS';
}
else {
via_transport = transport.server.scheme;
}
via = 'SIP/2.0/' + via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
events.EventEmitter.call(this);
}
util.inherits(AckClientTransaction, events.EventEmitter);
AckClientTransaction.prototype.send = function() {
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
AckClientTransaction.prototype.onTransportError = function() {
debugact('transport error occurred for transaction ' + this.id);
this.request_sender.onTransportError();
};
function NonInviteServerTransaction(request, ua) {
this.type = C.NON_INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.state = C.STATUS_TRYING;
ua.newTransaction(this);
events.EventEmitter.call(this);
}
util.inherits(NonInviteServerTransaction, events.EventEmitter);
NonInviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
NonInviteServerTransaction.prototype.timer_J = function() {
debugnist('Timer J expired for transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
NonInviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
debugnist('transport error occurred, deleting transaction ' + this.id);
clearTimeout(this.J);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code === 100) {
/* RFC 4320 4.1
* 'A SIP element MUST NOT
* send any provisional response with a
* Status-Code other than 100 to a non-INVITE request.'
*/
switch(this.state) {
case C.STATUS_TRYING:
this.stateChanged(C.STATUS_PROCEEDING);
if(!this.transport.send(response)) {
this.onTransportError();
}
break;
case C.STATUS_PROCEEDING:
this.last_response = response;
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 200 && status_code <= 699) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.last_response = response;
this.J = setTimeout(function() {
tr.timer_J();
}, Timers.TIMER_J);
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
case C.STATUS_COMPLETED:
break;
}
}
};
function InviteServerTransaction(request, ua) {
this.type = C.INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.state = C.STATUS_PROCEEDING;
ua.newTransaction(this);
this.resendProvisionalTimer = null;
request.reply(100);
events.EventEmitter.call(this);
}
util.inherits(InviteServerTransaction, events.EventEmitter);
InviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
InviteServerTransaction.prototype.timer_H = function() {
debugist('Timer H expired for transaction ' + this.id);
if(this.state === C.STATUS_COMPLETED) {
debugist('ACK not received, dialog will be terminated');
}
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
InviteServerTransaction.prototype.timer_I = function() {
this.stateChanged(C.STATUS_TERMINATED);
};
// RFC 6026 7.1
InviteServerTransaction.prototype.timer_L = function() {
debugist('Timer L expired for transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
debugist('transport error occurred, deleting transaction ' + this.id);
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
clearTimeout(this.L);
clearTimeout(this.H);
clearTimeout(this.I);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.resend_provisional = function() {
if(!this.transport.send(this.last_response)) {
this.onTransportError();
}
};
// INVITE Server Transaction RFC 3261 17.2.1
InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if(!this.transport.send(response)) {
this.onTransportError();
}
this.last_response = response;
break;
}
}
if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) {
// Trigger the resendProvisionalTimer only for the first non 100 provisional response.
if(this.resendProvisionalTimer === null) {
this.resendProvisionalTimer = setInterval(function() {
tr.resend_provisional();}, Timers.PROVISIONAL_RESPONSE_INTERVAL);
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.last_response = response;
this.L = setTimeout(function() {
tr.timer_L();
}, Timers.TIMER_L);
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
/* falls through */
case C.STATUS_ACCEPTED:
// Note that this point will be reached for proceeding tr.state also.
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else {
this.stateChanged(C.STATUS_COMPLETED);
this.H = setTimeout(function() {
tr.timer_H();
}, Timers.TIMER_H);
if (onSuccess) {
onSuccess();
}
}
break;
}
}
};
/**
* INVITE:
* _true_ if retransmission
* _false_ new request
*
* ACK:
* _true_ ACK to non2xx response
* _false_ ACK must be passed to TU (accepted state)
* ACK to 2xx response
*
* CANCEL:
* _true_ no matching invite transaction
* _false_ matching invite transaction and no final response sent
*
* OTHER:
* _true_ retransmission
* _false_ new request
*/
function checkTransaction(ua, request) {
var tr;
switch(request.method) {
case JsSIP_C.INVITE:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_PROCEEDING:
tr.transport.send(tr.last_response);
break;
// RFC 6026 7.1 Invite retransmission
//received while in C.STATUS_ACCEPTED state. Absorb it.
case C.STATUS_ACCEPTED:
break;
}
return true;
}
break;
case JsSIP_C.ACK:
tr = ua.transactions.ist[request.via_branch];
// RFC 6026 7.1
if(tr) {
if(tr.state === C.STATUS_ACCEPTED) {
return false;
} else if(tr.state === C.STATUS_COMPLETED) {
tr.state = C.STATUS_CONFIRMED;
tr.I = setTimeout(function() {tr.timer_I();}, Timers.TIMER_I);
return true;
}
}
// ACK to 2XX Response.
else {
return false;
}
break;
case JsSIP_C.CANCEL:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
request.reply_sl(200);
if(tr.state === C.STATUS_PROCEEDING) {
return false;
} else {
return true;
}
} else {
request.reply_sl(481);
return true;
}
break;
default:
// Non-INVITE Server Transaction RFC 3261 17.2.2
tr = ua.transactions.nist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_TRYING:
break;
case C.STATUS_PROCEEDING:
case C.STATUS_COMPLETED:
tr.transport.send(tr.last_response);
break;
}
return true;
}
break;
}
}
},{"./Constants":1,"./Timers":17,"debug":29,"events":24,"util":28}],19:[function(require,module,exports){
module.exports = Transport;
var C = {
// Transport status codes
STATUS_READY: 0,
STATUS_DISCONNECTED: 1,
STATUS_ERROR: 2
};
/**
* Expose C object.
*/
Transport.C = C;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:Transport');
var JsSIP_C = require('./Constants');
var Parser = require('./Parser');
var UA = require('./UA');
var SIPMessage = require('./SIPMessage');
var sanityCheck = require('./sanityCheck');
// 'websocket' module uses the native WebSocket interface when bundled to run in a browser.
var W3CWebSocket = require('websocket').w3cwebsocket;
function Transport(ua, server) {
this.ua = ua;
this.ws = null;
this.server = server;
this.reconnection_attempts = 0;
this.closed = false;
this.connected = false;
this.reconnectTimer = null;
this.lastTransportError = {};
/**
* Options for the Node "websocket" library.
*/
this.node_websocket_options = this.ua.configuration.node_websocket_options || {};
// Add our User-Agent header.
this.node_websocket_options.headers = this.node_websocket_options.headers || {};
this.node_websocket_options.headers['User-Agent'] = JsSIP_C.USER_AGENT;
}
Transport.prototype = {
/**
* Connect socket.
*/
connect: function() {
var transport = this;
if(this.ws && (this.ws.readyState === this.ws.OPEN || this.ws.readyState === this.ws.CONNECTING)) {
debug('WebSocket ' + this.server.ws_uri + ' is already connected');
return false;
}
if(this.ws) {
this.ws.close();
}
debug('connecting to WebSocket ' + this.server.ws_uri);
this.ua.onTransportConnecting(this,
(this.reconnection_attempts === 0)?1:this.reconnection_attempts);
try {
this.ws = new W3CWebSocket(this.server.ws_uri, 'sip', this.node_websocket_options.origin, this.node_websocket_options.headers, this.node_websocket_options.requestOptions, this.node_websocket_options.clientConfig);
this.ws.binaryType = 'arraybuffer';
this.ws.onopen = function() {
transport.onOpen();
};
this.ws.onclose = function(e) {
transport.onClose(e);
};
this.ws.onmessage = function(e) {
transport.onMessage(e);
};
this.ws.onerror = function(e) {
transport.onError(e);
};
} catch(e) {
debug('error connecting to WebSocket ' + this.server.ws_uri + ': ' + e);
this.lastTransportError.code = null;
this.lastTransportError.reason = e.message;
this.ua.onTransportError(this);
}
},
/**
* Disconnect socket.
*/
disconnect: function() {
if(this.ws) {
// Clear reconnectTimer
clearTimeout(this.reconnectTimer);
// TODO: should make this.reconnectTimer = null here?
this.closed = true;
debug('closing WebSocket ' + this.server.ws_uri);
this.ws.close();
}
// TODO: Why this??
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
this.ua.onTransportDisconnected({
transport: this,
code: this.lastTransportError.code,
reason: this.lastTransportError.reason
});
}
},
/**
* Send a message.
*/
send: function(msg) {
var message = msg.toString();
if(this.ws && this.ws.readyState === this.ws.OPEN) {
debug('sending WebSocket message:\n\n' + message + '\n');
this.ws.send(message);
return true;
} else {
debug('unable to send message, WebSocket is not open');
return false;
}
},
// Transport Event Handlers
onOpen: function() {
this.connected = true;
debug('WebSocket ' + this.server.ws_uri + ' connected');
// Clear reconnectTimer since we are not disconnected
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
// Reset reconnection_attempts
this.reconnection_attempts = 0;
// Disable closed
this.closed = false;
// Trigger onTransportConnected callback
this.ua.onTransportConnected(this);
},
onClose: function(e) {
var connected_before = this.connected;
this.connected = false;
this.lastTransportError.code = e.code;
this.lastTransportError.reason = e.reason;
debug('WebSocket disconnected (code: ' + e.code + (e.reason? '| reason: ' + e.reason : '') +')');
if(e.wasClean === false) {
debug('WebSocket abrupt disconnection');
}
// Transport was connected
if (connected_before === true) {
this.ua.onTransportClosed(this);
// Check whether the user requested to close.
if(!this.closed) {
this.reConnect();
}
} else {
// This is the first connection attempt
// May be a network error (or may be UA.stop() was called)
this.ua.onTransportError(this);
}
},
onMessage: function(e) {
var message, transaction,
data = e.data;
// CRLF Keep Alive response from server. Ignore it.
if(data === '\r\n') {
debug('received WebSocket message with CRLF Keep Alive response');
return;
}
// WebSocket binary message.
else if (typeof data !== 'string') {
try {
data = String.fromCharCode.apply(null, new Uint8Array(data));
} catch(evt) {
debug('received WebSocket binary message failed to be converted into string, message discarded');
return;
}
debug('received WebSocket binary message:\n\n' + data + '\n');
}
// WebSocket text message.
else {
debug('received WebSocket text message:\n\n' + data + '\n');
}
message = Parser.parseMessage(data, this.ua);
if (! message) {
return;
}
if(this.ua.status === UA.C.STATUS_USER_CLOSED && message instanceof SIPMessage.IncomingRequest) {
return;
}
// Do some sanity check
if(! sanityCheck(message, this.ua, this)) {
return;
}
if(message instanceof SIPMessage.IncomingRequest) {
message.transport = this;
this.ua.receiveRequest(message);
} else if(message instanceof SIPMessage.IncomingResponse) {
/* Unike stated in 18.1.2, if a response does not match
* any transaction, it is discarded here and no passed to the core
* in order to be discarded there.
*/
switch(message.method) {
case JsSIP_C.INVITE:
transaction = this.ua.transactions.ict[message.via_branch];
if(transaction) {
transaction.receiveResponse(message);
}
break;
case JsSIP_C.ACK:
// Just in case ;-)
break;
default:
transaction = this.ua.transactions.nict[message.via_branch];
if(transaction) {
transaction.receiveResponse(message);
}
break;
}
}
},
onError: function(e) {
debug('WebSocket connection error: %o', e);
},
/**
* Reconnection attempt logic.
*/
reConnect: function() {
var transport = this;
this.reconnection_attempts += 1;
if(this.reconnection_attempts > this.ua.configuration.ws_server_max_reconnection) {
debug('maximum reconnection attempts for WebSocket ' + this.server.ws_uri);
this.ua.onTransportError(this);
} else {
debug('trying to reconnect to WebSocket ' + this.server.ws_uri + ' (reconnection attempt ' + this.reconnection_attempts + ')');
this.reconnectTimer = setTimeout(function() {
transport.connect();
transport.reconnectTimer = null;
}, this.ua.configuration.ws_server_reconnection_timeout * 1000);
}
}
};
},{"./Constants":1,"./Parser":10,"./SIPMessage":16,"./UA":20,"./sanityCheck":23,"debug":29,"websocket":43}],20:[function(require,module,exports){
module.exports = UA;
var C = {
// UA status codes
STATUS_INIT : 0,
STATUS_READY: 1,
STATUS_USER_CLOSED: 2,
STATUS_NOT_READY: 3,
// UA error codes
CONFIGURATION_ERROR: 1,
NETWORK_ERROR: 2
};
/**
* Expose C object.
*/
UA.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:UA');
var rtcninja = require('rtcninja');
var JsSIP_C = require('./Constants');
var Registrator = require('./Registrator');
var RTCSession = require('./RTCSession');
var Message = require('./Message');
var Transport = require('./Transport');
var Transactions = require('./Transactions');
var Transactions = require('./Transactions');
var Utils = require('./Utils');
var Exceptions = require('./Exceptions');
var URI = require('./URI');
var Grammar = require('./Grammar');
/**
* The User-Agent class.
* @class JsSIP.UA
* @param {Object} configuration Configuration parameters.
* @throws {JsSIP.Exceptions.ConfigurationError} If a configuration parameter is invalid.
* @throws {TypeError} If no configuration is given.
*/
function UA(configuration) {
this.cache = {
credentials: {}
};
this.configuration = {};
this.dynConfiguration = {};
this.dialogs = {};
//User actions outside any session/dialog (MESSAGE)
this.applicants = {};
this.sessions = {};
this.transport = null;
this.contact = null;
this.status = C.STATUS_INIT;
this.error = null;
this.transactions = {
nist: {},
nict: {},
ist: {},
ict: {}
};
// Custom UA empty object for high level use
this.data = {};
this.transportRecoverAttempts = 0;
this.transportRecoveryTimer = null;
Object.defineProperties(this, {
transactionsCount: {
get: function() {
var type,
transactions = ['nist','nict','ist','ict'],
count = 0;
for (type in transactions) {
count += Object.keys(this.transactions[transactions[type]]).length;
}
return count;
}
},
nictTransactionsCount: {
get: function() {
return Object.keys(this.transactions.nict).length;
}
},
nistTransactionsCount: {
get: function() {
return Object.keys(this.transactions.nist).length;
}
},
ictTransactionsCount: {
get: function() {
return Object.keys(this.transactions.ict).length;
}
},
istTransactionsCount: {
get: function() {
return Object.keys(this.transactions.ist).length;
}
}
});
/**
* Load configuration
*/
if(configuration === undefined) {
throw new TypeError('Not enough arguments');
}
try {
this.loadConfig(configuration);
} catch(e) {
this.status = C.STATUS_NOT_READY;
this.error = C.CONFIGURATION_ERROR;
throw e;
}
// Initialize registrator
this._registrator = new Registrator(this);
events.EventEmitter.call(this);
// Initialize rtcninja if not yet done.
if (! rtcninja.called) {
rtcninja();
}
}
util.inherits(UA, events.EventEmitter);
//=================
// High Level API
//=================
/**
* Connect to the WS server if status = STATUS_INIT.
* Resume UA after being closed.
*/
UA.prototype.start = function() {
debug('start()');
var server;
if (this.status === C.STATUS_INIT) {
server = this.getNextWsServer();
this.transport = new Transport(this, server);
this.transport.connect();
} else if(this.status === C.STATUS_USER_CLOSED) {
debug('restarting UA');
this.status = C.STATUS_READY;
this.transport.connect();
} else if (this.status === C.STATUS_READY) {
debug('UA is in READY status, not restarted');
} else {
debug('ERROR: connection is down, Auto-Recovery system is trying to reconnect');
}
// Set dynamic configuration.
this.dynConfiguration.register = this.configuration.register;
};
/**
* Register.
*/
UA.prototype.register = function() {
debug('register()');
this.dynConfiguration.register = true;
this._registrator.register();
};
/**
* Unregister.
*/
UA.prototype.unregister = function(options) {
debug('unregister()');
this.dynConfiguration.register = false;
this._registrator.unregister(options);
};
/**
* Get the Registrator instance.
*/
UA.prototype.registrator = function() {
return this._registrator;
};
/**
* Registration state.
*/
UA.prototype.isRegistered = function() {
if(this._registrator.registered) {
return true;
} else {
return false;
}
};
/**
* Connection state.
*/
UA.prototype.isConnected = function() {
if(this.transport) {
return this.transport.connected;
} else {
return false;
}
};
/**
* Make an outgoing call.
*
* -param {String} target
* -param {Object} views
* -param {Object} [options]
*
* -throws {TypeError}
*
*/
UA.prototype.call = function(target, options) {
debug('call()');
var session;
session = new RTCSession(this);
session.connect(target, options);
return session;
};
/**
* Send a message.
*
* -param {String} target
* -param {String} body
* -param {Object} [options]
*
* -throws {TypeError}
*
*/
UA.prototype.sendMessage = function(target, body, options) {
debug('sendMessage()');
var message;
message = new Message(this);
message.send(target, body, options);
return message;
};
/**
* Terminate ongoing sessions.
*/
UA.prototype.terminateSessions = function(options) {
debug('terminateSessions()');
for(var idx in this.sessions) {
if (!this.sessions[idx].isEnded()) {
this.sessions[idx].terminate(options);
}
}
};
/**
* Gracefully close.
*
*/
UA.prototype.stop = function() {
debug('stop()');
var session;
var applicant;
var num_sessions;
var ua = this;
// Remove dynamic settings.
this.dynConfiguration = {};
if(this.status === C.STATUS_USER_CLOSED) {
debug('UA already closed');
return;
}
// Clear transportRecoveryTimer
clearTimeout(this.transportRecoveryTimer);
// Close registrator
this._registrator.close();
// If there are session wait a bit so CANCEL/BYE can be sent and their responses received.
num_sessions = Object.keys(this.sessions).length;
// Run _terminate_ on every Session
for(session in this.sessions) {
debug('closing session ' + session);
try { this.sessions[session].terminate(); } catch(error) {}
}
// Run _close_ on every applicant
for(applicant in this.applicants) {
try { this.applicants[applicant].close(); } catch(error) {}
}
this.status = C.STATUS_USER_CLOSED;
// If there are no pending non-INVITE client or server transactions and no
// sessions, then disconnect now. Otherwise wait for 2 seconds.
// TODO: This fails if sotp() is called once an outgoing is cancelled (no time
// to send ACK for 487), so leave 2 seconds until properly re-designed.
// if (this.nistTransactionsCount === 0 && this.nictTransactionsCount === 0 && num_sessions === 0) {
// ua.transport.disconnect();
// }
// else {
setTimeout(function() {
ua.transport.disconnect();
}, 2000);
// }
};
/**
* Normalice a string into a valid SIP request URI
* -param {String} target
* -returns {JsSIP.URI|undefined}
*/
UA.prototype.normalizeTarget = function(target) {
return Utils.normalizeTarget(target, this.configuration.hostport_params);
};
//===============================
// Private (For internal use)
//===============================
UA.prototype.saveCredentials = function(credentials) {
this.cache.credentials[credentials.realm] = this.cache.credentials[credentials.realm] || {};
this.cache.credentials[credentials.realm][credentials.uri] = credentials;
};
UA.prototype.getCredentials = function(request) {
var realm, credentials;
realm = request.ruri.host;
if (this.cache.credentials[realm] && this.cache.credentials[realm][request.ruri]) {
credentials = this.cache.credentials[realm][request.ruri];
credentials.method = request.method;
}
return credentials;
};
//==========================
// Event Handlers
//==========================
/**
* Transport Close event.
*/
UA.prototype.onTransportClosed = function(transport) {
// Run _onTransportError_ callback on every client transaction using _transport_
var type, idx, length,
client_transactions = ['nict', 'ict', 'nist', 'ist'];
transport.server.status = Transport.C.STATUS_DISCONNECTED;
length = client_transactions.length;
for (type = 0; type < length; type++) {
for(idx in this.transactions[client_transactions[type]]) {
this.transactions[client_transactions[type]][idx].onTransportError();
}
}
this.emit('disconnected', {
transport: transport,
code: transport.lastTransportError.code,
reason: transport.lastTransportError.reason
});
};
/**
* Unrecoverable transport event.
* Connection reattempt logic has been done and didn't success.
*/
UA.prototype.onTransportError = function(transport) {
var server;
debug('transport ' + transport.server.ws_uri + ' failed | connection state set to '+ Transport.C.STATUS_ERROR);
// Close sessions.
// Mark this transport as 'down' and try the next one
transport.server.status = Transport.C.STATUS_ERROR;
this.emit('disconnected', {
transport: transport,
code: transport.lastTransportError.code,
reason: transport.lastTransportError.reason
});
// Don't attempt to recover the connection if the user closes the UA.
if (this.status === C.STATUS_USER_CLOSED) {
return;
}
server = this.getNextWsServer();
if(server) {
this.transport = new Transport(this, server);
this.transport.connect();
} else {
this.closeSessionsOnTransportError();
if (!this.error || this.error !== C.NETWORK_ERROR) {
this.status = C.STATUS_NOT_READY;
this.error = C.NETWORK_ERROR;
}
// Transport Recovery process
this.recoverTransport();
}
};
/**
* Transport connection event.
*/
UA.prototype.onTransportConnected = function(transport) {
this.transport = transport;
// Reset transport recovery counter
this.transportRecoverAttempts = 0;
transport.server.status = Transport.C.STATUS_READY;
if(this.status === C.STATUS_USER_CLOSED) {
return;
}
this.status = C.STATUS_READY;
this.error = null;
if(this.dynConfiguration.register) {
this._registrator.register();
}
this.emit('connected', {
transport: transport
});
};
/**
* Transport connecting event
*/
UA.prototype.onTransportConnecting = function(transport, attempts) {
this.emit('connecting', {
transport: transport,
attempts: attempts
});
};
/**
* Transport connected event
*/
UA.prototype.onTransportDisconnected = function(data) {
this.emit('disconnected', data);
};
/**
* new Transaction
*/
UA.prototype.newTransaction = function(transaction) {
this.transactions[transaction.type][transaction.id] = transaction;
this.emit('newTransaction', {
transaction: transaction
});
};
/**
* Transaction destroyed.
*/
UA.prototype.destroyTransaction = function(transaction) {
delete this.transactions[transaction.type][transaction.id];
this.emit('transactionDestroyed', {
transaction: transaction
});
};
/**
* new Message
*/
UA.prototype.newMessage = function(data) {
this.emit('newMessage', data);
};
/**
* new RTCSession
*/
UA.prototype.newRTCSession = function(data) {
this.emit('newRTCSession', data);
};
/**
* Registered
*/
UA.prototype.registered = function(data) {
this.emit('registered', data);
};
/**
* Unregistered
*/
UA.prototype.unregistered = function(data) {
this.emit('unregistered', data);
};
/**
* Registration Failed
*/
UA.prototype.registrationFailed = function(data) {
this.emit('registrationFailed', data);
};
//=========================
// receiveRequest
//=========================
/**
* Request reception
*/
UA.prototype.receiveRequest = function(request) {
var dialog, session, message,
method = request.method;
// Check that request URI points to us
if(request.ruri.user !== this.configuration.uri.user && request.ruri.user !== this.contact.uri.user) {
debug('Request-URI does not point to us');
if (request.method !== JsSIP_C.ACK) {
request.reply_sl(404);
}
return;
}
// Check request URI scheme
if(request.ruri.scheme === JsSIP_C.SIPS) {
request.reply_sl(416);
return;
}
// Check transaction
if(Transactions.checkTransaction(this, request)) {
return;
}
// Create the server transaction
if(method === JsSIP_C.INVITE) {
new Transactions.InviteServerTransaction(request, this);
} else if(method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) {
new Transactions.NonInviteServerTransaction(request, this);
}
/* RFC3261 12.2.2
* Requests that do not change in any way the state of a dialog may be
* received within a dialog (for example, an OPTIONS request).
* They are processed as if they had been received outside the dialog.
*/
if(method === JsSIP_C.OPTIONS) {
request.reply(200);
} else if (method === JsSIP_C.MESSAGE) {
if (this.listeners('newMessage').length === 0) {
request.reply(405);
return;
}
message = new Message(this);
message.init_incoming(request);
} else if (method === JsSIP_C.INVITE) {
// Initial INVITE
if(!request.to_tag && this.listeners('newRTCSession').length === 0) {
request.reply(405);
return;
}
}
// Initial Request
if(!request.to_tag) {
switch(method) {
case JsSIP_C.INVITE:
if (rtcninja.hasWebRTC()) {
session = new RTCSession(this);
session.init_incoming(request);
} else {
debug('INVITE received but WebRTC is not supported');
request.reply(488);
}
break;
case JsSIP_C.BYE:
// Out of dialog BYE received
request.reply(481);
break;
case JsSIP_C.CANCEL:
session = this.findSession(request);
if (session) {
session.receiveRequest(request);
} else {
debug('received CANCEL request for a non existent session');
}
break;
case JsSIP_C.ACK:
/* Absorb it.
* ACK request without a corresponding Invite Transaction
* and without To tag.
*/
break;
default:
request.reply(405);
break;
}
}
// In-dialog request
else {
dialog = this.findDialog(request);
if(dialog) {
dialog.receiveRequest(request);
} else if (method === JsSIP_C.NOTIFY) {
session = this.findSession(request);
if(session) {
session.receiveRequest(request);
} else {
debug('received NOTIFY request for a non existent subscription');
request.reply(481, 'Subscription does not exist');
}
}
/* RFC3261 12.2.2
* Request with to tag, but no matching dialog found.
* Exception: ACK for an Invite request for which a dialog has not
* been created.
*/
else {
if(method !== JsSIP_C.ACK) {
request.reply(481);
}
}
}
};
//=================
// Utils
//=================
/**
* Get the session to which the request belongs to, if any.
*/
UA.prototype.findSession = function(request) {
var
sessionIDa = request.call_id + request.from_tag,
sessionA = this.sessions[sessionIDa],
sessionIDb = request.call_id + request.to_tag,
sessionB = this.sessions[sessionIDb];
if(sessionA) {
return sessionA;
} else if(sessionB) {
return sessionB;
} else {
return null;
}
};
/**
* Get the dialog to which the request belongs to, if any.
*/
UA.prototype.findDialog = function(request) {
var
id = request.call_id + request.from_tag + request.to_tag,
dialog = this.dialogs[id];
if(dialog) {
return dialog;
} else {
id = request.call_id + request.to_tag + request.from_tag;
dialog = this.dialogs[id];
if(dialog) {
return dialog;
} else {
return null;
}
}
};
/**
* Retrieve the next server to which connect.
*/
UA.prototype.getNextWsServer = function() {
// Order servers by weight
var idx, length, ws_server,
candidates = [];
length = this.configuration.ws_servers.length;
for (idx = 0; idx < length; idx++) {
ws_server = this.configuration.ws_servers[idx];
if (ws_server.status === Transport.C.STATUS_ERROR) {
continue;
} else if (candidates.length === 0) {
candidates.push(ws_server);
} else if (ws_server.weight > candidates[0].weight) {
candidates = [ws_server];
} else if (ws_server.weight === candidates[0].weight) {
candidates.push(ws_server);
}
}
idx = Math.floor((Math.random()* candidates.length));
return candidates[idx];
};
/**
* Close all sessions on transport error.
*/
UA.prototype.closeSessionsOnTransportError = function() {
var idx;
// Run _transportError_ for every Session
for(idx in this.sessions) {
this.sessions[idx].onTransportError();
}
// Call registrator _onTransportClosed_
this._registrator.onTransportClosed();
};
UA.prototype.recoverTransport = function(ua) {
var idx, length, k, nextRetry, count, server;
ua = ua || this;
count = ua.transportRecoverAttempts;
length = ua.configuration.ws_servers.length;
for (idx = 0; idx < length; idx++) {
ua.configuration.ws_servers[idx].status = 0;
}
server = ua.getNextWsServer();
k = Math.floor((Math.random() * Math.pow(2,count)) +1);
nextRetry = k * ua.configuration.connection_recovery_min_interval;
if (nextRetry > ua.configuration.connection_recovery_max_interval) {
debug('time for next connection attempt exceeds connection_recovery_max_interval, resetting counter');
nextRetry = ua.configuration.connection_recovery_min_interval;
count = 0;
}
debug('next connection attempt in '+ nextRetry +' seconds');
this.transportRecoveryTimer = setTimeout(function() {
ua.transportRecoverAttempts = count + 1;
ua.transport = new Transport(ua, server);
ua.transport.connect();
}, nextRetry * 1000);
};
UA.prototype.loadConfig = function(configuration) {
// Settings and default values
var parameter, value, checked_value, hostport_params, registrar_server,
settings = {
/* Host address
* Value to be set in Via sent_by and host part of Contact FQDN
*/
via_host: Utils.createRandomToken(12) + '.invalid',
// Password
password: null,
// Registration parameters
register_expires: 600,
register: true,
registrar_server: null,
// Transport related parameters
ws_server_max_reconnection: 3,
ws_server_reconnection_timeout: 4,
connection_recovery_min_interval: 2,
connection_recovery_max_interval: 30,
use_preloaded_route: false,
// Session parameters
no_answer_timeout: 60,
session_timers: true,
// Hacks
hack_via_tcp: false,
hack_via_ws: false,
hack_ip_in_contact: false,
// Options for Node.
node_websocket_options: {}
};
// Pre-Configuration
// Check Mandatory parameters
for(parameter in UA.configuration_check.mandatory) {
if(!configuration.hasOwnProperty(parameter)) {
throw new Exceptions.ConfigurationError(parameter);
} else {
value = configuration[parameter];
checked_value = UA.configuration_check.mandatory[parameter].call(this, value);
if (checked_value !== undefined) {
settings[parameter] = checked_value;
} else {
throw new Exceptions.ConfigurationError(parameter, value);
}
}
}
// Check Optional parameters
for(parameter in UA.configuration_check.optional) {
if(configuration.hasOwnProperty(parameter)) {
value = configuration[parameter];
/* If the parameter value is null, empty string, undefined, empty array
* or it's a number with NaN value, then apply its default value.
*/
if (Utils.isEmpty(value)) {
continue;
}
checked_value = UA.configuration_check.optional[parameter].call(this, value);
if (checked_value !== undefined) {
settings[parameter] = checked_value;
} else {
throw new Exceptions.ConfigurationError(parameter, value);
}
}
}
// Sanity Checks
// Connection recovery intervals.
if(settings.connection_recovery_max_interval < settings.connection_recovery_min_interval) {
throw new Exceptions.ConfigurationError('connection_recovery_max_interval', settings.connection_recovery_max_interval);
}
// Post Configuration Process
// Allow passing 0 number as display_name.
if (settings.display_name === 0) {
settings.display_name = '0';
}
// Instance-id for GRUU.
if (!settings.instance_id) {
settings.instance_id = Utils.newUUID();
}
// jssip_id instance parameter. Static random tag of length 5.
settings.jssip_id = Utils.createRandomToken(5);
// String containing settings.uri without scheme and user.
hostport_params = settings.uri.clone();
hostport_params.user = null;
settings.hostport_params = hostport_params.toString().replace(/^sip:/i, '');
// Check whether authorization_user is explicitly defined.
// Take 'settings.uri.user' value if not.
if (!settings.authorization_user) {
settings.authorization_user = settings.uri.user;
}
// If no 'registrar_server' is set use the 'uri' value without user portion.
if (!settings.registrar_server) {
registrar_server = settings.uri.clone();
registrar_server.user = null;
settings.registrar_server = registrar_server;
}
// User no_answer_timeout.
settings.no_answer_timeout = settings.no_answer_timeout * 1000;
// Via Host
if (settings.hack_ip_in_contact) {
settings.via_host = Utils.getRandomTestNetIP();
}
this.contact = {
pub_gruu: null,
temp_gruu: null,
uri: new URI('sip', Utils.createRandomToken(8), settings.via_host, null, {transport: 'ws'}),
toString: function(options) {
options = options || {};
var
anonymous = options.anonymous || null,
outbound = options.outbound || null,
contact = '<';
if (anonymous) {
contact += this.temp_gruu || 'sip:[email protected];transport=ws';
} else {
contact += this.pub_gruu || this.uri.toString();
}
if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) {
contact += ';ob';
}
contact += '>';
return contact;
}
};
// Fill the value of the configuration_skeleton
for(parameter in settings) {
UA.configuration_skeleton[parameter].value = settings[parameter];
}
Object.defineProperties(this.configuration, UA.configuration_skeleton);
// Clean UA.configuration_skeleton
for(parameter in settings) {
UA.configuration_skeleton[parameter].value = '';
}
debug('configuration parameters after validation:');
for(parameter in settings) {
switch(parameter) {
case 'uri':
case 'registrar_server':
debug('- ' + parameter + ': ' + settings[parameter]);
break;
case 'password':
debug('- ' + parameter + ': ' + 'NOT SHOWN');
break;
default:
debug('- ' + parameter + ': ' + JSON.stringify(settings[parameter]));
}
}
return;
};
/**
* Configuration Object skeleton.
*/
UA.configuration_skeleton = (function() {
var idx, parameter,
skeleton = {},
parameters = [
// Internal parameters
'jssip_id',
'ws_server_max_reconnection',
'ws_server_reconnection_timeout',
'hostport_params',
// Mandatory user configurable parameters
'uri',
'ws_servers',
// Optional user configurable parameters
'authorization_user',
'connection_recovery_max_interval',
'connection_recovery_min_interval',
'display_name',
'hack_via_tcp', // false
'hack_via_ws', // false
'hack_ip_in_contact', //false
'instance_id',
'no_answer_timeout', // 30 seconds
'session_timers', // true
'node_websocket_options',
'password',
'register_expires', // 600 seconds
'registrar_server',
'use_preloaded_route',
// Post-configuration generated parameters
'via_core_value',
'via_host'
];
for(idx in parameters) {
parameter = parameters[idx];
skeleton[parameter] = {
value: '',
writable: false,
configurable: false
};
}
skeleton.register = {
value: '',
writable: true,
configurable: false
};
return skeleton;
}());
/**
* Configuration checker.
*/
UA.configuration_check = {
mandatory: {
uri: function(uri) {
var parsed;
if (!/^sip:/i.test(uri)) {
uri = JsSIP_C.SIP + ':' + uri;
}
parsed = URI.parse(uri);
if(!parsed) {
return;
} else if(!parsed.user) {
return;
} else {
return parsed;
}
},
ws_servers: function(ws_servers) {
var idx, length, url;
/* Allow defining ws_servers parameter as:
* String: "host"
* Array of Strings: ["host1", "host2"]
* Array of Objects: [{ws_uri:"host1", weight:1}, {ws_uri:"host2", weight:0}]
* Array of Objects and Strings: [{ws_uri:"host1"}, "host2"]
*/
if (typeof ws_servers === 'string') {
ws_servers = [{ws_uri: ws_servers}];
} else if (Array.isArray(ws_servers)) {
length = ws_servers.length;
for (idx = 0; idx < length; idx++) {
if (typeof ws_servers[idx] === 'string') {
ws_servers[idx] = {ws_uri: ws_servers[idx]};
}
}
} else {
return;
}
if (ws_servers.length === 0) {
return false;
}
length = ws_servers.length;
for (idx = 0; idx < length; idx++) {
if (!ws_servers[idx].ws_uri) {
debug('ERROR: missing "ws_uri" attribute in ws_servers parameter');
return;
}
if (ws_servers[idx].weight && !Number(ws_servers[idx].weight)) {
debug('ERROR: "weight" attribute in ws_servers parameter must be a Number');
return;
}
url = Grammar.parse(ws_servers[idx].ws_uri, 'absoluteURI');
if(url === -1) {
debug('ERROR: invalid "ws_uri" attribute in ws_servers parameter: ' + ws_servers[idx].ws_uri);
return;
} else if(url.scheme !== 'wss' && url.scheme !== 'ws') {
debug('ERROR: invalid URI scheme in ws_servers parameter: ' + url.scheme);
return;
} else {
ws_servers[idx].sip_uri = '<sip:' + url.host + (url.port ? ':' + url.port : '') + ';transport=ws;lr>';
if (!ws_servers[idx].weight) {
ws_servers[idx].weight = 0;
}
ws_servers[idx].status = 0;
ws_servers[idx].scheme = url.scheme.toUpperCase();
}
}
return ws_servers;
}
},
optional: {
authorization_user: function(authorization_user) {
if(Grammar.parse('"'+ authorization_user +'"', 'quoted_string') === -1) {
return;
} else {
return authorization_user;
}
},
connection_recovery_max_interval: function(connection_recovery_max_interval) {
var value;
if(Utils.isDecimal(connection_recovery_max_interval)) {
value = Number(connection_recovery_max_interval);
if(value > 0) {
return value;
}
}
},
connection_recovery_min_interval: function(connection_recovery_min_interval) {
var value;
if(Utils.isDecimal(connection_recovery_min_interval)) {
value = Number(connection_recovery_min_interval);
if(value > 0) {
return value;
}
}
},
display_name: function(display_name) {
if(Grammar.parse('"' + display_name + '"', 'display_name') === -1) {
return;
} else {
return display_name;
}
},
hack_via_tcp: function(hack_via_tcp) {
if (typeof hack_via_tcp === 'boolean') {
return hack_via_tcp;
}
},
hack_via_ws: function(hack_via_ws) {
if (typeof hack_via_ws === 'boolean') {
return hack_via_ws;
}
},
hack_ip_in_contact: function(hack_ip_in_contact) {
if (typeof hack_ip_in_contact === 'boolean') {
return hack_ip_in_contact;
}
},
instance_id: function(instance_id) {
if ((/^uuid:/i.test(instance_id))) {
instance_id = instance_id.substr(5);
}
if(Grammar.parse(instance_id, 'uuid') === -1) {
return;
} else {
return instance_id;
}
},
no_answer_timeout: function(no_answer_timeout) {
var value;
if (Utils.isDecimal(no_answer_timeout)) {
value = Number(no_answer_timeout);
if (value > 0) {
return value;
}
}
},
session_timers: function(session_timers) {
if (typeof session_timers === 'boolean') {
return session_timers;
}
},
node_websocket_options: function(node_websocket_options) {
return (typeof node_websocket_options === 'object') ? node_websocket_options : {};
},
password: function(password) {
return String(password);
},
register: function(register) {
if (typeof register === 'boolean') {
return register;
}
},
register_expires: function(register_expires) {
var value;
if (Utils.isDecimal(register_expires)) {
value = Number(register_expires);
if (value > 0) {
return value;
}
}
},
registrar_server: function(registrar_server) {
var parsed;
if (!/^sip:/i.test(registrar_server)) {
registrar_server = JsSIP_C.SIP + ':' + registrar_server;
}
parsed = URI.parse(registrar_server);
if(!parsed) {
return;
} else if(parsed.user) {
return;
} else {
return parsed;
}
},
use_preloaded_route: function(use_preloaded_route) {
if (typeof use_preloaded_route === 'boolean') {
return use_preloaded_route;
}
}
}
};
},{"./Constants":1,"./Exceptions":5,"./Grammar":6,"./Message":8,"./RTCSession":11,"./Registrator":14,"./Transactions":18,"./Transport":19,"./URI":21,"./Utils":22,"debug":29,"events":24,"rtcninja":34,"util":28}],21:[function(require,module,exports){
module.exports = URI;
/**
* Dependencies.
*/
var JsSIP_C = require('./Constants');
var Utils = require('./Utils');
var Grammar = require('./Grammar');
/**
* -param {String} [scheme]
* -param {String} [user]
* -param {String} host
* -param {String} [port]
* -param {Object} [parameters]
* -param {Object} [headers]
*
*/
function URI(scheme, user, host, port, parameters, headers) {
var param, header;
// Checks
if(!host) {
throw new TypeError('missing or invalid "host" parameter');
}
// Initialize parameters
scheme = scheme || JsSIP_C.SIP;
this.parameters = {};
this.headers = {};
for (param in parameters) {
this.setParam(param, parameters[param]);
}
for (header in headers) {
this.setHeader(header, headers[header]);
}
Object.defineProperties(this, {
scheme: {
get: function(){ return scheme; },
set: function(value){
scheme = value.toLowerCase();
}
},
user: {
get: function(){ return user; },
set: function(value){
user = value;
}
},
host: {
get: function(){ return host; },
set: function(value){
host = value.toLowerCase();
}
},
port: {
get: function(){ return port; },
set: function(value){
port = value === 0 ? value : (parseInt(value,10) || null);
}
}
});
}
URI.prototype = {
setParam: function(key, value) {
if(key) {
this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString().toLowerCase();
}
},
getParam: function(key) {
if(key) {
return this.parameters[key.toLowerCase()];
}
},
hasParam: function(key) {
if(key) {
return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false;
}
},
deleteParam: function(parameter) {
var value;
parameter = parameter.toLowerCase();
if (this.parameters.hasOwnProperty(parameter)) {
value = this.parameters[parameter];
delete this.parameters[parameter];
return value;
}
},
clearParams: function() {
this.parameters = {};
},
setHeader: function(name, value) {
this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value];
},
getHeader: function(name) {
if(name) {
return this.headers[Utils.headerize(name)];
}
},
hasHeader: function(name) {
if(name) {
return (this.headers.hasOwnProperty(Utils.headerize(name)) && true) || false;
}
},
deleteHeader: function(header) {
var value;
header = Utils.headerize(header);
if(this.headers.hasOwnProperty(header)) {
value = this.headers[header];
delete this.headers[header];
return value;
}
},
clearHeaders: function() {
this.headers = {};
},
clone: function() {
return new URI(
this.scheme,
this.user,
this.host,
this.port,
JSON.parse(JSON.stringify(this.parameters)),
JSON.parse(JSON.stringify(this.headers)));
},
toString: function(){
var header, parameter, idx, uri,
headers = [];
uri = this.scheme + ':';
if (this.user) {
uri += Utils.escapeUser(this.user) + '@';
}
uri += this.host;
if (this.port || this.port === 0) {
uri += ':' + this.port;
}
for (parameter in this.parameters) {
uri += ';' + parameter;
if (this.parameters[parameter] !== null) {
uri += '='+ this.parameters[parameter];
}
}
for(header in this.headers) {
for(idx in this.headers[header]) {
headers.push(header + '=' + this.headers[header][idx]);
}
}
if (headers.length > 0) {
uri += '?' + headers.join('&');
}
return uri;
},
toAor: function(show_port){
var aor;
aor = this.scheme + ':';
if (this.user) {
aor += Utils.escapeUser(this.user) + '@';
}
aor += this.host;
if (show_port && (this.port || this.port === 0)) {
aor += ':' + this.port;
}
return aor;
}
};
/**
* Parse the given string and returns a JsSIP.URI instance or undefined if
* it is an invalid URI.
*/
URI.parse = function(uri) {
uri = Grammar.parse(uri,'SIP_URI');
if (uri !== -1) {
return uri;
} else {
return undefined;
}
};
},{"./Constants":1,"./Grammar":6,"./Utils":22}],22:[function(require,module,exports){
var Utils = {};
module.exports = Utils;
/**
* Dependencies.
*/
var JsSIP_C = require('./Constants');
var URI = require('./URI');
var Grammar = require('./Grammar');
Utils.str_utf8_length = function(string) {
return unescape(encodeURIComponent(string)).length;
};
Utils.isFunction = function(fn) {
if (fn !== undefined) {
return (Object.prototype.toString.call(fn) === '[object Function]')? true : false;
} else {
return false;
}
};
Utils.isDecimal = function(num) {
return !isNaN(num) && (parseFloat(num) === parseInt(num,10));
};
Utils.isEmpty = function(value) {
if (value === null || value === '' || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof(value) === 'number' && isNaN(value))) {
return true;
}
};
Utils.createRandomToken = function(size, base) {
var i, r,
token = '';
base = base || 32;
for( i=0; i < size; i++ ) {
r = Math.random() * base|0;
token += r.toString(base);
}
return token;
};
Utils.newTag = function() {
return Utils.createRandomToken(10);
};
// http://stackoverflow.com/users/109538/broofa
Utils.newUUID = function() {
var UUID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
return UUID;
};
Utils.hostType = function(host) {
if (!host) {
return;
} else {
host = Grammar.parse(host,'host');
if (host !== -1) {
return host.host_type;
}
}
};
/**
* Normalize SIP URI.
* NOTE: It does not allow a SIP URI without username.
* Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'.
* Detects the domain part (if given) and properly hex-escapes the user portion.
* If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators.
*/
Utils.normalizeTarget = function(target, domain) {
var uri, target_array, target_user, target_domain;
// If no target is given then raise an error.
if (!target) {
return;
// If a URI instance is given then return it.
} else if (target instanceof URI) {
return target;
// If a string is given split it by '@':
// - Last fragment is the desired domain.
// - Otherwise append the given domain argument.
} else if (typeof target === 'string') {
target_array = target.split('@');
switch(target_array.length) {
case 1:
if (!domain) {
return;
}
target_user = target;
target_domain = domain;
break;
case 2:
target_user = target_array[0];
target_domain = target_array[1];
break;
default:
target_user = target_array.slice(0, target_array.length-1).join('@');
target_domain = target_array[target_array.length-1];
}
// Remove the URI scheme (if present).
target_user = target_user.replace(/^(sips?|tel):/i, '');
// Remove 'tel' visual separators if the user portion just contains 'tel' number symbols.
if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(target_user)) {
target_user = target_user.replace(/[\-\.\(\)]/g, '');
}
// Build the complete SIP URI.
target = JsSIP_C.SIP + ':' + Utils.escapeUser(target_user) + '@' + target_domain;
// Finally parse the resulting URI.
if ((uri = URI.parse(target))) {
return uri;
} else {
return;
}
} else {
return;
}
};
/**
* Hex-escape a SIP URI user.
*/
Utils.escapeUser = function(user) {
// Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F).
return encodeURIComponent(decodeURIComponent(user)).replace(/%3A/ig, ':').replace(/%2B/ig, '+').replace(/%3F/ig, '?').replace(/%2F/ig, '/');
};
Utils.headerize = function(string) {
var exceptions = {
'Call-Id': 'Call-ID',
'Cseq': 'CSeq',
'Www-Authenticate': 'WWW-Authenticate'
},
name = string.toLowerCase().replace(/_/g,'-').split('-'),
hname = '',
parts = name.length, part;
for (part = 0; part < parts; part++) {
if (part !== 0) {
hname +='-';
}
hname += name[part].charAt(0).toUpperCase()+name[part].substring(1);
}
if (exceptions[hname]) {
hname = exceptions[hname];
}
return hname;
};
Utils.sipErrorCause = function(status_code) {
var cause;
for (cause in JsSIP_C.SIP_ERROR_CAUSES) {
if (JsSIP_C.SIP_ERROR_CAUSES[cause].indexOf(status_code) !== -1) {
return JsSIP_C.causes[cause];
}
}
return JsSIP_C.causes.SIP_FAILURE_CODE;
};
/**
* Generate a random Test-Net IP (http://tools.ietf.org/html/rfc5735)
*/
Utils.getRandomTestNetIP = function() {
function getOctet(from,to) {
return Math.floor(Math.random()*(to-from+1)+from);
}
return '192.0.2.' + getOctet(1, 254);
};
// MD5 (Message-Digest Algorithm) http://www.webtoolkit.info
Utils.calculateMD5 = function(string) {
function rotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function addUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function doF(x,y,z) {
return (x & y) | ((~x) & z);
}
function doG(x,y,z) {
return (x & z) | (y & (~z));
}
function doH(x,y,z) {
return (x ^ y ^ z);
}
function doI(x,y,z) {
return (y ^ (x | (~z)));
}
function doFF(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doF(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doGG(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doG(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doHH(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doH(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doII(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doI(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function convertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray = new Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
}
function wordToHex(lValue) {
var wordToHexValue='',wordToHexValue_temp='',lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
wordToHexValue_temp = '0' + lByte.toString(16);
wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2);
}
return wordToHexValue;
}
function utf8Encode(string) {
string = string.replace(/\r\n/g, '\n');
var utftext = '';
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
var x=[];
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = utf8Encode(string);
x = convertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=doFF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=doFF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=doFF(c,d,a,b,x[k+2], S13,0x242070DB);
b=doFF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=doFF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=doFF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=doFF(c,d,a,b,x[k+6], S13,0xA8304613);
b=doFF(b,c,d,a,x[k+7], S14,0xFD469501);
a=doFF(a,b,c,d,x[k+8], S11,0x698098D8);
d=doFF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=doFF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=doFF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=doFF(a,b,c,d,x[k+12],S11,0x6B901122);
d=doFF(d,a,b,c,x[k+13],S12,0xFD987193);
c=doFF(c,d,a,b,x[k+14],S13,0xA679438E);
b=doFF(b,c,d,a,x[k+15],S14,0x49B40821);
a=doGG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=doGG(d,a,b,c,x[k+6], S22,0xC040B340);
c=doGG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=doGG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=doGG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=doGG(d,a,b,c,x[k+10],S22,0x2441453);
c=doGG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=doGG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=doGG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=doGG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=doGG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=doGG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=doGG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=doGG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=doGG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=doGG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=doHH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=doHH(d,a,b,c,x[k+8], S32,0x8771F681);
c=doHH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=doHH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=doHH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=doHH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=doHH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=doHH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=doHH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=doHH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=doHH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=doHH(b,c,d,a,x[k+6], S34,0x4881D05);
a=doHH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=doHH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=doHH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=doHH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=doII(a,b,c,d,x[k+0], S41,0xF4292244);
d=doII(d,a,b,c,x[k+7], S42,0x432AFF97);
c=doII(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=doII(b,c,d,a,x[k+5], S44,0xFC93A039);
a=doII(a,b,c,d,x[k+12],S41,0x655B59C3);
d=doII(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=doII(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=doII(b,c,d,a,x[k+1], S44,0x85845DD1);
a=doII(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=doII(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=doII(c,d,a,b,x[k+6], S43,0xA3014314);
b=doII(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=doII(a,b,c,d,x[k+4], S41,0xF7537E82);
d=doII(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=doII(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=doII(b,c,d,a,x[k+9], S44,0xEB86D391);
a=addUnsigned(a,AA);
b=addUnsigned(b,BB);
c=addUnsigned(c,CC);
d=addUnsigned(d,DD);
}
var temp = wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d);
return temp.toLowerCase();
};
},{"./Constants":1,"./Grammar":6,"./URI":21}],23:[function(require,module,exports){
module.exports = sanityCheck;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:sanityCheck');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var Utils = require('./Utils');
var message, ua, transport,
requests = [],
responses = [],
all = [];
requests.push(rfc3261_8_2_2_1);
requests.push(rfc3261_16_3_4);
requests.push(rfc3261_18_3_request);
requests.push(rfc3261_8_2_2_2);
responses.push(rfc3261_8_1_3_3);
responses.push(rfc3261_18_3_response);
all.push(minimumHeaders);
function sanityCheck(m, u, t) {
var len, pass;
message = m;
ua = u;
transport = t;
len = all.length;
while(len--) {
pass = all[len](message);
if(pass === false) {
return false;
}
}
if(message instanceof SIPMessage.IncomingRequest) {
len = requests.length;
while(len--) {
pass = requests[len](message);
if(pass === false) {
return false;
}
}
}
else if(message instanceof SIPMessage.IncomingResponse) {
len = responses.length;
while(len--) {
pass = responses[len](message);
if(pass === false) {
return false;
}
}
}
//Everything is OK
return true;
}
/*
* Sanity Check for incoming Messages
*
* Requests:
* - _rfc3261_8_2_2_1_ Receive a Request with a non supported URI scheme
* - _rfc3261_16_3_4_ Receive a Request already sent by us
* Does not look at via sent-by but at jssip_id, which is inserted as
* a prefix in all initial requests generated by the ua
* - _rfc3261_18_3_request_ Body Content-Length
* - _rfc3261_8_2_2_2_ Merged Requests
*
* Responses:
* - _rfc3261_8_1_3_3_ Multiple Via headers
* - _rfc3261_18_3_response_ Body Content-Length
*
* All:
* - Minimum headers in a SIP message
*/
// Sanity Check functions for requests
function rfc3261_8_2_2_1() {
if(message.s('to').uri.scheme !== 'sip') {
reply(416);
return false;
}
}
function rfc3261_16_3_4() {
if(!message.to_tag) {
if(message.call_id.substr(0, 5) === ua.configuration.jssip_id) {
reply(482);
return false;
}
}
}
function rfc3261_18_3_request() {
var len = Utils.str_utf8_length(message.body),
contentLength = message.getHeader('content-length');
if(len < contentLength) {
reply(400);
return false;
}
}
function rfc3261_8_2_2_2() {
var tr, idx,
fromTag = message.from_tag,
call_id = message.call_id,
cseq = message.cseq;
// Accept any in-dialog request.
if(message.to_tag) {
return;
}
// INVITE request.
if (message.method === JsSIP_C.INVITE) {
// If the branch matches the key of any IST then assume it is a retransmission
// and ignore the INVITE.
// TODO: we should reply the last response.
if (ua.transactions.ist[message.via_branch]) {
return false;
}
// Otherwise check whether it is a merged request.
else {
for(idx in ua.transactions.ist) {
tr = ua.transactions.ist[idx];
if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) {
reply(482);
return false;
}
}
}
}
// Non INVITE request.
else {
// If the branch matches the key of any NIST then assume it is a retransmission
// and ignore the request.
// TODO: we should reply the last response.
if (ua.transactions.nist[message.via_branch]) {
return false;
}
// Otherwise check whether it is a merged request.
else {
for(idx in ua.transactions.nist) {
tr = ua.transactions.nist[idx];
if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) {
reply(482);
return false;
}
}
}
}
}
// Sanity Check functions for responses
function rfc3261_8_1_3_3() {
if(message.getHeaders('via').length > 1) {
debug('more than one Via header field present in the response, dropping the response');
return false;
}
}
function rfc3261_18_3_response() {
var
len = Utils.str_utf8_length(message.body),
contentLength = message.getHeader('content-length');
if(len < contentLength) {
debug('message body length is lower than the value in Content-Length header field, dropping the response');
return false;
}
}
// Sanity Check functions for requests and responses
function minimumHeaders() {
var
mandatoryHeaders = ['from', 'to', 'call_id', 'cseq', 'via'],
idx = mandatoryHeaders.length;
while(idx--) {
if(!message.hasHeader(mandatoryHeaders[idx])) {
debug('missing mandatory header field : ' + mandatoryHeaders[idx] + ', dropping the response');
return false;
}
}
}
// Reply
function reply(status_code) {
var to,
response = 'SIP/2.0 ' + status_code + ' ' + JsSIP_C.REASON_PHRASE[status_code] + '\r\n',
vias = message.getHeaders('via'),
length = vias.length,
idx = 0;
for(idx; idx < length; idx++) {
response += 'Via: ' + vias[idx] + '\r\n';
}
to = message.getHeader('To');
if(!message.to_tag) {
to += ';tag=' + Utils.newTag();
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + message.getHeader('From') + '\r\n';
response += 'Call-ID: ' + message.call_id + '\r\n';
response += 'CSeq: ' + message.cseq + ' ' + message.method + '\r\n';
response += '\r\n';
transport.send(response);
}
},{"./Constants":1,"./SIPMessage":16,"./Utils":22,"debug":29}],24:[function(require,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:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
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) {
var m;
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 {
// 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.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
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;
}
},{}],25:[function(require,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
}
}
},{}],26:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
currentQueue[queueIndex].run();
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],27:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],28:[function(require,module,exports){
(function (process,global){
// 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.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":27,"_process":26,"inherits":25}],29:[function(require,module,exports){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
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) {}
}
},{"./debug":30}],30:[function(require,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 = require('ms');
/**
* 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;
}
},{"ms":31}],31:[function(require,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';
}
},{}],32:[function(require,module,exports){
(function (global){
'use strict';
// Expose the Adapter function/object.
module.exports = Adapter;
// Dependencies
var browser = require('bowser').browser,
debug = require('debug')('rtcninja:Adapter'),
debugerror = require('debug')('rtcninja:ERROR:Adapter'),
// Internal vars
getUserMedia = null,
RTCPeerConnection = null,
RTCSessionDescription = null,
RTCIceCandidate = null,
MediaStreamTrack = null,
getMediaDevices = null,
attachMediaStream = null,
canRenegotiate = false,
oldSpecRTCOfferOptions = false,
browserVersion = Number(browser.version) || 0,
isDesktop = !!(!browser.mobile || !browser.tablet),
hasWebRTC = false,
virtGlobal, virtNavigator;
debugerror.log = console.warn.bind(console);
// Dirty trick to get this library working in a Node-webkit env with browserified libs
virtGlobal = global.window || global;
// Don't fail in Node
virtNavigator = virtGlobal.navigator || {};
// Constructor.
function Adapter(options) {
// Chrome desktop, Chrome Android, Opera desktop, Opera Android, Android native browser
// or generic Webkit browser.
if (
(isDesktop && browser.chrome && browserVersion >= 32) ||
(browser.android && browser.chrome && browserVersion >= 39) ||
(isDesktop && browser.opera && browserVersion >= 27) ||
(browser.android && browser.opera && browserVersion >= 24) ||
(browser.android && browser.webkit && !browser.chrome && browserVersion >= 37) ||
(virtNavigator.webkitGetUserMedia && virtGlobal.webkitRTCPeerConnection)
) {
hasWebRTC = true;
getUserMedia = virtNavigator.webkitGetUserMedia.bind(virtNavigator);
RTCPeerConnection = virtGlobal.webkitRTCPeerConnection;
RTCSessionDescription = virtGlobal.RTCSessionDescription;
RTCIceCandidate = virtGlobal.RTCIceCandidate;
MediaStreamTrack = virtGlobal.MediaStreamTrack;
if (MediaStreamTrack && MediaStreamTrack.getSources) {
getMediaDevices = MediaStreamTrack.getSources.bind(MediaStreamTrack);
} else if (virtNavigator.getMediaDevices) {
getMediaDevices = virtNavigator.getMediaDevices.bind(virtNavigator);
}
attachMediaStream = function (element, stream) {
element.src = URL.createObjectURL(stream);
return element;
};
canRenegotiate = true;
oldSpecRTCOfferOptions = false;
// Firefox desktop, Firefox Android.
} else if (
(isDesktop && browser.firefox && browserVersion >= 22) ||
(browser.android && browser.firefox && browserVersion >= 33) ||
(virtNavigator.mozGetUserMedia && virtGlobal.mozRTCPeerConnection)
) {
hasWebRTC = true;
getUserMedia = virtNavigator.mozGetUserMedia.bind(virtNavigator);
RTCPeerConnection = virtGlobal.mozRTCPeerConnection;
RTCSessionDescription = virtGlobal.mozRTCSessionDescription;
RTCIceCandidate = virtGlobal.mozRTCIceCandidate;
MediaStreamTrack = virtGlobal.MediaStreamTrack;
attachMediaStream = function (element, stream) {
element.src = URL.createObjectURL(stream);
return element;
};
canRenegotiate = false;
oldSpecRTCOfferOptions = false;
// WebRTC plugin required. For example IE or Safari with the Temasys plugin.
} else if (
options.plugin &&
typeof options.plugin.isRequired === 'function' &&
options.plugin.isRequired() &&
typeof options.plugin.isInstalled === 'function' &&
options.plugin.isInstalled()
) {
var pluginiface = options.plugin.interface;
hasWebRTC = true;
getUserMedia = pluginiface.getUserMedia;
RTCPeerConnection = pluginiface.RTCPeerConnection;
RTCSessionDescription = pluginiface.RTCSessionDescription;
RTCIceCandidate = pluginiface.RTCIceCandidate;
MediaStreamTrack = pluginiface.MediaStreamTrack;
// TODO: getSources() freezes IE so disable it.
if (browser.safari) {
if (MediaStreamTrack && MediaStreamTrack.getSources) {
getMediaDevices = MediaStreamTrack.getSources.bind(MediaStreamTrack);
} else if (virtNavigator.getMediaDevices) {
getMediaDevices = virtNavigator.getMediaDevices.bind(virtNavigator);
}
}
attachMediaStream = pluginiface.attachMediaStream;
canRenegotiate = pluginiface.canRenegotiate;
oldSpecRTCOfferOptions = true; // TODO: Update when fixed in the plugin.
// Best effort (may be adater.js is loaded).
} else if (virtNavigator.getUserMedia && virtGlobal.RTCPeerConnection) {
hasWebRTC = true;
getUserMedia = virtNavigator.getUserMedia.bind(virtNavigator);
RTCPeerConnection = virtGlobal.RTCPeerConnection;
RTCSessionDescription = virtGlobal.RTCSessionDescription;
RTCIceCandidate = virtGlobal.RTCIceCandidate;
MediaStreamTrack = virtGlobal.MediaStreamTrack;
if (MediaStreamTrack && MediaStreamTrack.getSources) {
getMediaDevices = MediaStreamTrack.getSources.bind(MediaStreamTrack);
} else if (virtNavigator.getMediaDevices) {
getMediaDevices = virtNavigator.getMediaDevices.bind(virtNavigator);
}
attachMediaStream = virtGlobal.attachMediaStream || function (element, stream) {
element.src = URL.createObjectURL(stream);
return element;
};
canRenegotiate = false;
oldSpecRTCOfferOptions = false;
}
function throwNonSupported(item) {
return function () {
throw new Error('rtcninja: WebRTC not supported, missing ' + item +
' [browser: ' + browser.name + ' ' + browser.version + ']');
};
}
// Public API.
// Expose a WebRTC checker.
Adapter.hasWebRTC = function () {
return hasWebRTC;
};
// Expose getUserMedia.
if (getUserMedia) {
Adapter.getUserMedia = function (constraints, successCallback, errorCallback) {
debug('getUserMedia() | constraints: %o', constraints);
try {
getUserMedia(constraints,
function (stream) {
debug('getUserMedia() | success');
if (successCallback) {
successCallback(stream);
}
},
function (error) {
debug('getUserMedia() | error:', error);
if (errorCallback) {
errorCallback(error);
}
}
);
}
catch (error) {
debugerror('getUserMedia() | error:', error);
if (errorCallback) {
errorCallback(error);
}
}
};
} else {
Adapter.getUserMedia = function (constraints, successCallback, errorCallback) {
debugerror('getUserMedia() | WebRTC not supported');
if (errorCallback) {
errorCallback(new Error('rtcninja: WebRTC not supported, missing ' +
'getUserMedia [browser: ' + browser.name + ' ' + browser.version + ']'));
} else {
throwNonSupported('getUserMedia');
}
};
}
// Expose RTCPeerConnection.
Adapter.RTCPeerConnection = RTCPeerConnection || throwNonSupported('RTCPeerConnection');
// Expose RTCSessionDescription.
Adapter.RTCSessionDescription = RTCSessionDescription || throwNonSupported('RTCSessionDescription');
// Expose RTCIceCandidate.
Adapter.RTCIceCandidate = RTCIceCandidate || throwNonSupported('RTCIceCandidate');
// Expose MediaStreamTrack.
Adapter.MediaStreamTrack = MediaStreamTrack || throwNonSupported('MediaStreamTrack');
// Expose getMediaDevices.
Adapter.getMediaDevices = getMediaDevices;
// Expose MediaStreamTrack.
Adapter.attachMediaStream = attachMediaStream || throwNonSupported('attachMediaStream');
// Expose canRenegotiate attribute.
Adapter.canRenegotiate = canRenegotiate;
// Expose closeMediaStream.
Adapter.closeMediaStream = function (stream) {
if (!stream) {
return;
}
// Latest spec states that MediaStream has no stop() method and instead must
// call stop() on every MediaStreamTrack.
if (MediaStreamTrack && MediaStreamTrack.prototype && MediaStreamTrack.prototype.stop) {
debug('closeMediaStream() | calling stop() on all the MediaStreamTrack');
var tracks, i, len;
if (stream.getTracks) {
tracks = stream.getTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
} else {
tracks = stream.getAudioTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
tracks = stream.getVideoTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
}
// Deprecated by the spec, but still in use.
} else if (typeof stream.stop === 'function') {
debug('closeMediaStream() | calling stop() on the MediaStream');
stream.stop();
}
};
// Expose fixPeerConnectionConfig.
Adapter.fixPeerConnectionConfig = function (pcConfig) {
var i, len, iceServer, hasUrls, hasUrl;
if (!Array.isArray(pcConfig.iceServers)) {
pcConfig.iceServers = [];
}
for (i = 0, len = pcConfig.iceServers.length; i < len; i += 1) {
iceServer = pcConfig.iceServers[i];
hasUrls = iceServer.hasOwnProperty('urls');
hasUrl = iceServer.hasOwnProperty('url');
if (typeof iceServer === 'object') {
// Has .urls but not .url, so add .url with a single string value.
if (hasUrls && !hasUrl) {
iceServer.url = (Array.isArray(iceServer.urls) ? iceServer.urls[0] : iceServer.urls);
// Has .url but not .urls, so add .urls with same value.
} else if (!hasUrls && hasUrl) {
iceServer.urls = (Array.isArray(iceServer.url) ? iceServer.url.slice() : iceServer.url);
}
// Ensure .url is a single string.
if (hasUrl && Array.isArray(iceServer.url)) {
iceServer.url = iceServer.url[0];
}
}
}
};
// Expose fixRTCOfferOptions.
Adapter.fixRTCOfferOptions = function (options) {
options = options || {};
// New spec.
if (!oldSpecRTCOfferOptions) {
if (options.mandatory && options.mandatory.OfferToReceiveAudio) {
options.offerToReceiveAudio = 1;
}
if (options.mandatory && options.mandatory.OfferToReceiveVideo) {
options.offerToReceiveVideo = 1;
}
delete options.mandatory;
// Old spec.
} else {
if (options.offerToReceiveAudio) {
options.mandatory = options.mandatory || {};
options.mandatory.OfferToReceiveAudio = true;
}
if (options.offerToReceiveVideo) {
options.mandatory = options.mandatory || {};
options.mandatory.OfferToReceiveVideo = true;
}
}
};
return Adapter;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"bowser":36,"debug":29}],33:[function(require,module,exports){
'use strict';
// Expose the RTCPeerConnection class.
module.exports = RTCPeerConnection;
// Dependencies.
var merge = require('merge'),
debug = require('debug')('rtcninja:RTCPeerConnection'),
debugerror = require('debug')('rtcninja:ERROR:RTCPeerConnection'),
Adapter = require('./Adapter'),
// Internal constants.
C = {
REGEXP_NORMALIZED_CANDIDATE: new RegExp(/^candidate:/i),
REGEXP_FIX_CANDIDATE: new RegExp(/(^a=|\r|\n)/gi),
REGEXP_RELAY_CANDIDATE: new RegExp(/ relay /i),
REGEXP_SDP_CANDIDATES: new RegExp(/^a=candidate:.*\r\n/igm),
REGEXP_SDP_NON_RELAY_CANDIDATES: new RegExp(/^a=candidate:(.(?!relay ))*\r\n/igm)
},
// Internal variables.
VAR = {
normalizeCandidate: null
};
debugerror.log = console.warn.bind(console);
// Constructor
function RTCPeerConnection(pcConfig, pcConstraints) {
debug('new | pcConfig: %o', pcConfig);
// Set this.pcConfig and this.options.
setConfigurationAndOptions.call(this, pcConfig);
// NOTE: Deprecated pcConstraints argument.
this.pcConstraints = pcConstraints;
// Own version of the localDescription.
this.ourLocalDescription = null;
// Latest values of PC attributes to avoid events with same value.
this.ourSignalingState = null;
this.ourIceConnectionState = null;
this.ourIceGatheringState = null;
// Timer for options.gatheringTimeout.
this.timerGatheringTimeout = null;
// Timer for options.gatheringTimeoutAfterRelay.
this.timerGatheringTimeoutAfterRelay = null;
// Flag to ignore new gathered ICE candidates.
this.ignoreIceGathering = false;
// Flag set when closed.
this.closed = false;
// Set RTCPeerConnection.
setPeerConnection.call(this);
// Set properties.
setProperties.call(this);
}
// Public API.
RTCPeerConnection.prototype.createOffer = function (successCallback, failureCallback, options) {
debug('createOffer()');
var self = this;
Adapter.fixRTCOfferOptions(options);
this.pc.createOffer(
function (offer) {
if (isClosed.call(self)) {
return;
}
debug('createOffer() | success');
if (successCallback) {
successCallback(offer);
}
},
function (error) {
if (isClosed.call(self)) {
return;
}
debugerror('createOffer() | error:', error);
if (failureCallback) {
failureCallback(error);
}
},
options
);
};
RTCPeerConnection.prototype.createAnswer = function (successCallback, failureCallback, options) {
debug('createAnswer()');
var self = this;
this.pc.createAnswer(
function (answer) {
if (isClosed.call(self)) {
return;
}
debug('createAnswer() | success');
if (successCallback) {
successCallback(answer);
}
},
function (error) {
if (isClosed.call(self)) {
return;
}
debugerror('createAnswer() | error:', error);
if (failureCallback) {
failureCallback(error);
}
},
options
);
};
RTCPeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
debug('setLocalDescription()');
var self = this;
this.pc.setLocalDescription(
description,
// success.
function () {
if (isClosed.call(self)) {
return;
}
debug('setLocalDescription() | success');
// Clear gathering timers.
clearTimeout(self.timerGatheringTimeout);
delete self.timerGatheringTimeout;
clearTimeout(self.timerGatheringTimeoutAfterRelay);
delete self.timerGatheringTimeoutAfterRelay;
runTimerGatheringTimeout();
if (successCallback) {
successCallback();
}
},
// failure
function (error) {
if (isClosed.call(self)) {
return;
}
debugerror('setLocalDescription() | error:', error);
if (failureCallback) {
failureCallback(error);
}
}
);
// Enable (again) ICE gathering.
this.ignoreIceGathering = false;
// Handle gatheringTimeout.
function runTimerGatheringTimeout() {
if (typeof self.options.gatheringTimeout !== 'number') {
return;
}
// If setLocalDescription was already called, it may happen that
// ICE gathering is not needed, so don't run this timer.
if (self.pc.iceGatheringState === 'complete') {
return;
}
debug('setLocalDescription() | ending gathering in %d ms (gatheringTimeout option)',
self.options.gatheringTimeout);
self.timerGatheringTimeout = setTimeout(function () {
if (isClosed.call(self)) {
return;
}
debug('forced end of candidates after gatheringTimeout timeout');
// Clear gathering timers.
delete self.timerGatheringTimeout;
clearTimeout(self.timerGatheringTimeoutAfterRelay);
delete self.timerGatheringTimeoutAfterRelay;
// Ignore new candidates.
self.ignoreIceGathering = true;
if (self.onicecandidate) {
self.onicecandidate({ candidate: null }, null);
}
}, self.options.gatheringTimeout);
}
};
RTCPeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
debug('setRemoteDescription()');
var self = this;
this.pc.setRemoteDescription(
description,
function () {
if (isClosed.call(self)) {
return;
}
debug('setRemoteDescription() | success');
if (successCallback) {
successCallback();
}
},
function (error) {
if (isClosed.call(self)) {
return;
}
debugerror('setRemoteDescription() | error:', error);
if (failureCallback) {
failureCallback(error);
}
}
);
};
RTCPeerConnection.prototype.updateIce = function (pcConfig) {
debug('updateIce() | pcConfig: %o', pcConfig);
// Update this.pcConfig and this.options.
setConfigurationAndOptions.call(this, pcConfig);
this.pc.updateIce(this.pcConfig);
// Enable (again) ICE gathering.
this.ignoreIceGathering = false;
};
RTCPeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
debug('addIceCandidate() | candidate: %o', candidate);
var self = this;
this.pc.addIceCandidate(
candidate,
function () {
if (isClosed.call(self)) {
return;
}
debug('addIceCandidate() | success');
if (successCallback) {
successCallback();
}
},
function (error) {
if (isClosed.call(self)) {
return;
}
debugerror('addIceCandidate() | error:', error);
if (failureCallback) {
failureCallback(error);
}
}
);
};
RTCPeerConnection.prototype.getConfiguration = function () {
debug('getConfiguration()');
return this.pc.getConfiguration();
};
RTCPeerConnection.prototype.getLocalStreams = function () {
debug('getLocalStreams()');
return this.pc.getLocalStreams();
};
RTCPeerConnection.prototype.getRemoteStreams = function () {
debug('getRemoteStreams()');
return this.pc.getRemoteStreams();
};
RTCPeerConnection.prototype.getStreamById = function (streamId) {
debug('getStreamById() | streamId: %s', streamId);
return this.pc.getStreamById(streamId);
};
RTCPeerConnection.prototype.addStream = function (stream) {
debug('addStream() | stream: %s', stream);
this.pc.addStream(stream);
};
RTCPeerConnection.prototype.removeStream = function (stream) {
debug('removeStream() | stream: %o', stream);
this.pc.removeStream(stream);
};
RTCPeerConnection.prototype.close = function () {
debug('close()');
this.closed = true;
// Clear gathering timers.
clearTimeout(this.timerGatheringTimeout);
delete this.timerGatheringTimeout;
clearTimeout(this.timerGatheringTimeoutAfterRelay);
delete this.timerGatheringTimeoutAfterRelay;
this.pc.close();
};
RTCPeerConnection.prototype.createDataChannel = function () {
debug('createDataChannel()');
return this.pc.createDataChannel.apply(this.pc, arguments);
};
RTCPeerConnection.prototype.createDTMFSender = function (track) {
debug('createDTMFSender()');
return this.pc.createDTMFSender(track);
};
RTCPeerConnection.prototype.getStats = function () {
debug('getStats()');
return this.pc.getStats.apply(this.pc, arguments);
};
RTCPeerConnection.prototype.setIdentityProvider = function () {
debug('setIdentityProvider()');
return this.pc.setIdentityProvider.apply(this.pc, arguments);
};
RTCPeerConnection.prototype.getIdentityAssertion = function () {
debug('getIdentityAssertion()');
return this.pc.getIdentityAssertion();
};
RTCPeerConnection.prototype.reset = function (pcConfig) {
debug('reset() | pcConfig: %o', pcConfig);
var pc = this.pc;
// Remove events in the old PC.
pc.onnegotiationneeded = null;
pc.onicecandidate = null;
pc.onaddstream = null;
pc.onremovestream = null;
pc.ondatachannel = null;
pc.onsignalingstatechange = null;
pc.oniceconnectionstatechange = null;
pc.onicegatheringstatechange = null;
pc.onidentityresult = null;
pc.onpeeridentity = null;
pc.onidpassertionerror = null;
pc.onidpvalidationerror = null;
// Clear gathering timers.
clearTimeout(this.timerGatheringTimeout);
delete this.timerGatheringTimeout;
clearTimeout(this.timerGatheringTimeoutAfterRelay);
delete this.timerGatheringTimeoutAfterRelay;
// Silently close the old PC.
debug('reset() | closing current peerConnection');
pc.close();
// Set this.pcConfig and this.options.
setConfigurationAndOptions.call(this, pcConfig);
// Create a new PC.
setPeerConnection.call(this);
};
// Private Helpers.
function setConfigurationAndOptions(pcConfig) {
// Clone pcConfig.
this.pcConfig = merge(true, pcConfig);
// Fix pcConfig.
Adapter.fixPeerConnectionConfig(this.pcConfig);
this.options = {
iceTransportsRelay: (this.pcConfig.iceTransports === 'relay'),
iceTransportsNone: (this.pcConfig.iceTransports === 'none'),
gatheringTimeout: this.pcConfig.gatheringTimeout,
gatheringTimeoutAfterRelay: this.pcConfig.gatheringTimeoutAfterRelay
};
// Remove custom rtcninja.RTCPeerConnection options from pcConfig.
delete this.pcConfig.gatheringTimeout;
delete this.pcConfig.gatheringTimeoutAfterRelay;
debug('setConfigurationAndOptions | processed pcConfig: %o', this.pcConfig);
}
function isClosed() {
return ((this.closed) || (this.pc && this.pc.iceConnectionState === 'closed'));
}
function setEvents() {
var self = this,
pc = this.pc;
pc.onnegotiationneeded = function (event) {
if (isClosed.call(self)) {
return;
}
debug('onnegotiationneeded()');
if (self.onnegotiationneeded) {
self.onnegotiationneeded(event);
}
};
pc.onicecandidate = function (event) {
var candidate, isRelay, newCandidate;
if (isClosed.call(self)) {
return;
}
if (self.ignoreIceGathering) {
return;
}
// Ignore any candidate (event the null one) if iceTransports:'none' is set.
if (self.options.iceTransportsNone) {
return;
}
candidate = event.candidate;
if (candidate) {
isRelay = C.REGEXP_RELAY_CANDIDATE.test(candidate.candidate);
// Ignore if just relay candidates are requested.
if (self.options.iceTransportsRelay && !isRelay) {
return;
}
// Handle gatheringTimeoutAfterRelay.
if (isRelay && !self.timerGatheringTimeoutAfterRelay &&
(typeof self.options.gatheringTimeoutAfterRelay === 'number')) {
debug('onicecandidate() | first relay candidate found, ending gathering in %d ms', self.options.gatheringTimeoutAfterRelay);
self.timerGatheringTimeoutAfterRelay = setTimeout(function () {
if (isClosed.call(self)) {
return;
}
debug('forced end of candidates after timeout');
// Clear gathering timers.
delete self.timerGatheringTimeoutAfterRelay;
clearTimeout(self.timerGatheringTimeout);
delete self.timerGatheringTimeout;
// Ignore new candidates.
self.ignoreIceGathering = true;
if (self.onicecandidate) {
self.onicecandidate({candidate: null}, null);
}
}, self.options.gatheringTimeoutAfterRelay);
}
newCandidate = new Adapter.RTCIceCandidate({
sdpMid: candidate.sdpMid,
sdpMLineIndex: candidate.sdpMLineIndex,
candidate: candidate.candidate
});
// Force correct candidate syntax (just check it once).
if (VAR.normalizeCandidate === null) {
if (C.REGEXP_NORMALIZED_CANDIDATE.test(candidate.candidate)) {
VAR.normalizeCandidate = false;
} else {
debug('onicecandidate() | normalizing ICE candidates syntax (remove "a=" and "\\r\\n")');
VAR.normalizeCandidate = true;
}
}
if (VAR.normalizeCandidate) {
newCandidate.candidate = candidate.candidate.replace(C.REGEXP_FIX_CANDIDATE, '');
}
debug(
'onicecandidate() | m%d(%s) %s',
newCandidate.sdpMLineIndex,
newCandidate.sdpMid || 'no mid', newCandidate.candidate);
if (self.onicecandidate) {
self.onicecandidate(event, newCandidate);
}
// Null candidate (end of candidates).
} else {
debug('onicecandidate() | end of candidates');
// Clear gathering timers.
clearTimeout(self.timerGatheringTimeout);
delete self.timerGatheringTimeout;
clearTimeout(self.timerGatheringTimeoutAfterRelay);
delete self.timerGatheringTimeoutAfterRelay;
if (self.onicecandidate) {
self.onicecandidate(event, null);
}
}
};
pc.onaddstream = function (event) {
if (isClosed.call(self)) {
return;
}
debug('onaddstream() | stream: %o', event.stream);
if (self.onaddstream) {
self.onaddstream(event, event.stream);
}
};
pc.onremovestream = function (event) {
if (isClosed.call(self)) {
return;
}
debug('onremovestream() | stream: %o', event.stream);
if (self.onremovestream) {
self.onremovestream(event, event.stream);
}
};
pc.ondatachannel = function (event) {
if (isClosed.call(self)) {
return;
}
debug('ondatachannel() | datachannel: %o', event.channel);
if (self.ondatachannel) {
self.ondatachannel(event, event.channel);
}
};
pc.onsignalingstatechange = function (event) {
if (pc.signalingState === self.ourSignalingState) {
return;
}
debug('onsignalingstatechange() | signalingState: %s', pc.signalingState);
self.ourSignalingState = pc.signalingState;
if (self.onsignalingstatechange) {
self.onsignalingstatechange(event, pc.signalingState);
}
};
pc.oniceconnectionstatechange = function (event) {
if (pc.iceConnectionState === self.ourIceConnectionState) {
return;
}
debug('oniceconnectionstatechange() | iceConnectionState: %s', pc.iceConnectionState);
self.ourIceConnectionState = pc.iceConnectionState;
if (self.oniceconnectionstatechange) {
self.oniceconnectionstatechange(event, pc.iceConnectionState);
}
};
pc.onicegatheringstatechange = function (event) {
if (isClosed.call(self)) {
return;
}
if (pc.iceGatheringState === self.ourIceGatheringState) {
return;
}
debug('onicegatheringstatechange() | iceGatheringState: %s', pc.iceGatheringState);
self.ourIceGatheringState = pc.iceGatheringState;
if (self.onicegatheringstatechange) {
self.onicegatheringstatechange(event, pc.iceGatheringState);
}
};
pc.onidentityresult = function (event) {
if (isClosed.call(self)) {
return;
}
debug('onidentityresult()');
if (self.onidentityresult) {
self.onidentityresult(event);
}
};
pc.onpeeridentity = function (event) {
if (isClosed.call(self)) {
return;
}
debug('onpeeridentity()');
if (self.onpeeridentity) {
self.onpeeridentity(event);
}
};
pc.onidpassertionerror = function (event) {
if (isClosed.call(self)) {
return;
}
debug('onidpassertionerror()');
if (self.onidpassertionerror) {
self.onidpassertionerror(event);
}
};
pc.onidpvalidationerror = function (event) {
if (isClosed.call(self)) {
return;
}
debug('onidpvalidationerror()');
if (self.onidpvalidationerror) {
self.onidpvalidationerror(event);
}
};
}
function setPeerConnection() {
// Create a RTCPeerConnection.
if (!this.pcConstraints) {
this.pc = new Adapter.RTCPeerConnection(this.pcConfig);
} else {
// NOTE: Deprecated.
this.pc = new Adapter.RTCPeerConnection(this.pcConfig, this.pcConstraints);
}
// Set RTC events.
setEvents.call(this);
}
function getLocalDescription() {
var pc = this.pc,
options = this.options,
sdp = null;
if (!pc.localDescription) {
this.ourLocalDescription = null;
return null;
}
// Mangle the SDP string.
if (options.iceTransportsRelay) {
sdp = pc.localDescription.sdp.replace(C.REGEXP_SDP_NON_RELAY_CANDIDATES, '');
} else if (options.iceTransportsNone) {
sdp = pc.localDescription.sdp.replace(C.REGEXP_SDP_CANDIDATES, '');
}
this.ourLocalDescription = new Adapter.RTCSessionDescription({
type: pc.localDescription.type,
sdp: sdp || pc.localDescription.sdp
});
return this.ourLocalDescription;
}
function setProperties() {
var self = this;
Object.defineProperties(this, {
peerConnection: {
get: function () {
return self.pc;
}
},
signalingState: {
get: function () {
return self.pc.signalingState;
}
},
iceConnectionState: {
get: function () {
return self.pc.iceConnectionState;
}
},
iceGatheringState: {
get: function () {
return self.pc.iceGatheringState;
}
},
localDescription: {
get: function () {
return getLocalDescription.call(self);
}
},
remoteDescription: {
get: function () {
return self.pc.remoteDescription;
}
},
peerIdentity: {
get: function () {
return self.pc.peerIdentity;
}
}
});
}
},{"./Adapter":32,"debug":29,"merge":37}],34:[function(require,module,exports){
'use strict';
module.exports = rtcninja;
// Dependencies.
var browser = require('bowser').browser,
debug = require('debug')('rtcninja'),
debugerror = require('debug')('rtcninja:ERROR'),
version = require('./version'),
Adapter = require('./Adapter'),
RTCPeerConnection = require('./RTCPeerConnection'),
// Internal vars.
called = false;
debugerror.log = console.warn.bind(console);
debug('version %s', version);
debug('detected browser: %s %s [mobile:%s, tablet:%s, android:%s, ios:%s]',
browser.name, browser.version, !!browser.mobile, !!browser.tablet,
!!browser.android, !!browser.ios);
// Constructor.
function rtcninja(options) {
// Load adapter
var iface = Adapter(options || {}); // jshint ignore:line
called = true;
// Expose RTCPeerConnection class.
rtcninja.RTCPeerConnection = RTCPeerConnection;
// Expose WebRTC API and utils.
rtcninja.getUserMedia = iface.getUserMedia;
rtcninja.RTCSessionDescription = iface.RTCSessionDescription;
rtcninja.RTCIceCandidate = iface.RTCIceCandidate;
rtcninja.MediaStreamTrack = iface.MediaStreamTrack;
rtcninja.getMediaDevices = iface.getMediaDevices;
rtcninja.attachMediaStream = iface.attachMediaStream;
rtcninja.closeMediaStream = iface.closeMediaStream;
rtcninja.canRenegotiate = iface.canRenegotiate;
// Log WebRTC support.
if (iface.hasWebRTC()) {
debug('WebRTC supported');
return true;
} else {
debugerror('WebRTC not supported');
return false;
}
}
// Public API.
// If called without calling rtcninja(), call it.
rtcninja.hasWebRTC = function () {
if (!called) {
rtcninja();
}
return Adapter.hasWebRTC();
};
// Expose version property.
Object.defineProperty(rtcninja, 'version', {
get: function () {
return version;
}
});
// Expose called property.
Object.defineProperty(rtcninja, 'called', {
get: function () {
return called;
}
});
// Exposing stuff.
rtcninja.debug = require('debug');
rtcninja.browser = browser;
},{"./Adapter":32,"./RTCPeerConnection":33,"./version":35,"bowser":36,"debug":29}],35:[function(require,module,exports){
'use strict';
// Expose the 'version' field of package.json.
module.exports = require('../package.json').version;
},{"../package.json":38}],36:[function(require,module,exports){
/*!
* Bowser - a browser detector
* https://github.com/ded/bowser
* MIT License | (c) Dustin Diaz 2014
*/
!function (name, definition) {
if (typeof module != 'undefined' && module.exports) module.exports['browser'] = definition()
else if (typeof define == 'function' && define.amd) define(definition)
else this[name] = definition()
}('bowser', function () {
/**
* See useragents.js for examples of navigator.userAgent
*/
var t = true
function detect(ua) {
function getFirstMatch(regex) {
var match = ua.match(regex);
return (match && match.length > 1 && match[1]) || '';
}
function getSecondMatch(regex) {
var match = ua.match(regex);
return (match && match.length > 1 && match[2]) || '';
}
var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase()
, likeAndroid = /like android/i.test(ua)
, android = !likeAndroid && /android/i.test(ua)
, edgeVersion = getFirstMatch(/edge\/(\d+(\.\d+)?)/i)
, versionIdentifier = getFirstMatch(/version\/(\d+(\.\d+)?)/i)
, tablet = /tablet/i.test(ua)
, mobile = !tablet && /[^-]mobi/i.test(ua)
, result
if (/opera|opr/i.test(ua)) {
result = {
name: 'Opera'
, opera: t
, version: versionIdentifier || getFirstMatch(/(?:opera|opr)[\s\/](\d+(\.\d+)?)/i)
}
}
else if (/windows phone/i.test(ua)) {
result = {
name: 'Windows Phone'
, windowsphone: t
}
if (edgeVersion) {
result.msedge = t
result.version = edgeVersion
}
else {
result.msie = t
result.version = getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i)
}
}
else if (/msie|trident/i.test(ua)) {
result = {
name: 'Internet Explorer'
, msie: t
, version: getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i)
}
}
else if (/chrome.+? edge/i.test(ua)) {
result = {
name: 'Microsoft Edge'
, msedge: t
, version: edgeVersion
}
}
else if (/chrome|crios|crmo/i.test(ua)) {
result = {
name: 'Chrome'
, chrome: t
, version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)
}
}
else if (iosdevice) {
result = {
name : iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod'
}
// WTF: version is not part of user agent in web apps
if (versionIdentifier) {
result.version = versionIdentifier
}
}
else if (/sailfish/i.test(ua)) {
result = {
name: 'Sailfish'
, sailfish: t
, version: getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i)
}
}
else if (/seamonkey\//i.test(ua)) {
result = {
name: 'SeaMonkey'
, seamonkey: t
, version: getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i)
}
}
else if (/firefox|iceweasel/i.test(ua)) {
result = {
name: 'Firefox'
, firefox: t
, version: getFirstMatch(/(?:firefox|iceweasel)[ \/](\d+(\.\d+)?)/i)
}
if (/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)) {
result.firefoxos = t
}
}
else if (/silk/i.test(ua)) {
result = {
name: 'Amazon Silk'
, silk: t
, version : getFirstMatch(/silk\/(\d+(\.\d+)?)/i)
}
}
else if (android) {
result = {
name: 'Android'
, version: versionIdentifier
}
}
else if (/phantom/i.test(ua)) {
result = {
name: 'PhantomJS'
, phantom: t
, version: getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i)
}
}
else if (/blackberry|\bbb\d+/i.test(ua) || /rim\stablet/i.test(ua)) {
result = {
name: 'BlackBerry'
, blackberry: t
, version: versionIdentifier || getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i)
}
}
else if (/(web|hpw)os/i.test(ua)) {
result = {
name: 'WebOS'
, webos: t
, version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)
};
/touchpad\//i.test(ua) && (result.touchpad = t)
}
else if (/bada/i.test(ua)) {
result = {
name: 'Bada'
, bada: t
, version: getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i)
};
}
else if (/tizen/i.test(ua)) {
result = {
name: 'Tizen'
, tizen: t
, version: getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i) || versionIdentifier
};
}
else if (/safari/i.test(ua)) {
result = {
name: 'Safari'
, safari: t
, version: versionIdentifier
}
}
else {
result = {
name: getFirstMatch(/^(.*)\/(.*) /),
version: getSecondMatch(/^(.*)\/(.*) /)
};
}
// set webkit or gecko flag for browsers based on these engines
if (!result.msedge && /(apple)?webkit/i.test(ua)) {
result.name = result.name || "Webkit"
result.webkit = t
if (!result.version && versionIdentifier) {
result.version = versionIdentifier
}
} else if (!result.opera && /gecko\//i.test(ua)) {
result.name = result.name || "Gecko"
result.gecko = t
result.version = result.version || getFirstMatch(/gecko\/(\d+(\.\d+)?)/i)
}
// set OS flags for platforms that have multiple browsers
if (!result.msedge && (android || result.silk)) {
result.android = t
} else if (iosdevice) {
result[iosdevice] = t
result.ios = t
}
// OS version extraction
var osVersion = '';
if (result.windowsphone) {
osVersion = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i);
} else if (iosdevice) {
osVersion = getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i);
osVersion = osVersion.replace(/[_\s]/g, '.');
} else if (android) {
osVersion = getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i);
} else if (result.webos) {
osVersion = getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i);
} else if (result.blackberry) {
osVersion = getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i);
} else if (result.bada) {
osVersion = getFirstMatch(/bada\/(\d+(\.\d+)*)/i);
} else if (result.tizen) {
osVersion = getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i);
}
if (osVersion) {
result.osversion = osVersion;
}
// device type extraction
var osMajorVersion = osVersion.split('.')[0];
if (tablet || iosdevice == 'ipad' || (android && (osMajorVersion == 3 || (osMajorVersion == 4 && !mobile))) || result.silk) {
result.tablet = t
} else if (mobile || iosdevice == 'iphone' || iosdevice == 'ipod' || android || result.blackberry || result.webos || result.bada) {
result.mobile = t
}
// Graded Browser Support
// http://developer.yahoo.com/yui/articles/gbs
if (result.msedge ||
(result.msie && result.version >= 10) ||
(result.chrome && result.version >= 20) ||
(result.firefox && result.version >= 20.0) ||
(result.safari && result.version >= 6) ||
(result.opera && result.version >= 10.0) ||
(result.ios && result.osversion && result.osversion.split(".")[0] >= 6) ||
(result.blackberry && result.version >= 10.1)
) {
result.a = t;
}
else if ((result.msie && result.version < 10) ||
(result.chrome && result.version < 20) ||
(result.firefox && result.version < 20.0) ||
(result.safari && result.version < 6) ||
(result.opera && result.version < 10.0) ||
(result.ios && result.osversion && result.osversion.split(".")[0] < 6)
) {
result.c = t
} else result.x = t
return result
}
var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent : '')
bowser.test = function (browserList) {
for (var i = 0; i < browserList.length; ++i) {
var browserItem = browserList[i];
if (typeof browserItem=== 'string') {
if (browserItem in bowser) {
return true;
}
}
}
return false;
}
/*
* Set our detect method to the main bowser object so we can
* reuse it to test other user agents.
* This is needed to implement future tests.
*/
bowser._detect = detect;
return bowser
});
},{}],37:[function(require,module,exports){
/*!
* @name JavaScript/NodeJS Merge v1.2.0
* @author yeikos
* @repository https://github.com/yeikos/js.merge
* Copyright 2014 yeikos - MIT license
* https://raw.github.com/yeikos/js.merge/master/LICENSE
*/
;(function(isNode) {
/**
* Merge one or more objects
* @param bool? clone
* @param mixed,... arguments
* @return object
*/
var Public = function(clone) {
return merge(clone === true, false, arguments);
}, publicName = 'merge';
/**
* Merge two or more objects recursively
* @param bool? clone
* @param mixed,... arguments
* @return object
*/
Public.recursive = function(clone) {
return merge(clone === true, true, arguments);
};
/**
* Clone the input removing any reference
* @param mixed input
* @return mixed
*/
Public.clone = function(input) {
var output = input,
type = typeOf(input),
index, size;
if (type === 'array') {
output = [];
size = input.length;
for (index=0;index<size;++index)
output[index] = Public.clone(input[index]);
} else if (type === 'object') {
output = {};
for (index in input)
output[index] = Public.clone(input[index]);
}
return output;
};
/**
* Merge two objects recursively
* @param mixed input
* @param mixed extend
* @return mixed
*/
function merge_recursive(base, extend) {
if (typeOf(base) !== 'object')
return extend;
for (var key in extend) {
if (typeOf(base[key]) === 'object' && typeOf(extend[key]) === 'object') {
base[key] = merge_recursive(base[key], extend[key]);
} else {
base[key] = extend[key];
}
}
return base;
}
/**
* Merge two or more objects
* @param bool clone
* @param bool recursive
* @param array argv
* @return object
*/
function merge(clone, recursive, argv) {
var result = argv[0],
size = argv.length;
if (clone || typeOf(result) !== 'object')
result = {};
for (var index=0;index<size;++index) {
var item = argv[index],
type = typeOf(item);
if (type !== 'object') continue;
for (var key in item) {
var sitem = clone ? Public.clone(item[key]) : item[key];
if (recursive) {
result[key] = merge_recursive(result[key], sitem);
} else {
result[key] = sitem;
}
}
}
return result;
}
/**
* Get type of variable
* @param mixed input
* @return string
*
* @see http://jsperf.com/typeofvar
*/
function typeOf(input) {
return ({}).toString.call(input).slice(8, -1).toLowerCase();
}
if (isNode) {
module.exports = Public;
} else {
window[publicName] = Public;
}
})(typeof module === 'object' && module && typeof module.exports === 'object' && module.exports);
},{}],38:[function(require,module,exports){
module.exports={
"name": "rtcninja",
"version": "0.6.1",
"description": "WebRTC API wrapper to deal with different browsers",
"author": {
"name": "Iñaki Baz Castillo",
"email": "[email protected]",
"url": "http://eface2face.com"
},
"contributors": [
{
"name": "Jesús Pérez",
"email": "[email protected]"
}
],
"license": "MIT",
"main": "lib/rtcninja.js",
"homepage": "https://github.com/eface2face/rtcninja.js",
"repository": {
"type": "git",
"url": "https://github.com/eface2face/rtcninja.js.git"
},
"keywords": [
"webrtc"
],
"engines": {
"node": ">=0.10.32"
},
"dependencies": {
"bowser": "^0.7.3",
"debug": "^2.2.0",
"merge": "^1.2.0"
},
"devDependencies": {
"browserify": "^10.2.3",
"gulp": "git+https://github.com/gulpjs/gulp.git#4.0",
"gulp-expect-file": "0.0.7",
"gulp-filelog": "^0.4.1",
"gulp-header": "^1.2.2",
"gulp-jscs": "^1.6.0",
"gulp-jscs-stylish": "^1.1.0",
"gulp-jshint": "^1.11.0",
"gulp-rename": "^1.2.2",
"gulp-uglify": "^1.2.0",
"jshint-stylish": "^1.0.2",
"retire": "^1.1.0",
"shelljs": "^0.5.0",
"vinyl-source-stream": "^1.1.0"
},
"readme": "# rtcninja.js <img src=\"http://www.pubnub.com/blog/wp-content/uploads/2014/01/google-webrtc-logo.png\" height=\"30\" width=\"30\">\nWebRTC API wrapper to deal with different browsers transparently, [eventually](http://iswebrtcreadyyet.com/) this library shouldn't be needed. We only have to wait until W3C group in charge [finishes the specification](https://tools.ietf.org/wg/rtcweb/) and the different browsers implement it correctly :sweat_smile:.\n\n<img src=\"http://images4.fanpop.com/image/photos/21800000/browser-fight-google-chrome-21865454-600-531.jpg\" height=\"250\" width=\"250\">\n\nSupported environments:\n- [Google Chrome](https://www.google.com/chrome/browser/desktop/index.html) (desktop & mobile)\n- [Google Canary](https://www.google.com/chrome/browser/canary.html) (desktop & mobile)\n- [Mozilla Firefox](https://www.mozilla.org/en-GB/firefox/new) (desktop & mobile)\n- [Firefox Nigthly](https://nightly.mozilla.org/) (desktop & mobile)\n- [Opera](http://www.opera.com/)\n- [Vivaldi](https://vivaldi.com/)\n- [CrossWalk](https://crosswalk-project.org/)\n- [Cordova](cordova.apache.org): iOS support, you only have to use our plugin [following these steps](https://github.com/eface2face/cordova-plugin-iosrtc#usage).\n- [Node-webkit](https://github.com/nwjs/nw.js/)\n\n\n## Installation\n\n### **npm**:\n```bash\n$ npm install rtcninja\n```\n#### Usage\n```javascript\nvar rtcninja = require('rtcninja');\n```\n\n### **bower**:\n```bash\n$ bower install rtcninja\n```\n\n\n## Transpiled library\n\nTake a browserified version of the library from the `dist/` folder:\n\n* `dist/rtcninja-X.Y.Z.js`: The uncompressed version.\n* `dist/rtcninja-X.Y.Z.min.js`: The compressed production-ready version.\n* `dist/rtcninja.js`: A copy of the uncompressed version.\n* `dist/rtcninja.min.js`: A copy of the compressed version.\n\nThey expose the global `window.rtcninja` module.\n\n\n## Usage\n\nIn the [examples](./examples/) folder we provide a complete one.\n\n```javascript\n// Must first call it.\nrtcninja();\n\n// Then check.\nif (rtcninja.hasWebRTC()) {\n // Do something.\n}\nelse {\n // Do something.\n}\n```\n\n\n## Documentation\n\nYou can read the full [API documentation](docs/index.md) in the docs folder.\n\n\n## Issues\nhttps://github.com/eface2face/rtcninja.js/issues\n\n\n## Developer guide\n\n- Create a branch with a name including your user and a meaningful word about the fix/feature you're going to implement, ie: \"jesusprubio/fixstuff\"\n- Use [GitHub pull requests](https://help.github.com/articles/using-pull-requests).\n- Conventions:\n - We use [JSHint](http://jshint.com/) and [Crockford's Styleguide](http://javascript.crockford.com/code.html).\n - Please run `grunt lint` to be sure your code fits with them.\n\n### Debugging\n\nThe library includes the Node [debug](https://github.com/visionmedia/debug) module. In order to enable debugging:\n\nIn Node set the `DEBUG=rtcninja*` environment variable before running the application, or set it at the top of the script:\n\n```javascript\nprocess.env.DEBUG = 'rtcninja*';\n```\n\nIn the browser run `rtcninja.debug.enable('rtcninja*');` and reload the page. Note that the debugging settings are stored into the browser LocalStorage. To disable it run `rtcninja.debug.disable('rtcninja*');`.\n\n\n## Copyright & License\n\n* eFace2Face Inc.\n* [MIT](./LICENSE)",
"readmeFilename": "README.md",
"gitHead": "8fba936eb9d38e72dd9c2b79b9cc49ebebcef33a",
"bugs": {
"url": "https://github.com/eface2face/rtcninja.js/issues"
},
"_id": "[email protected]",
"scripts": {},
"_shasum": "4adcdf139d42809db6026138a6f2920fa21b820f",
"_from": "rtcninja@>=0.6.1 <0.7.0"
}
},{}],39:[function(require,module,exports){
var grammar = module.exports = {
v: [{
name: 'version',
reg: /^(\d*)$/
}],
o: [{ //o=- 20518 0 IN IP4 203.0.113.1
// NB: sessionId will be a String in most cases because it is huge
name: 'origin',
reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
format: "%s %s %d %s IP%d %s"
}],
// default parsing of these only (though some of these feel outdated)
s: [{ name: 'name' }],
i: [{ name: 'description' }],
u: [{ name: 'uri' }],
e: [{ name: 'email' }],
p: [{ name: 'phone' }],
z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
//k: [{}], // outdated thing ignored
t: [{ //t=0 0
name: 'timing',
reg: /^(\d*) (\d*)/,
names: ['start', 'stop'],
format: "%d %d"
}],
c: [{ //c=IN IP4 10.47.197.26
name: 'connection',
reg: /^IN IP(\d) (\S*)/,
names: ['version', 'ip'],
format: "IN IP%d %s"
}],
b: [{ //b=AS:4000
push: 'bandwidth',
reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
names: ['type', 'limit'],
format: "%s:%s"
}],
m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
// NB: special - pushes to session
// TODO: rtp/fmtp should be filtered by the payloads found here?
reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
names: ['type', 'port', 'protocol', 'payloads'],
format: "%s %d %s %s"
}],
a: [
{ //a=rtpmap:110 opus/48000/2
push: 'rtp',
reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
names: ['payload', 'codec', 'rate', 'encoding'],
format: function (o) {
return (o.encoding) ?
"rtpmap:%d %s/%s/%s":
"rtpmap:%d %s/%s";
}
},
{ //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
push: 'fmtp',
reg: /^fmtp:(\d*) (\S*)/,
names: ['payload', 'config'],
format: "fmtp:%d %s"
},
{ //a=control:streamid=0
name: 'control',
reg: /^control:(.*)/,
format: "control:%s"
},
{ //a=rtcp:65179 IN IP4 193.84.77.194
name: 'rtcp',
reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
names: ['port', 'netType', 'ipVer', 'address'],
format: function (o) {
return (o.address != null) ?
"rtcp:%d %s IP%d %s":
"rtcp:%d";
}
},
{ //a=rtcp-fb:98 trr-int 100
push: 'rtcpFbTrrInt',
reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
names: ['payload', 'value'],
format: "rtcp-fb:%d trr-int %d"
},
{ //a=rtcp-fb:98 nack rpsi
push: 'rtcpFb',
reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
names: ['payload', 'type', 'subtype'],
format: function (o) {
return (o.subtype != null) ?
"rtcp-fb:%s %s %s":
"rtcp-fb:%s %s";
}
},
{ //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
//a=extmap:1/recvonly URI-gps-string
push: 'ext',
reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
names: ['value', 'uri', 'config'], // value may include "/direction" suffix
format: function (o) {
return (o.config != null) ?
"extmap:%s %s %s":
"extmap:%s %s";
}
},
{
//a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
push: 'crypto',
reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
names: ['id', 'suite', 'config', 'sessionConfig'],
format: function (o) {
return (o.sessionConfig != null) ?
"crypto:%d %s %s %s":
"crypto:%d %s %s";
}
},
{ //a=setup:actpass
name: 'setup',
reg: /^setup:(\w*)/,
format: "setup:%s"
},
{ //a=mid:1
name: 'mid',
reg: /^mid:([^\s]*)/,
format: "mid:%s"
},
{ //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
name: 'msid',
reg: /^msid:(.*)/,
format: "msid:%s"
},
{ //a=ptime:20
name: 'ptime',
reg: /^ptime:(\d*)/,
format: "ptime:%d"
},
{ //a=maxptime:60
name: 'maxptime',
reg: /^maxptime:(\d*)/,
format: "maxptime:%d"
},
{ //a=sendrecv
name: 'direction',
reg: /^(sendrecv|recvonly|sendonly|inactive)/
},
{ //a=ice-lite
name: 'icelite',
reg: /^(ice-lite)/
},
{ //a=ice-ufrag:F7gI
name: 'iceUfrag',
reg: /^ice-ufrag:(\S*)/,
format: "ice-ufrag:%s"
},
{ //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
name: 'icePwd',
reg: /^ice-pwd:(\S*)/,
format: "ice-pwd:%s"
},
{ //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
name: 'fingerprint',
reg: /^fingerprint:(\S*) (\S*)/,
names: ['type', 'hash'],
format: "fingerprint:%s %s"
},
{
//a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
//a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
//a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
push:'candidates',
reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
format: function (o) {
var str = "candidate:%s %d %s %d %s %d typ %s";
// NB: candidate has two optional chunks, so %void middle one if it's missing
str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
if (o.generation != null) {
str += " generation %d";
}
return str;
}
},
{ //a=end-of-candidates (keep after the candidates line for readability)
name: 'endOfCandidates',
reg: /^(end-of-candidates)/
},
{ //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
name: 'remoteCandidates',
reg: /^remote-candidates:(.*)/,
format: "remote-candidates:%s"
},
{ //a=ice-options:google-ice
name: 'iceOptions',
reg: /^ice-options:(\S*)/,
format: "ice-options:%s"
},
{ //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
push: "ssrcs",
reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
names: ['id', 'attribute', 'value'],
format: "ssrc:%d %s:%s"
},
{ //a=ssrc-group:FEC 1 2
push: "ssrcGroups",
reg: /^ssrc-group:(\w*) (.*)/,
names: ['semantics', 'ssrcs'],
format: "ssrc-group:%s %s"
},
{ //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
name: "msidSemantic",
reg: /^msid-semantic:\s?(\w*) (\S*)/,
names: ['semantic', 'token'],
format: "msid-semantic: %s %s" // space after ":" is not accidental
},
{ //a=group:BUNDLE audio video
push: 'groups',
reg: /^group:(\w*) (.*)/,
names: ['type', 'mids'],
format: "group:%s %s"
},
{ //a=rtcp-mux
name: 'rtcpMux',
reg: /^(rtcp-mux)/
},
{ //a=rtcp-rsize
name: 'rtcpRsize',
reg: /^(rtcp-rsize)/
},
{ // any a= that we don't understand is kepts verbatim on media.invalid
push: 'invalid',
names: ["value"]
}
]
};
// set sensible defaults to avoid polluting the grammar with boring details
Object.keys(grammar).forEach(function (key) {
var objs = grammar[key];
objs.forEach(function (obj) {
if (!obj.reg) {
obj.reg = /(.*)/;
}
if (!obj.format) {
obj.format = "%s";
}
});
});
},{}],40:[function(require,module,exports){
var parser = require('./parser');
var writer = require('./writer');
exports.write = writer;
exports.parse = parser.parse;
exports.parseFmtpConfig = parser.parseFmtpConfig;
exports.parsePayloads = parser.parsePayloads;
exports.parseRemoteCandidates = parser.parseRemoteCandidates;
},{"./parser":41,"./writer":42}],41:[function(require,module,exports){
var toIntIfInt = function (v) {
return String(Number(v)) === v ? Number(v) : v;
};
var attachProperties = function (match, location, names, rawName) {
if (rawName && !names) {
location[rawName] = toIntIfInt(match[1]);
}
else {
for (var i = 0; i < names.length; i += 1) {
if (match[i+1] != null) {
location[names[i]] = toIntIfInt(match[i+1]);
}
}
}
};
var parseReg = function (obj, location, content) {
var needsBlank = obj.name && obj.names;
if (obj.push && !location[obj.push]) {
location[obj.push] = [];
}
else if (needsBlank && !location[obj.name]) {
location[obj.name] = {};
}
var keyLocation = obj.push ?
{} : // blank object that will be pushed
needsBlank ? location[obj.name] : location; // otherwise, named location or root
attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
if (obj.push) {
location[obj.push].push(keyLocation);
}
};
var grammar = require('./grammar');
var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
exports.parse = function (sdp) {
var session = {}
, media = []
, location = session; // points at where properties go under (one of the above)
// parse lines we understand
sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
var type = l[0];
var content = l.slice(2);
if (type === 'm') {
media.push({rtp: [], fmtp: []});
location = media[media.length-1]; // point at latest media line
}
for (var j = 0; j < (grammar[type] || []).length; j += 1) {
var obj = grammar[type][j];
if (obj.reg.test(content)) {
return parseReg(obj, location, content);
}
}
});
session.media = media; // link it up
return session;
};
var fmtpReducer = function (acc, expr) {
var s = expr.split('=');
if (s.length === 2) {
acc[s[0]] = toIntIfInt(s[1]);
}
return acc;
};
exports.parseFmtpConfig = function (str) {
return str.split(';').reduce(fmtpReducer, {});
};
exports.parsePayloads = function (str) {
return str.split(' ').map(Number);
};
exports.parseRemoteCandidates = function (str) {
var candidates = [];
var parts = str.split(' ').map(toIntIfInt);
for (var i = 0; i < parts.length; i += 3) {
candidates.push({
component: parts[i],
ip: parts[i + 1],
port: parts[i + 2]
});
}
return candidates;
};
},{"./grammar":39}],42:[function(require,module,exports){
var grammar = require('./grammar');
// customized util.format - discards excess arguments and can void middle ones
var formatRegExp = /%[sdv%]/g;
var format = function (formatStr) {
var i = 1;
var args = arguments;
var len = args.length;
return formatStr.replace(formatRegExp, function (x) {
if (i >= len) {
return x; // missing argument
}
var arg = args[i];
i += 1;
switch (x) {
case '%%':
return '%';
case '%s':
return String(arg);
case '%d':
return Number(arg);
case '%v':
return '';
}
});
// NB: we discard excess arguments - they are typically undefined from makeLine
};
var makeLine = function (type, obj, location) {
var str = obj.format instanceof Function ?
(obj.format(obj.push ? location : location[obj.name])) :
obj.format;
var args = [type + '=' + str];
if (obj.names) {
for (var i = 0; i < obj.names.length; i += 1) {
var n = obj.names[i];
if (obj.name) {
args.push(location[obj.name][n]);
}
else { // for mLine and push attributes
args.push(location[obj.names[i]]);
}
}
}
else {
args.push(location[obj.name]);
}
return format.apply(null, args);
};
// RFC specified order
// TODO: extend this with all the rest
var defaultOuterOrder = [
'v', 'o', 's', 'i',
'u', 'e', 'p', 'c',
'b', 't', 'r', 'z', 'a'
];
var defaultInnerOrder = ['i', 'c', 'b', 'a'];
module.exports = function (session, opts) {
opts = opts || {};
// ensure certain properties exist
if (session.version == null) {
session.version = 0; // "v=0" must be there (only defined version atm)
}
if (session.name == null) {
session.name = " "; // "s= " must be there if no meaningful name set
}
session.media.forEach(function (mLine) {
if (mLine.payloads == null) {
mLine.payloads = "";
}
});
var outerOrder = opts.outerOrder || defaultOuterOrder;
var innerOrder = opts.innerOrder || defaultInnerOrder;
var sdp = [];
// loop through outerOrder for matching properties on session
outerOrder.forEach(function (type) {
grammar[type].forEach(function (obj) {
if (obj.name in session && session[obj.name] != null) {
sdp.push(makeLine(type, obj, session));
}
else if (obj.push in session && session[obj.push] != null) {
session[obj.push].forEach(function (el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
// then for each media line, follow the innerOrder
session.media.forEach(function (mLine) {
sdp.push(makeLine('m', grammar.m[0], mLine));
innerOrder.forEach(function (type) {
grammar[type].forEach(function (obj) {
if (obj.name in mLine && mLine[obj.name] != null) {
sdp.push(makeLine(type, obj, mLine));
}
else if (obj.push in mLine && mLine[obj.push] != null) {
mLine[obj.push].forEach(function (el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
});
return sdp.join('\r\n') + '\r\n';
};
},{"./grammar":39}],43:[function(require,module,exports){
var _global = (function() { return this; })();
var nativeWebSocket = _global.WebSocket || _global.MozWebSocket;
/**
* Expose a W3C WebSocket class with just one or two arguments.
*/
function W3CWebSocket(uri, protocols) {
var native_instance;
if (protocols) {
native_instance = new nativeWebSocket(uri, protocols);
}
else {
native_instance = new nativeWebSocket(uri);
}
/**
* 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket
* class). Since it is an Object it will be returned as it is when creating an
* instance of W3CWebSocket via 'new W3CWebSocket()'.
*
* ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2
*/
return native_instance;
}
/**
* Module exports.
*/
module.exports = {
'w3cwebsocket' : nativeWebSocket ? W3CWebSocket : null,
'version' : require('./version')
};
},{"./version":44}],44:[function(require,module,exports){
module.exports = require('../package.json').version;
},{"../package.json":45}],45:[function(require,module,exports){
module.exports={
"name": "websocket",
"description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",
"keywords": [
"websocket",
"websockets",
"socket",
"networking",
"comet",
"push",
"RFC-6455",
"realtime",
"server",
"client"
],
"author": {
"name": "Brian McKelvey",
"email": "[email protected]",
"url": "https://www.worlize.com/"
},
"version": "1.0.19",
"repository": {
"type": "git",
"url": "git+https://github.com/theturtle32/WebSocket-Node.git"
},
"homepage": "https://github.com/theturtle32/WebSocket-Node",
"engines": {
"node": ">=0.8.0"
},
"dependencies": {
"debug": "~2.1.0",
"nan": "1.8.x",
"typedarray-to-buffer": "~3.0.0"
},
"devDependencies": {
"buffer-equal": "0.0.1",
"faucet": "0.0.1",
"gulp": "git+https://github.com/gulpjs/gulp.git#4.0",
"gulp-jshint": "^1.9.0",
"jshint-stylish": "^1.0.0",
"tape": "^3.0.0"
},
"config": {
"verbose": false
},
"scripts": {
"install": "(node-gyp rebuild 2> builderror.log) || (exit 0)",
"test": "faucet test/unit",
"gulp": "gulp"
},
"main": "index",
"directories": {
"lib": "./lib"
},
"browser": "lib/browser.js",
"license": "Apache-2.0",
"gitHead": "da3bd5b04e9442c84881b2e9c13432cdbbae1f16",
"bugs": {
"url": "https://github.com/theturtle32/WebSocket-Node/issues"
},
"_id": "[email protected]",
"_shasum": "e62dbf1a3c5e0767425db7187cfa38f921dfb42c",
"_from": "websocket@>=1.0.19 <2.0.0",
"_npmVersion": "2.10.1",
"_nodeVersion": "0.12.4",
"_npmUser": {
"name": "theturtle32",
"email": "[email protected]"
},
"maintainers": [
{
"name": "theturtle32",
"email": "[email protected]"
}
],
"dist": {
"shasum": "e62dbf1a3c5e0767425db7187cfa38f921dfb42c",
"tarball": "http://registry.npmjs.org/websocket/-/websocket-1.0.19.tgz"
},
"_resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.19.tgz"
}
},{}],46:[function(require,module,exports){
module.exports={
"name": "jssip",
"title": "JsSIP",
"description": "the Javascript SIP library",
"version": "0.6.29",
"homepage": "http://jssip.net",
"author": "José Luis Millán <[email protected]> (https://github.com/jmillan)",
"contributors": [
"Iñaki Baz Castillo <[email protected]> (https://github.com/ibc)",
"Saúl Ibarra Corretgé <[email protected]> (https://github.com/saghul)"
],
"main": "lib/JsSIP.js",
"keywords": [
"sip",
"websocket",
"webrtc",
"node",
"browser",
"library"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/versatica/JsSIP.git"
},
"bugs": {
"url": "https://github.com/versatica/JsSIP/issues"
},
"dependencies": {
"debug": "^2.2.0",
"rtcninja": "^0.6.1",
"sdp-transform": "~1.4.0",
"websocket": "^1.0.19"
},
"devDependencies": {
"browserify": "^10.2.3",
"gulp": "git+https://github.com/gulpjs/gulp.git#4.0",
"gulp-expect-file": "0.0.7",
"gulp-filelog": "^0.4.1",
"gulp-header": "^1.2.2",
"gulp-jshint": "^1.11.0",
"gulp-nodeunit-runner": "^0.2.2",
"gulp-rename": "^1.2.2",
"gulp-uglify": "^1.2.0",
"gulp-util": "^3.0.5",
"jshint-stylish": "^1.0.1",
"pegjs": "0.7.0",
"vinyl-source-stream": "^1.1.0"
},
"scripts": {
"test": "gulp test"
}
}
},{}]},{},[7])(7)
}); |
actor-apps/app-web/src/app/components/ToolbarSection.react.js | VikingDen/actor-platform | import React from 'react';
import ReactMixin from 'react-mixin';
import { IntlMixin } from 'react-intl';
import classnames from 'classnames';
import ActivityActionCreators from 'actions/ActivityActionCreators';
import DialogStore from 'stores/DialogStore';
import ActivityStore from 'stores/ActivityStore';
//import AvatarItem from 'components/common/AvatarItem.react';
const getStateFromStores = () => {
return {
dialogInfo: DialogStore.getSelectedDialogInfo(),
isActivityOpen: ActivityStore.isOpen()
};
};
@ReactMixin.decorate(IntlMixin)
class ToolbarSection extends React.Component {
state = {
dialogInfo: null,
isActivityOpen: false
};
constructor(props) {
super(props);
DialogStore.addSelectedChangeListener(this.onChange);
ActivityStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
DialogStore.removeSelectedChangeListener(this.onChange);
ActivityStore.removeChangeListener(this.onChange);
}
onClick = () => {
if (!this.state.isActivityOpen) {
ActivityActionCreators.show();
} else {
ActivityActionCreators.hide();
}
};
onChange = () => {
this.setState(getStateFromStores());
};
render() {
const info = this.state.dialogInfo;
const isActivityOpen = this.state.isActivityOpen;
let infoButtonClassName = classnames('button button--icon', {
'button--active': isActivityOpen
});
if (info != null) {
return (
<header className="toolbar">
<div className="pull-left">
<div className="toolbar__peer row">
<div className="toolbar__peer__body col-xs">
<span className="toolbar__peer__title">{info.name}</span>
<span className="toolbar__peer__presence">{info.presence}</span>
</div>
</div>
</div>
<div className="toolbar__controls pull-right">
<div className="toolbar__controls__search pull-left hide">
<i className="material-icons">search</i>
<input className="input input--search" placeholder={this.getIntlMessage('search')} type="search"/>
</div>
<div className="toolbar__controls__buttons pull-right">
<button className={infoButtonClassName} onClick={this.onClick}>
<i className="material-icons">info</i>
</button>
<button className="button button--icon hide">
<i className="material-icons">more_vert</i>
</button>
</div>
</div>
</header>
);
} else {
return (
<header className="toolbar">
</header>
);
}
}
}
export default ToolbarSection;
|
client/tests/commonComponents/dashboard.spec.js | FlevianK/cp2-document-management-system | import expect from 'expect';
import React from 'react';
import App from '../../src/components/common/Dashboard';
import { shallow, mount } from 'enzyme';
describe('Dashboard component', () => {
it('renders div', () => {
const wrapper = shallow(<App />);
expect(wrapper.find('div').length).toBe(1);
});
});
|
server/sonar-web/src/main/js/apps/users/components/__tests__/UsersSelectSearchOption-test.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { shallow } from 'enzyme';
import UsersSelectSearchOption from '../UsersSelectSearchOption';
const user = {
login: 'admin',
name: 'Administrator',
avatar: '7daf6c79d4802916d83f6266e24850af'
};
const user2 = {
login: 'admin',
name: 'Administrator',
email: '[email protected]'
};
it('should render correctly without all parameters', () => {
const wrapper = shallow(
<UsersSelectSearchOption option={user}>{user.name}</UsersSelectSearchOption>
);
expect(wrapper).toMatchSnapshot();
});
it('should render correctly with email instead of hash', () => {
const wrapper = shallow(
<UsersSelectSearchOption option={user2}>{user.name}</UsersSelectSearchOption>
);
expect(wrapper).toMatchSnapshot();
});
|
src/Jumbotron.js | westonplatter/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import CustomPropTypes from './utils/CustomPropTypes';
const Jumbotron = React.createClass({
propTypes: {
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return { componentClass: 'div' };
},
render() {
const ComponentClass = this.props.componentClass;
return (
<ComponentClass {...this.props} className={classNames(this.props.className, 'jumbotron')}>
{this.props.children}
</ComponentClass>
);
}
});
export default Jumbotron;
|
packages/material-ui-icons/src/TheatersSharp.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M18 3v2h-2V3H8v2H6V3H4v18h2v-2h2v2h8v-2h2v2h2V3h-2zM8 17H6v-2h2v2zm0-4H6v-2h2v2zm0-4H6V7h2v2zm10 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z" />
, 'TheatersSharp');
|
src/components/views/Organization/ReceiveGoodsForm.js | jennywin/donate-for-good | import React, { Component } from 'react';
export default class ReceiveGoodsForm extends Component {
render() {
return (
<div id="receive_goods_form" className="page">
<div className="page__header">
<h2 className="page__heading">I would like to receive</h2>
</div>
<div className="page__body">
<form className="form">
<div className="checkbox">
<input type="checkbox" id="appliances" className="checkbox__input" />
<label className="checkbox__label" htmlFor="appliances">Appliances</label>
</div>
<div className="checkbox">
<input type="checkbox" id="accessories" className="checkbox__input" />
<label className="checkbox__label" htmlFor="accessories">Accessories</label>
</div>
<div className="checkbox">
<input type="checkbox" id="baby-children-items" className="checkbox__input" />
<label className="checkbox__label" htmlFor="baby-children-items">Baby & Children Items</label>
</div>
<div className="checkbox">
<input type="checkbox" id="beauty" className="checkbox__input" />
<label className="checkbox__label" htmlFor="beauty">Beauty</label>
</div>
<div className="checkbox">
<input type="checkbox" id="bikes" className="checkbox__input" />
<label className="checkbox__label" htmlFor="bikes">Bikes</label>
</div>
<div className="checkbox">
<input type="checkbox" id="books" className="checkbox__input" />
<label className="checkbox__label" htmlFor="books">Books</label>
</div>
<div className="checkbox">
<input type="checkbox" id="cell-phones" className="checkbox__input" />
<label className="checkbox__label" htmlFor="cell-phones">Cell Phones</label>
</div>
<div className="checkbox">
<input type="checkbox" id="electronics-computers" className="checkbox__input" />
<label className="checkbox__label" htmlFor="electronics-computers">Electronics / Computers</label>
</div>
<div className="checkbox">
<input type="checkbox" id="furniture" className="checkbox__input" />
<label className="checkbox__label" htmlFor="furniture">Furniture</label>
</div>
<div className="checkbox">
<input type="checkbox" id="household-items" className="checkbox__input" />
<label className="checkbox__label" htmlFor="household-items">Household items</label>
</div>
<div className="checkbox">
<input type="checkbox" id="toys-games" className="checkbox__input" />
<label className="checkbox__label" htmlFor="toys-games">Toys & Games</label>
</div>
<button className="button button--primary">Confirm Selections</button>
</form>
</div>
</div>
);
}
}
|
app/components/modules/code.module/index.js | omeryagmurlu/algoriv | import React from 'react';
import PropTypes from 'prop-types';
import { themedStyle, ifModuleEnabled } from 'app/utils';
import style from './style.scss';
const css = themedStyle(style);
const Code = props => {
const lineTags = Array(props.code.length).fill('');
props.highlights.forEach((idx => (lineTags[idx] = css('active'))));
const lines = props.code.map((line, i) => <p key={line + i} className={lineTags[i]}>{line}</p>); // eslint-disable-line max-len, react/no-array-index-key
return ifModuleEnabled('code', props,
<div className={css('code', props.theme)}>
{lines}
</div>
);
};
Code.defaultProps = {
highlights: []
};
Code.propTypes = {
code: PropTypes.arrayOf(PropTypes.string).isRequired,
theme: PropTypes.string.isRequired,
highlights: PropTypes.arrayOf(PropTypes.number),
};
export default Code;
|
ajax/libs/forerunnerdb/1.3.641/fdb-core+views.js | dlueth/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('./core'),
View = _dereq_('../lib/View');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":7,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Crc,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback(); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted});
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
self.chainSend('insert', doc, {index: index});
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
case '2d':
index = new Index2d(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":8,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],6:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
/**
* Creates a new collectionGroup instance or returns an existing
* instance if one already exists with the passed name.
* @func collectionGroup
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.collectionGroup = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof CollectionGroup) {
return name;
}
if (this._collectionGroup && this._collectionGroup[name]) {
return this._collectionGroup[name];
}
this._collectionGroup[name] = new CollectionGroup(name).db(this);
self.emit('create', self._collectionGroup[name], 'collectionGroup', name);
return this._collectionGroup[name];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":5,"./Shared":31}],7:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],8:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],9:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":31}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, data, options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":27}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":27}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload: ', def);
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":31}],29:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":31}],30:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Handler for Date() objects
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
// Handler for RegExp() objects
this.registerEncoder('$regexp', function (data) {
if (data instanceof RegExp) {
return {
source: data.source,
params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '')
};
}
});
this.registerDecoder('$regexp', function (data) {
var type = typeof data;
if (type === 'object') {
return new RegExp(data.source, data.params);
} else if (type === 'string') {
return new RegExp(data);
}
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
if (data) {
return this._parse(JSON.parse(data));
}
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],31:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.641',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}],33:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload');
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
// Hook our own join change event and refresh after change
this.on('joinChange', function () {
self.refresh();
});
};
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this.publicData().findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
// Check if we have an existing reactor io
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData, {}, callback);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::deferEmit()
*/
View.prototype.deferEmit = function () {
return this._privateData.deferEmit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
var coll = this.publicData();
return coll.distinct.apply(coll, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this.publicData().primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._publicData && this._publicData !== this._privateData) {
this._publicData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
}
});
View.prototype._joinChange = function (objName, objType) {
this.emit('joinChange');
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
var self = this,
pubData,
refreshResults,
joinArr,
i, k;
if (this._from) {
pubData = this.publicData();
// Re-grab all the data for the view from the collection
this._privateData.remove();
//pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) {
// Define the change handler method
self.__joinChange = self.__joinChange || function () {
self._joinChange();
};
// Check for existing join collections
if (this._joinCollections && this._joinCollections.length) {
// Loop the join collections and remove change listeners
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange);
}
}
// Now start hooking any new / existing joins
joinArr = this._querySettings.options.$join;
this._joinCollections = [];
// Loop the joined collections and hook change events
for (i = 0; i < joinArr.length; i++) {
for (k in joinArr[i]) {
if (joinArr[i].hasOwnProperty(k)) {
this._joinCollections.push(k);
}
}
}
if (this._joinCollections.length) {
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange);
}
}
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
if (this.publicData()) {
return this.publicData().count.apply(this.publicData(), arguments);
}
return 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var self = this;
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
if (this._transformEnabled) {
// Check for / create the public data collection
if (!this._publicData) {
// Create the public data collection
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
// Create a chain reaction IO node to keep the private and
// public data collections in sync
this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) {
var data = chainPacket.data;
switch (chainPacket.type) {
case 'primaryKey':
self._publicData.primaryKey(data);
this.chainSend('primaryKey', data);
break;
case 'setData':
self._publicData.setData(data);
this.chainSend('setData', data);
break;
case 'insert':
self._publicData.insert(data);
this.chainSend('insert', data);
break;
case 'update':
// Do the update
self._publicData.update(
data.query,
data.update,
data.options
);
this.chainSend('update', data);
break;
case 'remove':
self._publicData.remove(data.query, chainPacket.options);
this.chainSend('remove', data);
break;
default:
break;
}
});
}
// Set initial data and settings
this._publicData.primaryKey(this.privateData().primaryKey());
this._publicData.setData(this.privateData().find());
} else {
// Remove the public data collection
if (this._publicData) {
this._publicData.drop();
delete this._publicData;
if (this._transformIo) {
this._transformIo.drop();
delete this._transformIo;
}
}
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
/**
* @see Collection.indexOf
* @returns {*}
*/
View.prototype.indexOf = function () {
return this.publicData().indexOf.apply(this.publicData(), arguments);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.privateData().db(db);
this.publicData().db(db);
// Apply the same debug settings
this.debug(db.debug());
this.privateData().debug(db.debug());
this.publicData().debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} name The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (name) {
var self = this;
// Handle being passed an instance
if (name instanceof View) {
return name;
}
if (this._view[name]) {
return this._view[name];
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + name);
}
this._view[name] = new View(name).db(this);
self.emit('create', self._view[name], 'view', name);
return this._view[name];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} name The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (name) {
return Boolean(this._view[name]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
|
packages/material-ui-icons/src/HotelRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M7 13c1.66 0 3-1.34 3-3S8.66 7 7 7s-3 1.34-3 3 1.34 3 3 3zm12-6h-6c-1.1 0-2 .9-2 2v5H3V6c0-.55-.45-1-1-1s-1 .45-1 1v13c0 .55.45 1 1 1s1-.45 1-1v-2h18v2c0 .55.45 1 1 1s1-.45 1-1v-8c0-2.21-1.79-4-4-4z" /></React.Fragment>
, 'HotelRounded');
|
app/containers/tutorial/sixth.js | DeividasK/my-future-ai | import React from 'react'
import SimpleList from 'components/lists/simple'
import { updateStep, updateHeading, updateActions } from '../../actions/TutorialActions'
import { FormattedMessage, defineMessages, injectIntl } from 'react-intl'
const content = defineMessages({
title: { id: 'app.tutorial.step6.title', defaultMessage: 'Deadlines', }
})
class TutorialStep6 extends React.Component {
constructor (props) {
super(props)
this.state = {
filters: [
function(item) { return item.primary === false }
],
formItem: { type: 'date', value: 'deadline' }
}
}
componentWillMount () {
updateStep(6)
updateHeading(this.props.intl.formatMessage(content.title), "calendar")
updateActions(6)
}
render () {
return (
<div>
<p><FormattedMessage
id='app.tutorial.step6.introduction'
defaultMessage="Set a date when you plan to achieve your goal."
/></p>
<SimpleList
items={ this.props.goals }
filters={ this.state.filters }
formItem={ this.state.formItem }
/>
</div>
)
}
}
export default injectIntl(TutorialStep6) |
analysis/paladinretribution/src/CHANGELOG.js | anom0ly/WoWAnalyzer | import { change, date } from 'common/changelog';
import SPELLS from 'common/SPELLS';
import { Adoraci, Juko8, Skeletor, Zeboot, Hordehobbs } from 'CONTRIBUTORS';
import { SpellLink } from 'interface';
import React from 'react';
export default [
change(date(2021, 4, 10), <>Added <SpellLink id={SPELLS.FINAL_VERDICT.id} icon />.</>, Juko8),
change(date(2021, 4, 3), 'Verified patch changes and bumped support to 9.0.5', Adoraci),
change(date(2020, 12, 1), <>Added <SpellLink id={SPELLS.SANCTIFIED_WRATH_TALENT_RETRIBUTION.id} icon /> module and minor housekeeping.</>, Skeletor),
change(date(2020, 11, 8), <>Added <SpellLink id={SPELLS.EMPYREAN_POWER_TALENT.id} icon /> module.</>, Skeletor),
change(date(2020, 11, 7), <>Added <SpellLink id={SPELLS.HOLY_AVENGER_TALENT.id} icon /> module from new Shared module.</>, Skeletor),
change(date(2020, 11, 7), <>Updated <SpellLink id={SPELLS.DIVINE_PURPOSE_TALENT.id} icon /> module to new Shared module.</>, Skeletor),
change(date(2020, 11, 7), 'Core and Talent modules converted to TypeScript', Skeletor),
change(date(2020, 11, 6), 'General housekeeping and ability updates.', Skeletor),
change(date(2020, 10, 23), <>Aggregate Prot and Ret <SpellLink id={SPELLS.JUDGMENT_CAST.id} /> analyzers into single analyzer.</>, Hordehobbs),
change(date(2020, 10, 18), 'Converted legacy listeners to new event filters', Zeboot),
change(date(2020, 10, 17), <>Updated <SpellLink id={SPELLS.HAMMER_OF_WRATH.id} icon /> max casts calculation to account for execute restrictions and added cast efficiency tracking</>, Juko8),
change(date(2020, 9, 18), 'Removed BFA stuff and updated most things for 9.0', Juko8),
];
|
packages/material-ui-icons/src/FirstPage.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M18.41 16.59L13.82 12l4.59-4.59L17 6l-6 6 6 6zM6 6h2v12H6z" /><path fill="none" d="M24 24H0V0h24v24z" /></React.Fragment>
, 'FirstPage');
|
js/components/radio/index.js | YeisonGomez/RNAmanda |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Content, Button, Icon, List, ListItem, Radio, Text,Left,Right,Body } from 'native-base';
import { openDrawer } from '../../actions/drawer';
import styles from './styles';
class NHRadio extends Component {
static propTypes = {
openDrawer: React.PropTypes.func,
}
constructor(props) {
super(props);
this.state = {
radio1: false,
radio2: false,
radio3: false,
radio4: true,
};
}
toggleRadio1() {
this.setState({
radio1: true,
radio2: false,
radio3: false,
radio4: false,
});
}
toggleRadio2() {
this.setState({
radio1: false,
radio2: true,
radio3: false,
radio4: false,
});
}
toggleRadio3() {
this.setState({
radio1: false,
radio2: false,
radio3: true,
radio4: false,
});
}
toggleRadio4() {
this.setState({
radio1: false,
radio2: false,
radio3: false,
radio4: true,
});
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={this.props.openDrawer}>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>Radios</Title>
</Body>
<Right />
</Header>
<Content>
<ListItem selected={this.state.radio1} onPress={() => this.toggleRadio1()} >
<Text>Lunch Break</Text>
<Right>
<Radio selected={this.state.radio1} onPress={() => this.toggleRadio1()} />
</Right>
</ListItem>
<ListItem selected={this.state.radio2} onPress={() => this.toggleRadio2()} >
<Text >Daily Stand Up</Text>
<Right>
<Radio selected={this.state.radio2} onPress={() => this.toggleRadio2()} />
</Right>
</ListItem>
<ListItem selected={this.state.radio3} onPress={() => this.toggleRadio3()} >
<Text>Finish list Screen</Text>
<Right>
<Radio selected={this.state.radio3} onPress={() => this.toggleRadio3()} />
</Right>
</ListItem>
<ListItem selected={this.state.radio4} onPress={() => this.toggleRadio4()} >
<Text>Discussion with Client</Text>
<Right>
<Radio selected={this.state.radio4} onPress={() => this.toggleRadio4()} />
</Right>
</ListItem>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(NHRadio);
|
src/svg-icons/action/info-outline.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionInfoOutline = (props) => (
<SvgIcon {...props}>
<path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"/>
</SvgIcon>
);
ActionInfoOutline = pure(ActionInfoOutline);
ActionInfoOutline.displayName = 'ActionInfoOutline';
ActionInfoOutline.muiName = 'SvgIcon';
export default ActionInfoOutline;
|
src/js/components/icons/status/Label.js | primozs/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import CSSClassnames from '../../../utils/CSSClassnames';
const STATUS_ICON = CSSClassnames.STATUS_ICON;
export default class Label extends Component {
render() {
var className = `${STATUS_ICON} ${STATUS_ICON}-label`;
if (this.props.className) {
className += ' ' + this.props.className;
}
return (
<svg className={className} viewBox="0 0 24 24" version="1.1">
<g className={`${STATUS_ICON}__base`}>
<circle cx="12" cy="12" r="12" stroke="none"></circle>
</g>
</svg>
);
}
}
|
examples/draft-0-10-0/tex/js/components/TeXBlock.js | dirkholsopple/draft-js | /**
* Copyright (c) 2013-present, Facebook, Inc. All rights reserved.
*
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* 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
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
import katex from 'katex';
import React from 'react';
class KatexOutput extends React.Component {
constructor(props) {
super(props);
this._timer = null;
}
_update() {
if (this._timer) {
clearTimeout(this._timer);
}
this._timer = setTimeout(() => {
katex.render(
this.props.content,
this.refs.container,
{displayMode: true},
);
}, 0);
}
componentDidMount() {
this._update();
}
componentWillReceiveProps(nextProps) {
if (nextProps.content !== this.props.content) {
this._update();
}
}
componentWillUnmount() {
clearTimeout(this._timer);
this._timer = null;
}
render() {
return <div ref="container" onClick={this.props.onClick} />;
}
}
export default class TeXBlock extends React.Component {
constructor(props) {
super(props);
this.state = {editMode: false};
this._onClick = () => {
if (this.state.editMode) {
return;
}
this.setState({
editMode: true,
texValue: this._getValue(),
}, () => {
this._startEdit();
});
};
this._onValueChange = evt => {
var value = evt.target.value;
var invalid = false;
try {
katex.__parse(value);
} catch (e) {
invalid = true;
} finally {
this.setState({
invalidTeX: invalid,
texValue: value,
});
}
};
this._save = () => {
var entityKey = this.props.block.getEntityAt(0);
var newContentState = this.props.contentState.mergeEntityData(
entityKey,
{content: this.state.texValue},
);
this.setState({
invalidTeX: false,
editMode: false,
texValue: null,
}, this._finishEdit.bind(this, newContentState));
};
this._remove = () => {
this.props.blockProps.onRemove(this.props.block.getKey());
};
this._startEdit = () => {
this.props.blockProps.onStartEdit(this.props.block.getKey());
};
this._finishEdit = (newContentState) => {
this.props.blockProps.onFinishEdit(
this.props.block.getKey(),
newContentState,
);
};
}
_getValue() {
return this.props.contentState
.getEntity(this.props.block.getEntityAt(0))
.getData()['content'];
}
render() {
var texContent = null;
if (this.state.editMode) {
if (this.state.invalidTeX) {
texContent = '';
} else {
texContent = this.state.texValue;
}
} else {
texContent = this._getValue();
}
var className = 'TeXEditor-tex';
if (this.state.editMode) {
className += ' TeXEditor-activeTeX';
}
var editPanel = null;
if (this.state.editMode) {
var buttonClass = 'TeXEditor-saveButton';
if (this.state.invalidTeX) {
buttonClass += ' TeXEditor-invalidButton';
}
editPanel =
<div className="TeXEditor-panel">
<textarea
className="TeXEditor-texValue"
onChange={this._onValueChange}
ref="textarea"
value={this.state.texValue}
/>
<div className="TeXEditor-buttons">
<button
className={buttonClass}
disabled={this.state.invalidTeX}
onClick={this._save}>
{this.state.invalidTeX ? 'Invalid TeX' : 'Done'}
</button>
<button className="TeXEditor-removeButton" onClick={this._remove}>
Remove
</button>
</div>
</div>;
}
return (
<div className={className}>
<KatexOutput content={texContent} onClick={this._onClick} />
{editPanel}
</div>
);
}
}
|
examples/animated-framer-motion/src/App.js | tannerlinsley/react-table | import React from 'react'
import styled from 'styled-components'
import { useTable, useSortBy, useFilters, useColumnOrder } from 'react-table'
import { motion, AnimatePresence } from 'framer-motion'
import matchSorter from 'match-sorter'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
background: white;
:last-child {
border-right: 0;
}
}
}
`
// Define a default UI for filtering
function DefaultColumnFilter({
column: { filterValue, preFilteredRows, setFilter },
}) {
const count = preFilteredRows.length
return (
<input
value={filterValue || ''}
onChange={e => {
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
}}
placeholder={`Search ${count} records...`}
/>
)
}
// This is a custom filter UI for selecting
// a unique option from a list
function SelectColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the options for filtering
// using the preFilteredRows
const options = React.useMemo(() => {
const options = new Set()
preFilteredRows.forEach(row => {
options.add(row.values[id])
})
return [...options.values()]
}, [id, preFilteredRows])
// Render a multi-select box
return (
<select
value={filterValue}
onChange={e => {
setFilter(e.target.value || undefined)
}}
>
<option value="">All</option>
{options.map((option, i) => (
<option key={i} value={option}>
{option}
</option>
))}
</select>
)
}
// This is a custom filter UI that uses a
// slider to set the filter value between a column's
// min and max values
function SliderColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the min and max
// using the preFilteredRows
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<>
<input
type="range"
min={min}
max={max}
value={filterValue || min}
onChange={e => {
setFilter(parseInt(e.target.value, 10))
}}
/>
<button onClick={() => setFilter(undefined)}>Off</button>
</>
)
}
// This is a custom UI for our 'between' or number range
// filter. It uses two number boxes and filters rows to
// ones that have values between the two
function NumberRangeColumnFilter({
column: { filterValue = [], preFilteredRows, setFilter, id },
}) {
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<div
style={{
display: 'flex',
}}
>
<input
value={filterValue[0] || ''}
type="number"
onChange={e => {
const val = e.target.value
setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
}}
placeholder={`Min (${min})`}
style={{
width: '70px',
marginRight: '0.5rem',
}}
/>
to
<input
value={filterValue[1] || ''}
type="number"
onChange={e => {
const val = e.target.value
setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
}}
placeholder={`Max (${max})`}
style={{
width: '70px',
marginLeft: '0.5rem',
}}
/>
</div>
)
}
function fuzzyTextFilterFn(rows, id, filterValue) {
return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
}
// Let the table remove the filter if the string is empty
fuzzyTextFilterFn.autoRemove = val => !val
function shuffle(arr) {
arr = [...arr]
const shuffled = []
while (arr.length) {
const rand = Math.floor(Math.random() * arr.length)
shuffled.push(arr.splice(rand, 1)[0])
}
return shuffled
}
function Table({ columns, data }) {
const defaultColumn = React.useMemo(
() => ({
// Let's set up our default Filter UI
Filter: DefaultColumnFilter,
}),
[]
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
visibleColumns,
prepareRow,
setColumnOrder,
state,
} = useTable(
{
columns,
data,
defaultColumn,
},
useColumnOrder,
useFilters,
useSortBy
)
const spring = React.useMemo(
() => ({
type: 'spring',
damping: 50,
stiffness: 100,
}),
[]
)
const randomizeColumns = () => {
setColumnOrder(shuffle(visibleColumns.map(d => d.id)))
}
return (
<>
<button onClick={() => randomizeColumns({})}>Randomize Columns</button>
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup, i) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<motion.th
{...column.getHeaderProps({
layoutTransition: spring,
style: {
minWidth: column.minWidth,
},
})}
>
<div {...column.getSortByToggleProps()}>
{column.render('Header')}
<span>
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
</div>
<div>{column.canFilter ? column.render('Filter') : null}</div>
</motion.th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
<AnimatePresence>
{rows.slice(0, 10).map((row, i) => {
prepareRow(row)
return (
<motion.tr
{...row.getRowProps({
layoutTransition: spring,
exit: { opacity: 0, maxHeight: 0 },
})}
>
{row.cells.map((cell, i) => {
return (
<motion.td
{...cell.getCellProps({
layoutTransition: spring,
})}
>
{cell.render('Cell')}
</motion.td>
)
})}
</motion.tr>
)
})}
</AnimatePresence>
</tbody>
</table>
<pre>
<code>{JSON.stringify(state, null, 2)}</code>
</pre>
</>
)
}
// Define a custom filter filter function!
function filterGreaterThan(rows, id, filterValue) {
return rows.filter(row => {
const rowValue = row.values[id]
return rowValue >= filterValue
})
}
// This is an autoRemove method on the filter function that
// when given the new filter value and returns true, the filter
// will be automatically removed. Normally this is just an undefined
// check, but here, we want to remove the filter if it's not a number
filterGreaterThan.autoRemove = val => typeof val !== 'number'
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
minWidth: 150,
},
{
Header: 'Last Name',
accessor: 'lastName',
minWidth: 150,
// Use our custom `fuzzyText` filter on this column
filter: 'fuzzyText',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
minWidth: 150,
Filter: SliderColumnFilter,
filter: 'equals',
},
{
Header: 'Visits',
accessor: 'visits',
minWidth: 150,
Filter: NumberRangeColumnFilter,
filter: 'between',
},
{
Header: 'Status',
accessor: 'status',
minWidth: 150,
Filter: SelectColumnFilter,
filter: 'includes',
},
{
Header: 'Profile Progress',
accessor: 'progress',
minWidth: 150,
Filter: SliderColumnFilter,
filter: filterGreaterThan,
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(100), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
|
src/entry.js | bj75326/react-slider | //entry.js
import React from 'react';
import {render} from 'react-dom';
import Test from './component/Test.js';
import initReactFastClick from 'react-fastclick';
initReactFastClick();
render(<Test/>, document.querySelector('#App')); |
app/javascript/mastodon/components/load_more.js | glitch-soc/mastodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
export default class LoadMore extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func,
disabled: PropTypes.bool,
visible: PropTypes.bool,
}
static defaultProps = {
visible: true,
}
render() {
const { disabled, visible } = this.props;
return (
<button className='load-more' disabled={disabled || !visible} style={{ visibility: visible ? 'visible' : 'hidden' }} onClick={this.props.onClick}>
<FormattedMessage id='status.load_more' defaultMessage='Load more' />
</button>
);
}
}
|
src/group-finder/NoResults.js | NewSpring/Apollos | import React from 'react';
import Card, { CardContent } from '@ui/Card';
import { BodyText } from '@ui/typography';
import { ButtonLink } from '@ui/Button';
import styled from '@ui/styled';
import PaddedView from '@ui/PaddedView';
import WebBrowser from '@ui/WebBrowser';
const StyledBodyText = styled({ textAlign: 'center' })(BodyText);
const AdUnit = () => (
<Card>
<CardContent>
<PaddedView>
<StyledBodyText italic>
{
"Unfortunately, we didn't find any groups matching your search. Gather some friends, and "
}
<ButtonLink
onPress={() => WebBrowser.openBrowserAsync('https://rock.newspring.cc/workflows/81')}
>
start your own group
</ButtonLink>
{'!'}
</StyledBodyText>
</PaddedView>
</CardContent>
</Card>
);
export default AdUnit;
|
public/js/components/Instructions.js | richardison/audition-project | import React from 'react';
export default class Instructions extends React.Component {
render() {
return (
<div className="instructions">
<p>
Pretty simple app that uses React and NodeJS. The front end
communicates to the server by REST API calls. This includes fetching
all messages, posting a message, retrieving a specific message on
demand to determine if it is a palindrome, and deleting specific
messages.
</p>
<p>
You can add in new messages by typing and submitting in the input below.
Clicking on one of the messages brings up a modal that shows the details,
clicking on x deletes the message.
</p>
</div>
);
}
}
|
src/components/common/Icon.js | jinqiupeter/mtsr | import React from 'react';
import {StyleSheet, Platform, View, Text, TouchableOpacity} from 'react-native';
import {Actions} from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/FontAwesome';
import {COLOR, SCREEN_WIDTH, SCREEN_HEIGHT} from '../../config';
export default ({name, transparent=false, onPress, styleKind='normal', style,
containerStyle, ...props}) => {
let transparentStyle = transparent ? {backgroundColor: 'transparent'} : null;
if (onPress) {
return (
<TouchableOpacity onPress={onPress} style={containerStyle}>
<Icon {...props} name={name} style={[styles[styleKind], transparentStyle, style]} />
</TouchableOpacity>
);
} else{
return (
<Icon {...props} name={name} style={[styles[styleKind], transparentStyle, style]} />
);
}
}
const styles = StyleSheet.create({
normal: {
fontSize: 12,
color: COLOR.textNormal,
},
normalBig: {
fontSize: 14,
color: COLOR.textNormal,
},
empha: {
fontSize: 12,
color: COLOR.textEmpha,
},
emphaBig: {
fontSize: 14,
color: COLOR.textEmpha,
},
});
|
app/src/components/List.js | wtfil/google-music-unofficial-client | import React from 'react';
import cx from 'classnames';
import {Link} from 'react-router';
import formatTime from '../utils/formatTime';
class Item extends React.Component {
render(props) {
const {small, current, album, albumId, artist, title, duration, trackId, onSelect, artistId, index} = this.props;
const isCurrent = current === trackId;
return <tr className={cx('playlist__item song-title', {current: isCurrent} )}>
{isCurrent ?
<td>
<i className="playlist__number material-icons tiny playlist__note">music_note</i>
</td> :
<td className="playlist__number">
<span className="playlist__index">{index + 1}</span>
<i
onClick={e => onSelect(trackId)}
className="pointer material-icons playlist__icon"
children="play_arrow"
/>
</td>
}
<td className={cx("playlist__name", {bold: isCurrent})}>{title}</td>
{!small && <td className="playlist__duration hide-on-small-only">{formatTime(duration)}</td>}
<td className="playlist__artist">
<Link to={'artists/' + artistId}>{artist}</Link>
</td>
<td className="playlist__artist hide-on-small-only">
<Link to={'albums/' + albumId}>{album}</Link>
</td>
</tr>;
}
}
export default class List extends React.Component {
shouldComponentUpdate(props) {
return props.items !== this.props.items ||
props.current !== this.props.current
}
render() {
const {items, ...props} = this.props;
return <table className="playlist">
<thead>
<tr>
<td className="playlist__number">#</td>
<td className="playlist__name">NAME</td>
{!props.small && <td className="playlist__duration hide-on-small-only"><i className="tiny right material-icons">access_time</i></td>}
<td className="playlist__artist">ARTIST</td>
<td className="playlist__artist hide-on-small-only">ALBUM</td>
</tr>
</thead>
<tbody>
{items && items.map((item, index) => (
<Item key={index} index={index} {...item} {...props} />
))}
</tbody>
</table>;
}
}
|
src/components/_common/List.js | visarts/dotorg | import React from 'react'
import _ from 'lodash'
import { Typography, Image } from 'common'
import styled, { css } from 'styled-components'
import { Link } from 'react-router-dom'
const StyledListItem = styled.li`
border-radius: 5px;
`
const StyledListItemLink = styled(Link)`
${props => css`
display: ${props.image ? 'flex' : 'block'};
background-color: ${props.theme.colors.background.light2};
color: ${props.theme.colors.foreground.darkest};
transition: .2s all;
&:hover {
color: ${props.theme.colors.foreground.dark};
background-color: ${props.theme.colors.background.light3};
}
`}
`
const StyledListItemDesc = styled.div`
display: flex;
flex-direction: column;
${props => css`
padding: ${props.theme.sizes.sm};
`}
`
const ListItem = props => {
const truncateLength = window.innerWidth > 768 ? 190 : 100
if (props.to) {
return (
<StyledListItem>
<StyledListItemLink to={props.to} image={props.image}>
{props.image &&
<Image
type="thumbnail"
src={props.image.src}
default={props.image.default}
alt={props.image.alt || props.image.src} />
}
<StyledListItemDesc>
{props.headline && <Typography type="listPrimary">{props.headline}</Typography>}
{props.subHeadline && <Typography type="listSecondary">{props.subHeadline}</Typography>}
{props.primaryText && <Typography type="listSecondary">{_.truncate(props.primaryText, { length: truncateLength, separator: ' ' })}</Typography>}
</StyledListItemDesc>
</StyledListItemLink>
</StyledListItem>
)
} else {
return (
<StyledListItem key={props.key || 0}>
{props.headline && <Typography type="listPrimary">{props.headline}</Typography>}
{props.subHeadline && <Typography type="listSecondary">{props.subHeadline}</Typography>}
</StyledListItem>
)
}
}
function List (props) {
return (
<ul>
{props.children}
</ul>
)
}
export default List
export { ListItem }
|
js/components/button/outline.js | YeisonGomez/RNAmanda |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text, H3 } from 'native-base';
import { Actions } from 'react-native-router-flux';
import { actions } from 'react-native-navigation-redux-helpers';
import { openDrawer } from '../../actions/drawer';
import styles from './styles';
const {
popRoute,
} = actions;
class Outline extends Component { // eslint-disable-line
static propTypes = {
openDrawer: React.PropTypes.func,
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Outline</Title>
</Body>
<Right />
</Header>
<Content padder style={{ backgroundColor: '#fff', padding: 20 }}>
<Button bordered light style={styles.mb15}><Text>Light</Text></Button>
<Button bordered info style={styles.mb15}><Text>Info</Text></Button>
<Button bordered danger style={styles.mb15}><Text>Danger</Text></Button>
<Button bordered primary style={styles.mb15}><Text>Primary</Text></Button>
<Button bordered warning style={styles.mb15}><Text>Warning</Text></Button>
<Button bordered success style={styles.mb15}><Text>Success</Text></Button>
<Button bordered dark style={styles.mb15}><Text>Dark</Text></Button>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(Outline);
|
ajax/libs/reactive-coffee/1.2.0/reactive-coffee.min.js | qrohlf/cdnjs | (function(){var a,b=[].slice,c={}.hasOwnProperty,d=function(a,b){function d(){this.constructor=a}for(var e in b)c.call(b,e)&&(a[e]=b[e]);return d.prototype=b.prototype,a.prototype=new d,a.__super__=b.prototype,a};a=function(a,c){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,ab,bb,cb;if(U={},L=0,K=function(){return L+=1},O=function(a,b){var c;if(!(b in a))throw new Error("object has no key "+b);return c=a[b],delete a[b],c},M=function(a,b,c){var d,e,f,g;for(d=f=0,g=a.length;g>f;d=++f)if(e=a[d],c(e)&&(b-=1)<0)return[e,d];return[null,-1]},E=function(a,b){return M(a,0,b)},I=function(b){var c,d,e,f,g,h;if(null==b&&(b=[]),d=null!=Object.create?Object.create(null):{},a.isArray(b))for(f=0,g=b.length;g>f;f++)h=b[f],c=h[0],e=h[1],d[c]=e;else for(c in b)e=b[c],d[c]=e;return d},Z=function(a){var b,c,d,e;for(b=0,d=0,e=a.length;e>d;d++)c=a[d],b+=c;return b},h=U.DepMgr=function(){function a(){this.uid2src={},this.buffering=0,this.buffer=[]}return a.prototype.sub=function(a,b){return this.uid2src[a]=b},a.prototype.unsub=function(a){return O(this.uid2src,a)},a.prototype.transaction=function(a){var b,c,d,e,f;this.buffering+=1;try{c=a()}finally{if(this.buffering-=1,0===this.buffering){for(f=this.buffer,d=0,e=f.length;e>d;d++)(b=f[d])();this.buffer=[]}}return c},a}(),U._depMgr=B=new h,i=U.Ev=function(){function a(a){this.inits=a,this.subs=I()}return a.prototype.sub=function(a){var b,c,d,e,f;if(c=K(),null!=this.inits)for(f=this.inits(),d=0,e=f.length;e>d;d++)b=f[d],a(b);return this.subs[c]=a,B.sub(c,this),c},a.prototype.pub=function(a){var b,c,d,e;if(B.buffering)return B.buffer.push(function(b){return function(){return b.pub(a)}}(this));d=this.subs,e=[];for(c in d)b=d[c],e.push(b(a));return e},a.prototype.unsub=function(a){return O(this.subs,a),B.unsub(a,this)},a.prototype.scoped=function(a,b){var c;c=this.sub(a);try{return b()}finally{this.unsub(c)}},a}(),U.skipFirst=function(a){var c;return c=!0,function(){var d;return d=1<=arguments.length?b.call(arguments,0):[],c?c=!1:a.apply(null,d)}},u=U.Recorder=function(){function b(){this.stack=[],this.isMutating=!1,this.isIgnoring=!1,this.onMutationWarning=new i}return b.prototype.record=function(b,c){var d,e;this.stack.length>0&&!this.isMutating&&a(this.stack).last().addNestedBind(b),this.stack.push(b),e=this.isMutating,this.isMutating=!1,d=this.isIgnoring,this.isIgnoring=!1;try{return c()}finally{this.isIgnoring=d,this.isMutating=e,this.stack.pop()}},b.prototype.sub=function(b){var c,d;return this.stack.length>0&&!this.isIgnoring?(d=a(this.stack).last(),c=b(d)):void 0},b.prototype.addCleanup=function(b){return this.stack.length>0?a(this.stack).last().addCleanup(b):void 0},b.prototype.mutating=function(a){var b;this.stack.length>0&&(console.warn("Mutation to observable detected during a bind context"),this.onMutationWarning.pub(null)),b=this.isMutating,this.isMutating=!0;try{return a()}finally{this.isMutating=b}},b.prototype.ignoring=function(a){var b;b=this.isIgnoring,this.isIgnoring=!0;try{return a()}finally{this.isIgnoring=b}},b}(),U._recorder=T=new u,U.asyncBind=z=function(a,b){var c;return c=new f(b,a),c.refresh(),c},U.bind=A=function(a){return z(null,function(){return this.done(this.record(a))})},U.lagBind=G=function(a,b,c){var d;return d=null,z(b,function(){return null!=d&&clearTimeout(d),d=setTimeout(function(a){return function(){return a.done(a.record(c))}}(this),a)})},U.postLagBind=P=function(a,b){var c;return c=null,z(a,function(){var a,d,e;return e=this.record(b),d=e.val,a=e.ms,null!=c&&clearTimeout(c),c=setTimeout(function(a){return function(){return a.done(d)}}(this),a)})},U.snap=function(a){return T.ignoring(a)},U.onDispose=function(a){return T.addCleanup(a)},U.autoSub=function(a,b){var c;return c=a.sub(b),U.onDispose(function(){return a.unsub(c)}),c},q=U.ObsCell=function(){function a(a){var b;this.x=a,this.x=null!=(b=this.x)?b:null,this.onSet=new i(function(a){return function(){return[[null,a.x]]}}(this))}return a.prototype.get=function(){return T.sub(function(a){return function(b){return U.autoSub(a.onSet,function(){return b.refresh()})}}(this)),this.x},a}(),w=U.SrcCell=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return d(b,a),b.prototype.set=function(a){return T.mutating(function(b){return function(){var c;return b.x!==a?(c=b.x,b.x=a,b.onSet.pub([c,a]),c):void 0}}(this))},b}(q),f=U.DepCell=function(a){function b(a,c){this.body=a,b.__super__.constructor.call(this,null!=c?c:null),this.refreshing=!1,this.nestedBinds=[],this.cleanups=[]}return d(b,a),b.prototype.refresh=function(){var a,b,c,d,e;return this.refreshing?void 0:(c=this.x,d=function(a){return function(b){return a.x=b,a.onSet.pub([c,a.x])}}(this),e=null,b=!1,a={record:function(c){return function(f){var g,h;if(!c.refreshing){if(c.disconnect(),g)throw new Error("this refresh has already recorded its dependencies");c.refreshing=!0,g=!0;try{h=T.record(c,function(){return f.call(a)})}finally{c.refreshing=!1}return b&&d(e),h}}}(this),done:function(a){return function(f){return c!==f?a.refreshing?(b=!0,e=f):d(f):void 0}}(this)},this.body.call(a))},b.prototype.disconnect=function(){var a,b,c,d,e,f,g,h;for(g=this.cleanups,c=0,e=g.length;e>c;c++)(a=g[c])();for(h=this.nestedBinds,d=0,f=h.length;f>d;d++)b=h[d],b.disconnect();return this.nestedBinds=[],this.cleanups=[]},b.prototype.addNestedBind=function(a){return this.nestedBinds.push(a)},b.prototype.addCleanup=function(a){return this.cleanups.push(a)},b}(q),p=U.ObsArray=function(){function b(a,b){this.xs=null!=a?a:[],this.diff=null!=b?b:U.basicDiff(),this.onChange=new i(function(a){return function(){return[[0,[],a.xs]]}}(this)),this.indexed_=null}return b.prototype.all=function(){return T.sub(function(a){return function(b){return U.autoSub(a.onChange,function(){return b.refresh()})}}(this)),a.clone(this.xs)},b.prototype.raw=function(){return T.sub(function(a){return function(b){return U.autoSub(a.onChange,function(){return b.refresh()})}}(this)),this.xs},b.prototype.at=function(a){return T.sub(function(b){return function(c){return U.autoSub(b.onChange,function(b){var d,e,f;return e=b[0],f=b[1],d=b[2],e===a?c.refresh():void 0})}}(this)),this.xs[a]},b.prototype.length=function(){return T.sub(function(a){return function(b){return U.autoSub(a.onChange,function(a){var c,d,e;return d=a[0],e=a[1],c=a[2],e.length!==c.length?b.refresh():void 0})}}(this)),this.xs.length},b.prototype.map=function(a){var b;return b=new o,U.autoSub(this.onChange,function(c){var d,e,f;return e=c[0],f=c[1],d=c[2],b.realSplice(e,f.length,d.map(a))}),b},b.prototype.indexed=function(){return null==this.indexed_&&(this.indexed_=new m,U.autoSub(this.onChange,function(a){return function(b){var c,d,e;return d=b[0],e=b[1],c=b[2],a.indexed_.realSplice(d,e.length,c)}}(this))),this.indexed_},b.prototype.concat=function(a){return U.concat(this,a)},b.prototype.realSplice=function(a,b,c){var d;return d=this.xs.splice.apply(this.xs,[a,b].concat(c)),this.onChange.pub([a,d,c])},b.prototype._update=function(a,b){var c,d,e,f,g,h,i,j,k,l,m,n;for(null==b&&(b=this.diff),g=this.xs,e=[0,g.length,a],j=null,i=null!=b&&null!=(m=N(g.length,a,b(g,a)))?m:[e],n=[],k=0,l=i.length;l>k;k++)h=i[k],f=h[0],d=h[1],c=h[2],n.push(this.realSplice(f,d,c));return n},b}(),v=U.SrcArray=function(c){function e(){return e.__super__.constructor.apply(this,arguments)}return d(e,c),e.prototype.spliceArray=function(a,b,c){return T.mutating(function(d){return function(){return d.realSplice(a,b,c)}}(this))},e.prototype.splice=function(){var a,c,d;return d=arguments[0],c=arguments[1],a=3<=arguments.length?b.call(arguments,2):[],this.spliceArray(d,c,a)},e.prototype.insert=function(a,b){return this.splice(b,0,a)},e.prototype.remove=function(b){var c;return c=a(this.raw()).indexOf(b),c>=0?this.removeAt(c):void 0},e.prototype.removeAt=function(a){return this.splice(a,1)},e.prototype.push=function(a){return this.splice(this.length(),0,a)},e.prototype.put=function(a,b){return this.splice(a,1,b)},e.prototype.replace=function(a){return this.spliceArray(0,this.length(),a)},e.prototype.update=function(a){return T.mutating(function(b){return function(){return b._update(a)}}(this))},e}(p),o=U.MappedDepArray=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return d(b,a),b}(p),m=U.IndexedDepArray=function(c){function e(b,c){var d,f;null==b&&(b=[]),e.__super__.constructor.call(this,b,c),this.is=function(){var a,b,c,e;for(c=this.xs,e=[],d=a=0,b=c.length;b>a;d=++a)f=c[d],e.push(U.cell(d));return e}.call(this),this.onChange=new i(function(b){return function(){return[[0,[],a.zip(b.xs,b.is)]]}}(this))}return d(e,c),e.prototype.map=function(a){var b;return b=new n,U.autoSub(this.onChange,function(c){var d,e,f,g,h;return g=c[0],h=c[1],e=c[2],b.realSplice(g,h.length,function(){var b,c,g,h;for(h=[],b=0,c=e.length;c>b;b++)g=e[b],d=g[0],f=g[1],h.push(a(d,f));return h}())}),b},e.prototype.realSplice=function(c,d,e){var f,g,h,i,j,k,l,m,n;for(i=(l=this.xs).splice.apply(l,[c,d].concat(b.call(e))),m=this.is.slice(c+d),h=j=0,k=m.length;k>j;h=++j)f=m[h],f.set(c+e.length+h);return g=function(){var a,b,d;for(d=[],f=a=0,b=e.length;b>=0?b>a:a>b;f=b>=0?++a:--a)d.push(U.cell(c+f));return d}(),(n=this.is).splice.apply(n,[c,d].concat(b.call(g))),this.onChange.pub([c,i,a.zip(e,g)])},e}(p),n=U.IndexedMappedDepArray=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return d(b,a),b}(m),e=U.DepArray=function(a){function b(a,c){this.f=a,b.__super__.constructor.call(this,[],c),U.autoSub(A(function(a){return function(){return a.f()}}(this)).onSet,function(a){return function(b){var c,d;return c=b[0],d=b[1],a._update(d)}}(this))}return d(b,a),b}(p),l=U.IndexedArray=function(a){function b(a){this.xs=a}return d(b,a),b.prototype.map=function(a){var b;return b=new o,U.autoSub(this.xs.onChange,function(c){var d,e,f;return e=c[0],f=c[1],d=c[2],b.realSplice(e,f.length,d.map(a))}),b},b}(e),U.concat=function(){var a,c,d,e;return d=1<=arguments.length?b.call(arguments,0):[],e=new o,a=function(){var a,b,e;for(e=[],a=0,b=d.length;b>a;a++)c=d[a],e.push(0);return e}(),d.map(function(b,c){return U.autoSub(b.onChange,function(b){var d,f,g,h;return f=b[0],g=b[1],d=b[2],h=Z(a.slice(0,c)),a[c]+=d.length-g.length,e.realSplice(h+f,g.length,d)})}),e},k=U.FakeSrcCell=function(a){function b(a,b){this._getter=a,this._setter=b}return d(b,a),b.prototype.get=function(){return this._getter()},b.prototype.set=function(a){return this._setter(a)},b}(w),j=U.FakeObsCell=function(a){function b(a){this._getter=a}return d(b,a),b.prototype.get=function(){return this._getter()},b}(q),y=U.MapEntryCell=function(a){function b(a,b){this._map=a,this._key=b}return d(b,a),b.prototype.get=function(){return this._map.get(this._key)},b.prototype.set=function(a){return this._map.put(this._key,a)},b}(k),s=U.ObsMapEntryCell=function(a){function b(a,b){this._map=a,this._key=b}return d(b,a),b.prototype.get=function(){return this._map.get(this._key)},b}(j),r=U.ObsMap=function(){function b(a){this.x=null!=a?a:{},this.onAdd=new i(function(){var b,c,d;d=[];for(b in a)c=a[b],d.push([b,c]);return d}),this.onRemove=new i,this.onChange=new i}return b.prototype.get=function(a){return T.sub(function(b){return function(c){return U.autoSub(b.onAdd,function(b){var d,e;return d=b[0],e=b[1],a===d?c.refresh():void 0})}}(this)),T.sub(function(b){return function(c){return U.autoSub(b.onChange,function(b){var d,e,f;return e=b[0],d=b[1],f=b[2],a===e?c.refresh():void 0})}}(this)),T.sub(function(b){return function(c){return U.autoSub(b.onRemove,function(b){var d,e;return e=b[0],d=b[1],a===e?c.refresh():void 0})}}(this)),this.x[a]},b.prototype.all=function(){return T.sub(function(a){return function(b){return U.autoSub(a.onAdd,function(){return b.refresh()})}}(this)),T.sub(function(a){return function(b){return U.autoSub(a.onChange,function(){return b.refresh()})}}(this)),T.sub(function(a){return function(b){return U.autoSub(a.onRemove,function(){return b.refresh()})}}(this)),a.clone(this.x)},b.prototype.realPut=function(a,b){var c;return a in this.x?(c=this.x[a],this.x[a]=b,this.onChange.pub([a,c,b]),c):(this.x[a]=b,void this.onAdd.pub([a,b]))},b.prototype.realRemove=function(a){var b;return b=O(this.x,a),this.onRemove.pub([a,b]),b},b.prototype.cell=function(a){return new s(this,a)},b}(),x=U.SrcMap=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return d(b,a),b.prototype.put=function(a,b){return T.mutating(function(c){return function(){return c.realPut(a,b)}}(this))},b.prototype.remove=function(a){return T.mutating(function(b){return function(){return b.realRemove(a)}}(this))},b.prototype.cell=function(a){return new y(this,a)},b}(r),g=U.DepMap=function(a){function b(a){this.f=a,b.__super__.constructor.call(this),U.autoSub(new f(this.f).onSet,function(a){var b,c,d,e,f;c=a[0],e=a[1];for(b in c)d=c[b],b in e||this.realRemove(b);f=[];for(b in e)d=e[b],f.push(this.x[b]!==d?this.realPut(b,d):void 0);return f})}return d(b,a),b}(r),U.liftSpec=function(b){var c,d,e;return a.object(function(){var f,g,h,i;for(h=Object.getOwnPropertyNames(b),i=[],f=0,g=h.length;g>f;f++)c=h[f],e=b[c],null!=e&&(e instanceof U.ObsMap||e instanceof U.ObsCell||e instanceof U.ObsArray)||(d=a.isFunction(e)?null:a.isArray(e)?"array":"cell",i.push([c,{type:d,val:e}]));return i}())},U.lift=function(b,c){var d,e,f;null==c&&(c=U.liftSpec(b));for(e in c)f=c[e],a.some(function(){var a,c,f,g;for(f=[q,p,r],g=[],a=0,c=f.length;c>a;a++)d=f[a],g.push(b[e]instanceof d);return g}())||(b[e]=function(){switch(f.type){case"cell":return U.cell(b[e]);case"array":return U.array(b[e]);case"map":return U.map(b[e]);default:return b[e]}}());return b},U.unlift=function(b){var c,d;return a.object(function(){var a;a=[];for(c in b)d=b[c],a.push([c,d instanceof U.ObsCell?d.get():d instanceof U.ObsArray?d.all():d]);return a}())},U.reactify=function(c,d){var e,f,g,h;return a.isArray(c)?(e=U.array(a.clone(c)),Object.defineProperties(c,a.object(function(){var d,g,h,i;for(h=a.functions(e),i=[],d=0,g=h.length;g>d;d++)f=h[d],"length"!==f&&i.push(function(a){var d,f,g;return d=c[a],f=function(){var f,g,h;return f=1<=arguments.length?b.call(arguments,0):[],null!=d&&(g=d.call.apply(d,[c].concat(b.call(f)))),(h=e[a]).call.apply(h,[e].concat(b.call(f))),g},g={configurable:!0,enumerable:!1,value:f,writable:!0},[a,g]}(f));return i}())),c):Object.defineProperties(c,a.object(function(){var a;a=[];for(g in d)h=d[g],a.push(function(a,c){var d,e,f,g,h;switch(d=null,c.type){case"cell":e=U.cell(null!=(g=c.val)?g:null),d={configurable:!0,enumerable:!0,get:function(){return e.get()},set:function(a){return e.set(a)}};break;case"array":f=U.reactify(null!=(h=c.val)?h:[]),d={configurable:!0,enumerable:!0,get:function(){return f.raw(),f},set:function(a){return f.splice.apply(f,[0,f.length].concat(b.call(a))),f}};break;default:throw new Error("Unknown observable type: "+type)}return[a,d]}(g,h));return a}()))},U.autoReactify=function(b){var c,d,e;return U.reactify(b,a.object(function(){var f,g,h,i;for(h=Object.getOwnPropertyNames(b),i=[],f=0,g=h.length;g>f;f++)c=h[f],e=b[c],e instanceof r||e instanceof q||e instanceof p||(d=a.isFunction(e)?null:a.isArray(e)?"array":"cell",i.push([c,{type:d,val:e}]));return i}()))},a.extend(U,{cell:function(a){return new w(a)},array:function(a,b){return new v(a,b)},map:function(a){return new x(a)}}),U.flatten=function(b){return new e(function(){var c;return a(function(){var a,d,e;for(e=[],a=0,d=b.length;d>a;a++)c=b[a],e.push(c instanceof p?c.raw():c instanceof q?c.get():c);return e}()).chain().flatten(!0).filter(function(a){return null!=a}).value()})},F=function(b){var c;return c=a.flatten(b),U.cellToArray(A(function(){return a.flatten(b)}))},U.cellToArray=function(a,b){return new e(function(){return a.get()},b)},U.basicDiff=function(a){return null==a&&(a=U.smartUidify),function(b,c){var d,e,f,g,h,i,j;for(e=I(function(){var c,e,g;for(g=[],d=c=0,e=b.length;e>c;d=++c)f=b[d],g.push([a(f),d]);return g}()),j=[],g=0,h=c.length;h>g;g++)f=c[g],j.push(null!=(i=e[a(f)])?i:-1);return j}},U.uidify=function(a){var b;return null!=(b=a.__rxUid)?b:Object.defineProperty(a,"__rxUid",{enumerable:!1,value:K()}).__rxUid},U.smartUidify=function(b){return a.isObject(b)?U.uidify(b):JSON.stringify(b)},N=function(b,c,d){var e,f,g,h,i,j;if(h=function(){var a,b,c;for(c=[],a=0,b=d.length;b>a;a++)f=d[a],f>=0&&c.push(f);return c}(),a.some(function(){var a,b,c;for(c=[],f=a=0,b=h.length-1;b>=0?b>a:a>b;f=b>=0?++a:--a)c.push(h[f+1]-h[f]<=0);return c}()))return null;for(j=[],g=-1,f=0;f<d.length;){for(;f<d.length&&d[f]===g+1;)g+=1,f+=1;for(i={index:f,count:0,additions:[]};f<d.length&&-1===d[f];)i.additions.push(c[f]),f+=1;e=f===d.length?b:d[f],i.count=e-(g+1),(i.count>0||i.additions.length>0)&&j.push([i.index,i.count,i.additions]),g=e,f+=1}return j},U.transaction=function(a){return B.transaction(a)},null!=c){c.fn.rx=function(a){var b,c,d,e;return d=this.data("rx-map"),null==d&&this.data("rx-map",d=I()),a in d?d[a]:d[a]=function(){switch(a){case"focused":return c=U.cell(this.is(":focus")),this.focus(function(){return c.set(!0)}),this.blur(function(){return c.set(!1)}),c;case"val":return e=U.cell(this.val()),this.change(function(a){return function(){return e.set(a.val())}}(this)),this.on("input",function(a){return function(){return e.set(a.val())}}(this)),e;case"checked":return b=U.cell(this.is(":checked")),this.change(function(a){return function(){return b.set(a.is(":checked"))}}(this)),b;default:throw new Error("Unknown reactive property type")}}.call(this)},V={},t=V.RawHtml=function(){function a(a){this.html=a}return a}(),D=["blur","change","click","dblclick","error","focus","focusin","focusout","hover","keydown","keypress","keyup","load","mousedown","mouseenter","mouseleave","mousemove","mouseout","mouseover","mouseup","ready","resize","scroll","select","submit","toggle","unload"],Y=V.specialAttrs={init:function(a,b){return b.call(a)}},ab=function(a){return Y[a]=function(b,c){return b[a](function(a){return c.call(b,a)})}};for(bb=0,cb=D.length;cb>bb;bb++)C=D[bb],ab(C);S=["async","autofocus","checked","location","multiple","readOnly","selected","selectedIndex","tagName","nodeName","nodeType","ownerDocument","defaultChecked","defaultSelected"],R=a.object(function(){var a,b,c;for(c=[],a=0,b=S.length;b>a;a++)Q=S[a],c.push([Q,null]);return c}()),X=function(a,b,c){return"value"===b?a.val(c):b in R?a.prop(b,c):a.attr(b,c)},W=function(b,c,d,e){return null==e&&(e=a.identity),d instanceof q?U.autoSub(d.onSet,function(a){var d,f;return f=a[0],d=a[1],X(b,c,e(d))}):X(b,c,e(d))},V.mkAtts=H=function(a){return function(b){var c,d,e;return e=a.match(/[#](\w+)/),e&&(b.id=e[1]),c=a.match(/\.\w+/g),c&&(b["class"]=function(){var a,b,e;for(e=[],a=0,b=c.length;b>a;a++)d=c[a],e.push(d.replace(/^\./,""));return e}().join(" ")),b}({})},V.mktag=J=function(b){return function(d,e){var f,g,h,i,j,k,l,m,n,o;n=null==d&&null==e?[{},null]:d instanceof Object&&null!=e?[d,e]:a.isString(d)&&null!=e?[H(d),e]:null==e&&a.isString(d)||a.isNumber(d)||d instanceof Element||d instanceof t||d instanceof c||a.isArray(d)||d instanceof q||d instanceof p?[{},d]:[d,null],f=n[0],g=n[1],h=c("<"+b+"/>"),o=a.omit(f,a.keys(Y));for(j in o)m=o[j],W(h,j,m);null!=g&&(k=function(b){var d,e,f,g,h;for(h=[],f=0,g=b.length;g>f;f++)if(d=b[f],null!=d)if(a.isString(d)||a.isNumber(d))h.push(document.createTextNode(d));else if(d instanceof Element)h.push(d);else if(d instanceof t){if(e=c(d.html),1!==e.length)throw new Error("RawHtml must wrap a single element");h.push(e[0])}else{if(!(d instanceof c))throw new Error("Unknown element type in array: "+d.constructor.name+" (must be string, number, Element, RawHtml, or jQuery objects)");if(1!==d.length)throw new Error("jQuery object must wrap a single element");h.push(d[0])}else h.push(void 0);return h},l=function(b){var d;if(h.html(""),!a.isArray(b)){if(a.isString(b)||a.isNumber(b)||b instanceof Element||b instanceof t||b instanceof c)return l([b]);throw new Error("Unknown type for element contents: "+b.constructor.name+" (accepted types: string, number, Element, RawHtml, jQuery object of single element, or array of the aforementioned)")}d=k(b),h.append(d)},g instanceof p?U.autoSub(g.onChange,function(a){var b,c,d,e;return c=a[0],d=a[1],b=a[2],h.contents().slice(c,c+d.length).remove(),e=k(b),c===h.contents().length?h.append(e):h.contents().eq(c).before(e)}):g instanceof q?U.autoSub(g.onSet,function(a){var b,c;return b=a[0],c=a[1],l(c)}):l(g));for(i in f)i in Y&&Y[i](h,f[i],f,g);return h}},_=["html","head","title","base","link","meta","style","script","noscript","body","body","section","nav","article","aside","h1","h2","h3","h4","h5","h6","h1","h6","header","footer","address","main","main","p","hr","pre","blockquote","ol","ul","li","dl","dt","dd","dd","figure","figcaption","div","a","em","strong","small","s","cite","q","dfn","abbr","data","time","code","var","samp","kbd","sub","sup","i","b","u","mark","ruby","rt","rp","bdi","bdo","span","br","wbr","ins","del","img","iframe","embed","object","param","object","video","audio","source","video","audio","track","video","audio","canvas","map","area","area","map","svg","math","table","caption","colgroup","col","tbody","thead","tfoot","tr","td","th","form","fieldset","legend","fieldset","label","input","button","select","datalist","optgroup","option","select","datalist","textarea","keygen","output","progress","meter","details","summary","details","menuitem","menu"],V.tags=a.object(function(){var a,b,c;for(c=[],a=0,b=_.length;b>a;a++)$=_[a],c.push([$,V.mktag($)]);return c}()),V.rawHtml=function(a){return new t(a)},V.importTags=function(b){return function(c){return a(null!=c?c:b).extend(V.tags)}}(this),V.cast=function(b,c){var d,e,f;if(null==c&&(c="cell"),!a.isString(c))return e=b,f=c,a.object(function(){var a;a=[];for(d in e)b=e[d],a.push([d,f[d]?V.cast(b,f[d]):b]);return a}());switch(c){case"array":if(b instanceof U.ObsArray)return b;if(a.isArray(b))return new U.DepArray(function(){return b});if(b instanceof U.ObsCell)return new U.DepArray(function(){return b.get()});throw new Error("Cannot cast to array: "+b.constructor.name);case"cell":return b instanceof U.ObsCell?b:A(function(){return b});default:return b}},V.trim=c.trim,V.dasherize=function(a){return V.trim(a).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},V.cssify=function(b){var c,d;return function(){var e;e=[];for(c in b)d=b[c],null!=d&&e.push(""+V.dasherize(c)+": "+(a.isNumber(d)?d+"px":d)+";");return e}().join(" ")},Y.style=function(b,c){return W(b,"style",c,function(b){return a.isString(b)?b:V.cssify(b)})},V.smushClasses=function(b){return a(b).chain().flatten().compact().value().join(" ").replace(/\s+/," ").trim()},Y["class"]=function(b,c){return W(b,"class",c,function(b){return a.isString(b)?b:V.smushClasses(b)})}}return U.rxt=V,U},function(a,b,c){var d,e;if(null!=("undefined"!=typeof define&&null!==define?define.amd:void 0))return define(c,b);if(null!=("undefined"!=typeof module&&null!==module?module.exports:void 0))return e=require("underscore"),d=b(e),module.exports=d;if(null!=a._&&null!=a.$)return a.rx=b(a._,a.$);throw"Dependencies are not met for reactive: _ and $ not found"}(this,a,["underscore","jquery"])}).call(this); |
src/components/Loading/Loading.js | wfp/ui | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import settings from '../../globals/js/settings';
import { componentsX } from '../../internal/FeatureFlags';
const { prefix } = settings;
/** Loading spinners are used when retrieving data or performing slow computations, and help to notify users that loading is underway. */
export default class Loading extends React.Component {
static propTypes = {
/**
* Specify whether you want the loading indicator to be spinning or not
*/
active: PropTypes.bool,
/**
* Provide an optional className to be applied to the containing node
*/
className: PropTypes.string,
/**
* Specify whether you want the loader to be applied with an overlay
*/
withOverlay: PropTypes.bool,
/**
* Specify whether you would like the small variant of <Loading>
*/
small: PropTypes.bool,
};
static defaultProps = {
active: true,
withOverlay: true,
small: false,
};
render() {
const { active, className, withOverlay, small, ...other } = this.props;
const loadingClasses = classNames(`${prefix}--loading`, className, {
[`${prefix}--loading--small`]: small,
[`${prefix}--loading--stop`]: !active,
});
const overlayClasses = classNames(`${prefix}--loading-overlay`, {
[`${prefix}--loading-overlay--stop`]: !active,
});
const loading = (
<div
{...other}
aria-live={active ? 'assertive' : 'off'}
className={loadingClasses}>
<svg className={`${prefix}--loading__svg`} viewBox="-75 -75 150 150">
<title>Loading</title>
{componentsX && small ? (
<circle
className={`${prefix}--loading__background`}
cx="0"
cy="0"
r="37.5"
/>
) : null}
<circle
className={componentsX ? `${prefix}--loading__stroke` : null}
cx="0"
cy="0"
r="37.5"
/>
</svg>
</div>
);
return withOverlay ? (
<div className={overlayClasses}>{loading}</div>
) : (
loading
);
}
}
|
pootle/static/js/admin/components/AdminController.js | evernote/zing | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import Backbone from 'backbone';
import $ from 'jquery';
import React from 'react';
import _ from 'underscore';
import msg from '../../msg';
const AdminController = React.createClass({
propTypes: {
adminModule: React.PropTypes.object.isRequired,
appRoot: React.PropTypes.string.isRequired,
formChoices: React.PropTypes.object.isRequired,
router: React.PropTypes.object.isRequired,
},
/* Lifecycle */
getInitialState() {
return {
items: new this.props.adminModule.Collection(),
selectedItem: null,
searchQuery: '',
view: 'edit',
};
},
componentWillMount() {
this.setupRoutes(this.props.router);
Backbone.history.start({ pushState: true, root: this.props.appRoot });
},
componentWillUpdate(nextProps, nextState) {
if (
nextState.searchQuery !== this.state.searchQuery ||
nextState.selectedItem !== this.state.selectedItem
) {
this.handleURL(nextState);
}
},
setupRoutes(router) {
router.on('route:main', (searchQuery) => {
let query = searchQuery;
if (searchQuery === undefined || searchQuery === null) {
query = '';
}
this.handleSearch(query);
});
router.on('route:edit', (id) => {
this.handleSelectItem(id);
});
},
/* State-changing handlers */
handleSearch(query, extraState) {
const newState = extraState || {};
if (query !== this.state.searchQuery) {
newState.searchQuery = query;
newState.selectedItem = null;
}
return this.state.items.search(query).then(() => {
newState.items = this.state.items;
this.setState(newState);
});
},
handleSelectItem(itemId) {
const item = this.state.items.get(itemId);
if (item) {
this.setState({ selectedItem: item, view: 'edit' });
} else {
const { items } = this.state;
items
.search('')
.then(() => {
/* eslint-disable new-cap */
const deferred = $.Deferred();
/* eslint-enable new-cap */
let newItem = items.get(itemId);
if (newItem !== undefined) {
deferred.resolve(newItem);
} else {
newItem = new this.props.adminModule.Model({ id: itemId });
newItem.fetch({
success: () => {
deferred.resolve(newItem);
},
});
}
return deferred.promise();
})
.then((newItem) => {
items.unshift(newItem, { merge: true });
this.setState({
items,
selectedItem: newItem,
view: 'edit',
});
});
}
},
handleAdd() {
this.setState({ selectedItem: null, view: 'add' });
},
handleCancel() {
this.setState({ selectedItem: null, view: 'edit' });
},
handleSave(item) {
const { items } = this.state;
items.unshift(item, { merge: true });
items.move(item, 0);
this.setState({
items,
selectedItem: item,
view: 'edit',
});
msg.show({
text: gettext('Saved successfully.'),
level: 'success',
});
},
handleDelete() {
this.setState({ selectedItem: null });
msg.show({
text: gettext('Deleted successfully.'),
level: 'danger',
});
},
/* Handlers */
handleURL(newState) {
const { router } = this.props;
const query = newState.searchQuery;
let newURL;
if (newState.selectedItem) {
newURL = `/${newState.selectedItem.id}/`;
} else {
newURL = query === '' ? '/' : `?q=${encodeURIComponent(query)}`;
}
router.navigate(newURL);
},
/* Layout */
render() {
const { Model } = this.props.adminModule;
// Inject dynamic model form choices
// FIXME: hackish and too far from ideal
_.defaults(Model.prototype, { fieldChoices: {} });
_.extend(Model.prototype.fieldChoices, this.props.formChoices);
_.extend(Model.prototype.defaults, this.props.formChoices.defaults);
const props = {
items: this.state.items,
selectedItem: this.state.selectedItem,
searchQuery: this.state.searchQuery,
view: this.state.view,
collection: this.props.adminModule.collection,
model: Model,
onSearch: this.handleSearch,
onSelectItem: this.handleSelectItem,
onAdd: this.handleAdd,
onCancel: this.handleCancel,
onSuccess: this.handleSave,
onDelete: this.handleDelete,
};
return (
<div className="admin-app">
<this.props.adminModule.Controller {...props} />
</div>
);
},
});
export default AdminController;
|
build/javascripts/vendor/jquery-1.8.0.min-5ee64c85.js | euruko2013/site | /*! jQuery [email protected] jquery.com | jquery.org/license */
(function(e,t){function n(e){var t=dt[e]={};return Y.each(e.split(tt),function(e,n){t[n]=!0}),t}function r(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(mt,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:vt.test(r)?Y.parseJSON(r):r}catch(s){}Y.data(e,n,r)}else r=t}return r}function i(e){var t;for(t in e){if(t==="data"&&Y.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function s(){return!1}function o(){return!0}function u(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function a(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function f(e,t,n){t=t||0;if(Y.isFunction(t))return Y.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return Y.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=Y.grep(e,function(e){return e.nodeType===1});if(Bt.test(t))return Y.filter(t,r,!n);t=Y.filter(t,r)}return Y.grep(e,function(e,r){return Y.inArray(e,t)>=0===n})}function l(e){var t=It.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function c(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function h(e,t){if(t.nodeType!==1||!Y.hasData(e))return;var n,r,i,s=Y._data(e),o=Y._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)Y.event.add(t,n,u[n][r])}o.data&&(o.data=Y.extend({},o.data))}function p(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),Y.support.html5Clone&&e.innerHTML&&!Y.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Kt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(Y.expando)}function d(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function v(e){Kt.test(e.type)&&(e.defaultChecked=e.checked)}function m(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=gn.length;while(i--){t=gn[i]+n;if(t in e)return t}return r}function g(e,t){return e=t||e,Y.css(e,"display")==="none"||!Y.contains(e.ownerDocument,e)}function y(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=Y._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&g(n)&&(i[s]=Y._data(n,"olddisplay",S(n.nodeName)))):(r=nn(n,"display"),!i[s]&&r!=="none"&&Y._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function b(e,t,n){var r=ln.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function w(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=Y.css(e,n+mn[i],!0)),r?(n==="content"&&(s-=parseFloat(nn(e,"padding"+mn[i]))||0),n!=="margin"&&(s-=parseFloat(nn(e,"border"+mn[i]+"Width"))||0)):(s+=parseFloat(nn(e,"padding"+mn[i]))||0,n!=="padding"&&(s+=parseFloat(nn(e,"border"+mn[i]+"Width"))||0));return s}function E(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=Y.support.boxSizing&&Y.css(e,"boxSizing")==="border-box";if(r<=0){r=nn(e,t);if(r<0||r==null)r=e.style[t];if(cn.test(r))return r;i=s&&(Y.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+w(e,t,n||(s?"border":"content"),i)+"px"}function S(e){if(pn[e])return pn[e];var t=Y("<"+e+">").appendTo(R.body),n=t.css("display");t.remove();if(n==="none"||n===""){rn=R.body.appendChild(rn||Y.extend(R.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!sn||!rn.createElement)sn=(rn.contentWindow||rn.contentDocument).document,sn.write("<!doctype html><html><body>"),sn.close();t=sn.body.appendChild(sn.createElement(e)),n=nn(t,"display"),R.body.removeChild(rn)}return pn[e]=n,n}function x(e,t,n,r){var i;if(Y.isArray(t))Y.each(t,function(t,i){n||wn.test(e)?r(e,i):x(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&Y.type(t)==="object")for(i in t)x(e+"["+i+"]",t[i],n,r);else r(e,t)}function T(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(tt),u=0,a=o.length;if(Y.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function N(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Bn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=N(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=N(e,n,r,i,"*",o)),u}function C(e,n){var r,i,s=Y.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&Y.extend(!0,e,i)}function k(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function L(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function A(){try{return new e.XMLHttpRequest}catch(t){}}function O(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function M(){return setTimeout(function(){$n=t},0),$n=Y.now()}function _(e,t){Y.each(t,function(t,n){var r=(Zn[t]||[]).concat(Zn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function D(e,t,n){var r,i=0,s=0,o=Yn.length,u=Y.Deferred().always(function(){delete a.elem}),a=function(){var t=$n||M(),n=Math.max(0,f.startTime+f.duration-t),r=1-(n/f.duration||0),i=0,s=f.tweens.length;for(;i<s;i++)f.tweens[i].run(r);return u.notifyWith(e,[f,r,n]),r<1&&s?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:Y.extend({},t),opts:Y.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:$n||M(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=Y.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;P(l,f.opts.specialEasing);for(;i<o;i++){r=Yn[i].call(f,e,l,f.opts);if(r)return r}return _(f,l),Y.isFunction(f.opts.start)&&f.opts.start.call(e,f),Y.fx.timer(Y.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function P(e,t){var n,r,i,s,o;for(n in e){r=Y.camelCase(n),i=t[r],s=e[n],Y.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=Y.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function H(e,t,n){var r,i,s,o,u,a,f,l,c=this,h=e.style,p={},d=[],v=e.nodeType&&g(e);n.queue||(f=Y._queueHooks(e,"fx"),f.unqueued==null&&(f.unqueued=0,l=f.empty.fire,f.empty.fire=function(){f.unqueued||l()}),f.unqueued++,c.always(function(){c.always(function(){f.unqueued--,Y.queue(e,"fx").length||f.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],Y.css(e,"display")==="inline"&&Y.css(e,"float")==="none"&&(!Y.support.inlineBlockNeedsLayout||S(e.nodeName)==="inline"?h.display="inline-block":h.zoom=1)),n.overflow&&(h.overflow="hidden",Y.support.shrinkWrapBlocks||c.done(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Kn.exec(s)){delete t[r];if(s===(v?"hide":"show"))continue;d.push(r)}}o=d.length;if(o){u=Y._data(e,"fxshow")||Y._data(e,"fxshow",{}),v?Y(e).show():c.done(function(){Y(e).hide()}),c.done(function(){var t;Y.removeData(e,"fxshow",!0);for(t in p)Y.style(e,t,p[t])});for(r=0;r<o;r++)i=d[r],a=c.createTween(i,v?u[i]:0),p[i]=u[i]||Y.style(e,i),i in u||(u[i]=a.start,v&&(a.end=a.start,a.start=i==="width"||i==="height"?1:0))}}function B(e,t,n,r,i){return new B.prototype.init(e,t,n,r,i)}function j(e,t){var n,r={height:e},i=0;for(;i<4;i+=2-t)n=mn[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function F(e){return Y.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var I,q,R=e.document,U=e.location,z=e.navigator,W=e.jQuery,X=e.$,V=Array.prototype.push,$=Array.prototype.slice,J=Array.prototype.indexOf,K=Object.prototype.toString,Q=Object.prototype.hasOwnProperty,G=String.prototype.trim,Y=function(e,t){return new Y.fn.init(e,t,I)},Z=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,et=/\S/,tt=/\s+/,nt=et.test(" ")?/^[\s\xA0]+|[\s\xA0]+$/g:/^\s+|\s+$/g,rt=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,it=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,st=/^[\],:{}\s]*$/,ot=/(?:^|:|,)(?:\s*\[)+/g,ut=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,at=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,ft=/^-ms-/,lt=/-([\da-z])/gi,ct=function(e,t){return(t+"").toUpperCase()},ht=function(){R.addEventListener?(R.removeEventListener("DOMContentLoaded",ht,!1),Y.ready()):R.readyState==="complete"&&(R.detachEvent("onreadystatechange",ht),Y.ready())},pt={};Y.fn=Y.prototype={constructor:Y,init:function(e,n,r){var i,s,o,u;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?i=[null,e,null]:i=rt.exec(e);if(i&&(i[1]||!n)){if(i[1])return n=n instanceof Y?n[0]:n,u=n&&n.nodeType?n.ownerDocument||n:R,e=Y.parseHTML(i[1],u,!0),it.test(i[1])&&Y.isPlainObject(n)&&this.attr.call(e,n,!0),Y.merge(this,e);s=R.getElementById(i[2]);if(s&&s.parentNode){if(s.id!==i[2])return r.find(e);this.length=1,this[0]=s}return this.context=R,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return Y.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),Y.makeArray(e,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return $.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=Y.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return Y.each(this,e,t)},ready:function(e){return Y.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack($.apply(this,arguments),"slice",$.call(arguments).join(","))},map:function(e){return this.pushStack(Y.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:V,sort:[].sort,splice:[].splice},Y.fn.init.prototype=Y.fn,Y.extend=Y.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!Y.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(Y.isPlainObject(i)||(s=Y.isArray(i)))?(s?(s=!1,o=r&&Y.isArray(r)?r:[]):o=r&&Y.isPlainObject(r)?r:{},u[n]=Y.extend(l,o,i)):i!==t&&(u[n]=i)}return u},Y.extend({noConflict:function(t){return e.$===Y&&(e.$=X),t&&e.jQuery===Y&&(e.jQuery=W),Y},isReady:!1,readyWait:1,holdReady:function(e){e?Y.readyWait++:Y.ready(!0)},ready:function(e){if(e===!0?--Y.readyWait:Y.isReady)return;if(!R.body)return setTimeout(Y.ready,1);Y.isReady=!0;if(e!==!0&&--Y.readyWait>0)return;q.resolveWith(R,[Y]),Y.fn.trigger&&Y(R).trigger("ready").off("ready")},isFunction:function(e){return Y.type(e)==="function"},isArray:Array.isArray||function(e){return Y.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):pt[K.call(e)]||"object"},isPlainObject:function(e){if(!e||Y.type(e)!=="object"||e.nodeType||Y.isWindow(e))return!1;try{if(e.constructor&&!Q.call(e,"constructor")&&!Q.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||Q.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||R,(r=it.exec(e))?[t.createElement(r[1])]:(r=Y.buildFragment([e],t,n?null:[]),Y.merge([],(r.cacheable?Y.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=Y.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(st.test(t.replace(ut,"@").replace(at,"]").replace(ot,"")))return(new Function("return "+t))();Y.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&Y.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&et.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(ft,"ms-").replace(lt,ct)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toUpperCase()===t.toUpperCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||Y.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:G?function(e){return e==null?"":G.call(e)}:function(e){return e==null?"":e.toString().replace(nt,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=Y.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||Y.isWindow(e)?V.call(r,e):Y.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(J)return J.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof Y||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||Y.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),Y.isFunction(e)?(i=$.call(arguments,2),s=function(){return e.apply(n,i.concat($.call(arguments)))},s.guid=e.guid=e.guid||s.guid||Y.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)Y.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&Y.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(Y(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),Y.ready.promise=function(t){if(!q){q=Y.Deferred();if(R.readyState==="complete"||R.readyState!=="loading"&&R.addEventListener)setTimeout(Y.ready,1);else if(R.addEventListener)R.addEventListener("DOMContentLoaded",ht,!1),e.addEventListener("load",Y.ready,!1);else{R.attachEvent("onreadystatechange",ht),e.attachEvent("onload",Y.ready);var n=!1;try{n=e.frameElement==null&&R.documentElement}catch(r){}n&&n.doScroll&&function i(){if(!Y.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}Y.ready()}}()}}return q.promise(t)},Y.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){pt["[object "+t+"]"]=t.toLowerCase()}),I=Y(R);var dt={};Y.Callbacks=function(e){e=typeof e=="string"?dt[e]||n(e):Y.extend({},e);var r,i,s,o,u,a,f=[],l=!e.once&&[],c=function(t){r=e.memory&&t,i=!0,a=o||0,o=0,u=f.length,s=!0;for(;f&&a<u;a++)if(f[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}s=!1,f&&(l?l.length&&c(l.shift()):r?f=[]:h.disable())},h={add:function(){if(f){var t=f.length;(function n(t){Y.each(t,function(t,r){Y.isFunction(r)&&(!e.unique||!h.has(r))?f.push(r):r&&r.length&&n(r)})})(arguments),s?u=f.length:r&&(o=t,c(r))}return this},remove:function(){return f&&Y.each(arguments,function(e,t){var n;while((n=Y.inArray(t,f,n))>-1)f.splice(n,1),s&&(n<=u&&u--,n<=a&&a--)}),this},has:function(e){return Y.inArray(e,f)>-1},empty:function(){return f=[],this},disable:function(){return f=l=r=t,this},disabled:function(){return!f},lock:function(){return l=t,r||h.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],f&&(!i||l)&&(s?l.push(t):c(t)),this},fire:function(){return h.fireWith(this,arguments),this},fired:function(){return!!i}};return h},Y.extend({Deferred:function(e){var t=[["resolve","done",Y.Callbacks("once memory"),"resolved"],["reject","fail",Y.Callbacks("once memory"),"rejected"],["notify","progress",Y.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return Y.Deferred(function(n){Y.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](Y.isFunction(o)?function(){var e=o.apply(this,arguments);e&&Y.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return typeof e=="object"?Y.extend(e,r):r}},i={};return r.pipe=r.then,Y.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=$.call(arguments),r=n.length,i=r!==1||e&&Y.isFunction(e.promise)?r:0,s=i===1?e:Y.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?$.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&Y.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),Y.support=function(){var t,n,r,i,s,o,u,a,f,l,c,h=R.createElement("div");h.setAttribute("className","t"),h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=h.getElementsByTagName("*"),r=h.getElementsByTagName("a")[0],r.style.cssText="top:1px;float:left;opacity:.5";if(!n||!n.length||!r)return{};i=R.createElement("select"),s=i.appendChild(R.createElement("option")),o=h.getElementsByTagName("input")[0],t={leadingWhitespace:h.firstChild.nodeType===3,tbody:!h.getElementsByTagName("tbody").length,htmlSerialize:!!h.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:o.value==="on",optSelected:s.selected,getSetAttribute:h.className!=="t",enctype:!!R.createElement("form").enctype,html5Clone:R.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:R.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,i.disabled=!0,t.optDisabled=!s.disabled;try{delete h.test}catch(p){t.deleteExpando=!1}!h.addEventListener&&h.attachEvent&&h.fireEvent&&(h.attachEvent("onclick",c=function(){t.noCloneEvent=!1}),h.cloneNode(!0).fireEvent("onclick"),h.detachEvent("onclick",c)),o=R.createElement("input"),o.value="t",o.setAttribute("type","radio"),t.radioValue=o.value==="t",o.setAttribute("checked","checked"),o.setAttribute("name","t"),h.appendChild(o),u=R.createDocumentFragment(),u.appendChild(h.lastChild),t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=o.checked,u.removeChild(o),u.appendChild(h);if(h.attachEvent)for(f in{submit:!0,change:!0,focusin:!0})a="on"+f,l=a in h,l||(h.setAttribute(a,"return;"),l=typeof h[a]=="function"),t[f+"Bubbles"]=l;return Y(function(){var n,r,i,s,o="padding:0;margin:0;border:0;display:block;overflow:hidden;",u=R.getElementsByTagName("body")[0];if(!u)return;n=R.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",u.insertBefore(n,u.firstChild),r=R.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=r.getElementsByTagName("td"),i[0].style.cssText="padding:0;margin:0;border:0;display:none",l=i[0].offsetHeight===0,i[0].style.display="",i[1].style.display="none",t.reliableHiddenOffsets=l&&i[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=u.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",s=R.createElement("div"),s.style.cssText=r.style.cssText=o,s.style.marginRight=s.style.width="0",r.style.width="1px",r.appendChild(s),t.reliableMarginRight=!parseFloat((e.getComputedStyle(s,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=o+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),u.removeChild(n),n=r=i=s=null}),u.removeChild(h),n=r=i=s=o=u=h=null,t}();var vt=/^(?:\{.*\}|\[.*\])$/,mt=/([A-Z])/g;Y.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(Y.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?Y.cache[e[Y.expando]]:e[Y.expando],!!e&&!i(e)},data:function(e,n,r,i){if(!Y.acceptData(e))return;var s,o,u=Y.expando,a=typeof n=="string",f=e.nodeType,l=f?Y.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=Y.deletedIds.pop()||++Y.uuid:c=u),l[c]||(l[c]={},f||(l[c].toJSON=Y.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=Y.extend(l[c],n):l[c].data=Y.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[Y.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[Y.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!Y.acceptData(e))return;var r,s,o,u=e.nodeType,a=u?Y.cache:e,f=u?e[Y.expando]:Y.expando;if(!a[f])return;if(t){r=n?a[f]:a[f].data;if(r){Y.isArray(t)||(t in r?t=[t]:(t=Y.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(s=0,o=t.length;s<o;s++)delete r[t[s]];if(!(n?i:Y.isEmptyObject)(r))return}}if(!n){delete a[f].data;if(!i(a[f]))return}u?Y.cleanData([e],!0):Y.support.deleteExpando||a!=a.window?delete a[f]:a[f]=null},_data:function(e,t,n){return Y.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&Y.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),Y.fn.extend({data:function(e,n){var i,s,o,u,a,f=this[0],l=0,c=null;if(e===t){if(this.length){c=Y.data(f);if(f.nodeType===1&&!Y._data(f,"parsedAttrs")){o=f.attributes;for(a=o.length;l<a;l++)u=o[l].name,u.indexOf("data-")===0&&(u=Y.camelCase(u.substring(5)),r(f,u,c[u]));Y._data(f,"parsedAttrs",!0)}}return c}return typeof e=="object"?this.each(function(){Y.data(this,e)}):(i=e.split(".",2),i[1]=i[1]?"."+i[1]:"",s=i[1]+"!",Y.access(this,function(n){if(n===t)return c=this.triggerHandler("getData"+s,[i[0]]),c===t&&f&&(c=Y.data(f,e),c=r(f,e,c)),c===t&&i[1]?this.data(i[0]):c;i[1]=n,this.each(function(){var t=Y(this);t.triggerHandler("setData"+s,i),Y.data(this,e,n),t.triggerHandler("changeData"+s,i)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){Y.removeData(this,e)})}}),Y.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=Y._data(e,t),n&&(!r||Y.isArray(n)?r=Y._data(e,t,Y.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=Y.queue(e,t),r=n.shift(),i=Y._queueHooks(e,t),s=function(){Y.dequeue(e,t)};r==="inprogress"&&(r=n.shift()),r&&(t==="fx"&&n.unshift("inprogress"),delete i.stop,r.call(e,s,i)),!n.length&&i&&i.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Y._data(e,n)||Y._data(e,n,{empty:Y.Callbacks("once memory").add(function(){Y.removeData(e,t+"queue",!0),Y.removeData(e,n,!0)})})}}),Y.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?Y.queue(this[0],e):n===t?this:this.each(function(){var t=Y.queue(this,e,n);Y._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&Y.dequeue(this,e)})},dequeue:function(e){return this.each(function(){Y.dequeue(this,e)})},delay:function(e,t){return e=Y.fx?Y.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=Y.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)(r=Y._data(o[u],e+"queueHooks"))&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var gt,yt,bt,wt=/[\t\r\n]/g,Et=/\r/g,St=/^(?:button|input)$/i,xt=/^(?:button|input|object|select|textarea)$/i,Tt=/^a(?:rea|)$/i,Nt=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,Ct=Y.support.getSetAttribute;Y.fn.extend({attr:function(e,t){return Y.access(this,Y.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){Y.removeAttr(this,e)})},prop:function(e,t){return Y.access(this,Y.prop,e,t,arguments.length>1)},removeProp:function(e){return e=Y.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(Y.isFunction(e))return this.each(function(t){Y(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(tt);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)~s.indexOf(" "+t[o]+" ")||(s+=t[o]+" ");i.className=Y.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(Y.isFunction(e))return this.each(function(t){Y(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(tt);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(wt," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>-1)r=r.replace(" "+n[s]+" "," ");i.className=e?Y.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return Y.isFunction(e)?this.each(function(n){Y(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=Y(this),u=t,a=e.split(tt);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&Y._data(this,"__className__",this.className),this.className=this.className||e===!1?"":Y._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(wt," ").indexOf(t)>-1)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=Y.valHooks[s.type]||Y.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(Et,""):r==null?"":r);return}return i=Y.isFunction(e),this.each(function(r){var s,o=Y(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":Y.isArray(s)&&(s=Y.map(s,function(e){return e==null?"":e+""})),n=Y.valHooks[this.type]||Y.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),Y.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r,i,s=e.selectedIndex,o=[],u=e.options,a=e.type==="select-one";if(s<0)return null;n=a?s:0,r=a?s+1:u.length;for(;n<r;n++){i=u[n];if(i.selected&&(Y.support.optDisabled?!i.disabled:i.getAttribute("disabled")===null)&&(!i.parentNode.disabled||!Y.nodeName(i.parentNode,"optgroup"))){t=Y(i).val();if(a)return t;o.push(t)}}return a&&!o.length&&u.length?Y(u[s]).val():o},set:function(e,t){var n=Y.makeArray(t);return Y(e).find("option").each(function(){this.selected=Y.inArray(Y(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&Y.isFunction(Y.fn[n]))return Y(e)[n](r);if(typeof e.getAttribute=="undefined")return Y.prop(e,n,r);u=a!==1||!Y.isXMLDoc(e),u&&(n=n.toLowerCase(),o=Y.attrHooks[n]||(Nt.test(n)?yt:gt));if(r!==t){if(r===null){Y.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,""+r),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(tt);for(;o<r.length;o++)i=r[o],i&&(n=Y.propFix[i]||i,s=Nt.test(i),s||Y.attr(e,i,""),e.removeAttribute(Ct?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(St.test(e.nodeName)&&e.parentNode)Y.error("type property can't be changed");else if(!Y.support.radioValue&&t==="radio"&&Y.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return gt&&Y.nodeName(e,"button")?gt.get(e,t):t in e?e.value:null},set:function(e,t,n){if(gt&&Y.nodeName(e,"button"))return gt.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!Y.isXMLDoc(e),o&&(n=Y.propFix[n]||n,s=Y.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):xt.test(e.nodeName)||Tt.test(e.nodeName)&&e.href?0:t}}}}),yt={get:function(e,n){var r,i=Y.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?Y.removeAttr(e,n):(r=Y.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},Ct||(bt={name:!0,id:!0,coords:!0},gt=Y.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(bt[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=R.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},Y.each(["width","height"],function(e,t){Y.attrHooks[t]=Y.extend(Y.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),Y.attrHooks.contenteditable={get:gt.get,set:function(e,t,n){t===""&&(t="false"),gt.set(e,t,n)}}),Y.support.hrefNormalized||Y.each(["href","src","width","height"],function(e,n){Y.attrHooks[n]=Y.extend(Y.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),Y.support.style||(Y.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:
function(e,t){return e.style.cssText=""+t}}),Y.support.optSelected||(Y.propHooks.selected=Y.extend(Y.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),Y.support.enctype||(Y.propFix.enctype="encoding"),Y.support.checkOn||Y.each(["radio","checkbox"],function(){Y.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),Y.each(["radio","checkbox"],function(){Y.valHooks[this]=Y.extend(Y.valHooks[this],{set:function(e,t){if(Y.isArray(t))return e.checked=Y.inArray(Y(e).val(),t)>=0}})});var kt=/^(?:textarea|input|select)$/i,Lt=/^([^\.]*|)(?:\.(.+)|)$/,At=/(?:^|\s)hover(\.\S+|)\b/,Ot=/^key/,Mt=/^(?:mouse|contextmenu)|click/,_t=/^(?:focusinfocus|focusoutblur)$/,Dt=function(e){return Y.event.special.hover?e:e.replace(At,"mouseenter$1 mouseleave$1")};Y.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,v,m;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=Y._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=Y.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof Y=="undefined"||!!e&&Y.event.triggered===e.type?t:Y.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=Y.trim(Dt(n)).split(" ");for(f=0;f<n.length;f++){l=Lt.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),m=Y.event.special[c]||{},c=(s?m.delegateType:m.bindType)||c,m=Y.event.special[c]||{},p=Y.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,namespace:h.join(".")},d),v=a[c];if(!v){v=a[c]=[],v.delegateCount=0;if(!m.setup||m.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}m.add&&(m.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?v.splice(v.delegateCount++,0,p):v.push(p),Y.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,v,m=Y.hasData(e)&&Y._data(e);if(!m||!(h=m.events))return;t=Y.trim(Dt(t||"")).split(" ");for(s=0;s<t.length;s++){o=Lt.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)Y.event.remove(e,u+t[s],n,r,!0);continue}p=Y.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)v=d[c],(i||a===v.origType)&&(!n||n.guid===v.guid)&&(!f||f.test(v.namespace))&&(!r||r===v.selector||r==="**"&&v.selector)&&(d.splice(c--,1),v.selector&&d.delegateCount--,p.remove&&p.remove.call(e,v));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,m.handle)===!1)&&Y.removeEvent(e,u,m.handle),delete h[u])}Y.isEmptyObject(h)&&(delete m.handle,Y.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,i,s){if(!i||i.nodeType!==3&&i.nodeType!==8){var o,u,a,f,l,c,h,p,d,v,m=n.type||n,g=[];if(_t.test(m+Y.event.triggered))return;m.indexOf("!")>=0&&(m=m.slice(0,-1),u=!0),m.indexOf(".")>=0&&(g=m.split("."),m=g.shift(),g.sort());if((!i||Y.event.customEvent[m])&&!Y.event.global[m])return;n=typeof n=="object"?n[Y.expando]?n:new Y.Event(m,n):new Y.Event(m),n.type=m,n.isTrigger=!0,n.exclusive=u,n.namespace=g.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,c=m.indexOf(":")<0?"on"+m:"";if(!i){o=Y.cache;for(a in o)o[a].events&&o[a].events[m]&&Y.event.trigger(n,r,o[a].handle.elem,!0);return}n.result=t,n.target||(n.target=i),r=r!=null?Y.makeArray(r):[],r.unshift(n),h=Y.event.special[m]||{};if(h.trigger&&h.trigger.apply(i,r)===!1)return;d=[[i,h.bindType||m]];if(!s&&!h.noBubble&&!Y.isWindow(i)){v=h.delegateType||m,f=_t.test(v+m)?i:i.parentNode;for(l=i;f;f=f.parentNode)d.push([f,v]),l=f;l===(i.ownerDocument||R)&&d.push([l.defaultView||l.parentWindow||e,v])}for(a=0;a<d.length&&!n.isPropagationStopped();a++)f=d[a][0],n.type=d[a][1],p=(Y._data(f,"events")||{})[n.type]&&Y._data(f,"handle"),p&&p.apply(f,r),p=c&&f[c],p&&Y.acceptData(f)&&p.apply(f,r)===!1&&n.preventDefault();return n.type=m,!s&&!n.isDefaultPrevented()&&(!h._default||h._default.apply(i.ownerDocument,r)===!1)&&(m!=="click"||!Y.nodeName(i,"a"))&&Y.acceptData(i)&&c&&i[m]&&(m!=="focus"&&m!=="blur"||n.target.offsetWidth!==0)&&!Y.isWindow(i)&&(l=i[c],l&&(i[c]=null),Y.event.triggered=m,i[m](),Y.event.triggered=t,l&&(i[c]=l)),n.result}return},dispatch:function(n){n=Y.event.fix(n||e.event);var r,i,s,o,u,a,f,l,c,h,p,d=(Y._data(this,"events")||{})[n.type]||[],v=d.delegateCount,m=[].slice.call(arguments),g=!n.exclusive&&!n.namespace,y=Y.event.special[n.type]||{},b=[];m[0]=n,n.delegateTarget=this;if(y.preDispatch&&y.preDispatch.call(this,n)===!1)return;if(v&&(!n.button||n.type!=="click")){o=Y(this),o.context=this;for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){a={},l=[],o[0]=s;for(r=0;r<v;r++)c=d[r],h=c.selector,a[h]===t&&(a[h]=o.is(h)),a[h]&&l.push(c);l.length&&b.push({elem:s,matches:l})}}d.length>v&&b.push({elem:this,matches:d.slice(v)});for(r=0;r<b.length&&!n.isPropagationStopped();r++){f=b[r],n.currentTarget=f.elem;for(i=0;i<f.matches.length&&!n.isImmediatePropagationStopped();i++){c=f.matches[i];if(g||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,u=((Y.event.special[c.origType]||{}).handle||c.handler).apply(f.elem,m),u!==t&&(n.result=u,u===!1&&(n.preventDefault(),n.stopPropagation()))}}return y.postDispatch&&y.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,s,o=n.button,u=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||R,i=r.documentElement,s=r.body,e.pageX=n.clientX+(i&&i.scrollLeft||s&&s.scrollLeft||0)-(i&&i.clientLeft||s&&s.clientLeft||0),e.pageY=n.clientY+(i&&i.scrollTop||s&&s.scrollTop||0)-(i&&i.clientTop||s&&s.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),!e.which&&o!==t&&(e.which=o&1?1:o&2?3:o&4?2:0),e}},fix:function(e){if(e[Y.expando])return e;var t,n,r=e,i=Y.event.fixHooks[e.type]||{},s=i.props?this.props.concat(i.props):this.props;e=Y.Event(r);for(t=s.length;t;)n=s[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||R),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,i.filter?i.filter(e,r):e},special:{ready:{setup:Y.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){Y.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=Y.extend(new Y.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?Y.event.trigger(i,null,t):Y.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},Y.event.handle=Y.event.dispatch,Y.removeEvent=R.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},Y.Event=function(e,t){if(!(this instanceof Y.Event))return new Y.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?o:s):this.type=e,t&&Y.extend(this,t),this.timeStamp=e&&e.timeStamp||Y.now(),this[Y.expando]=!0},Y.Event.prototype={preventDefault:function(){this.isDefaultPrevented=o;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=o;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=o,this.stopPropagation()},isDefaultPrevented:s,isPropagationStopped:s,isImmediatePropagationStopped:s},Y.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){Y.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!Y.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),Y.support.submitBubbles||(Y.event.special.submit={setup:function(){if(Y.nodeName(this,"form"))return!1;Y.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=Y.nodeName(n,"input")||Y.nodeName(n,"button")?n.form:t;r&&!Y._data(r,"_submit_attached")&&(Y.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),Y._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&Y.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(Y.nodeName(this,"form"))return!1;Y.event.remove(this,"._submit")}}),Y.support.changeBubbles||(Y.event.special.change={setup:function(){if(kt.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")Y.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),Y.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),Y.event.simulate("change",this,e,!0)});return!1}Y.event.add(this,"beforeactivate._change",function(e){var t=e.target;kt.test(t.nodeName)&&!Y._data(t,"_change_attached")&&(Y.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&Y.event.simulate("change",this.parentNode,e,!0)}),Y._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return Y.event.remove(this,"._change"),kt.test(this.nodeName)}}),Y.support.focusinBubbles||Y.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){Y.event.simulate(t,e.target,Y.event.fix(e),!0)};Y.event.special[t]={setup:function(){n++===0&&R.addEventListener(e,r,!0)},teardown:function(){--n===0&&R.removeEventListener(e,r,!0)}}}),Y.fn.extend({on:function(e,n,r,i,o){var u,a;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=s;else if(!i)return this;return o===1&&(u=i,i=function(e){return Y().off(e),u.apply(this,arguments)},i.guid=u.guid||(u.guid=Y.guid++)),this.each(function(){Y.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,Y(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(o in e)this.off(o,n,e[o]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=s),this.each(function(){Y.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return Y(this.context).on(e,this.selector,t,n),this},die:function(e,t){return Y(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length==1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){Y.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return Y.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||Y.guid++,r=0,i=function(n){var i=(Y._data(this,"lastToggle"+e.guid)||0)%r;return Y._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),Y.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){Y.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Ot.test(t)&&(Y.event.fixHooks[t]=Y.event.keyHooks),Mt.test(t)&&(Y.event.fixHooks[t]=Y.event.mouseHooks)}),function(e,t){function n(e,t,n,r){var i=0,s=t.length;for(;i<s;i++)st(e,t[i],n,r)}function r(e,t,r,i,s,o){var u,a=ot.setFilters[t.toLowerCase()];return a||st.error(t),(e||!(u=s))&&n(e||"*",i,u=[],s),u.length>0?a(u,r,o):[]}function i(e,i,s,o,u){var a,f,l,c,h,p,d,v,m=0,g=u.length,y=W.POS,b=new RegExp("^"+y.source+"(?!"+T+")","i"),w=function(){var e=1,n=arguments.length-2;for(;e<n;e++)arguments[e]===t&&(a[e]=t)};for(;m<g;m++){y.exec(""),e=u[m],c=[],l=0,h=o;while(a=y.exec(e)){v=y.lastIndex=a.index+a[0].length;if(v>l){d=e.slice(l,a.index),l=v,p=[i],P.test(d)&&(h&&(p=h),h=o);if(f=q.test(d))d=d.slice(0,-5).replace(P,"$&*");a.length>1&&a[0].replace(b,w),h=r(d,a[1],a[2],p,h,f)}}h?(c=c.concat(h),(d=e.slice(l))&&d!==")"?P.test(d)?n(d,c,s,o):st(d,i,s,o?o.concat(h):h):S.apply(s,c)):st(e,i,s,o)}return g===1?s:st.uniqueSort(s)}function s(e,t,n){var r,i,s,o=[],u=0,a=B.exec(e),f=!a.pop()&&!a.pop(),l=f&&e.match(H)||[""],c=ot.preFilter,h=ot.filter,p=!n&&t!==v;for(;(i=l[u])!=null&&f;u++){o.push(r=[]),p&&(i=" "+i);while(i){f=!1;if(a=P.exec(i))i=i.slice(a[0].length),f=r.push({part:a.pop().replace(D," "),captures:a});for(s in h)(a=W[s].exec(i))&&(!c[s]||(a=c[s](a,t,n)))&&(i=i.slice(a.shift().length),f=r.push({part:s,captures:a}));if(!f)break}}return f||st.error(e),o}function o(e,t,n){var r=t.dir,i=w++;return e||(e=function(e){return e===n}),t.first?function(t,n){while(t=t[r])if(t.nodeType===1)return e(t,n)&&t}:function(t,n){var s,o=i+"."+c,u=o+"."+l;while(t=t[r])if(t.nodeType===1){if((s=t[x])===u)return t.sizset;if(typeof s=="string"&&s.indexOf(o)===0){if(t.sizset)return t}else{t[x]=u;if(e(t,n))return t.sizset=!0,t;t.sizset=!1}}}}function u(e,t){return e?function(n,r){var i=t(n,r);return i&&e(i===!0?n:i,r)}:t}function a(e,t,n){var r,i,s=0;for(;r=e[s];s++)ot.relative[r.part]?i=o(i,ot.relative[r.part],t):(r.captures.push(t,n),i=u(i,ot.filter[r.part].apply(null,r.captures)));return i}function f(e){return function(t,n){var r,i=0;for(;r=e[i];i++)if(r(t,n))return!0;return!1}}var l,c,h,p,d,v=e.document,m=v.documentElement,g="undefined",y=!1,b=!0,w=0,E=[].slice,S=[].push,x=("sizcache"+Math.random()).replace(".",""),T="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",C=N.replace("w","w#"),k="([*^$|!~]?=)",L="\\["+T+"*("+N+")"+T+"*(?:"+k+T+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+C+")|)|)"+T+"*\\]",A=":("+N+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",O=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",M=T+"*([\\x20\\t\\r\\n\\f>+~])"+T+"*",_="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+L+"|"+A.replace(2,7)+"|[^\\\\(),])+",D=new RegExp("^"+T+"+|((?:^|[^\\\\])(?:\\\\.)*)"+T+"+$","g"),P=new RegExp("^"+M),H=new RegExp(_+"?(?="+T+"*,|$)","g"),B=new RegExp("^(?:(?!,)(?:(?:^|,)"+T+"*"+_+")*?|"+T+"*(.*?))(\\)|$)"),j=new RegExp(_.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+M,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,I=/[\x20\t\r\n\f]*[+~]/,q=/:not\($/,R=/h\d/i,U=/input|select|textarea|button/i,z=/\\(?!\\)/g,W={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),NAME:new RegExp("^\\[name=['\"]?("+N+")['\"]?\\]"),TAG:new RegExp("^("+N.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+L),PSEUDO:new RegExp("^"+A),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+T+"*(even|odd|(([+-]|)(\\d*)n|)"+T+"*(?:([+-]|)"+T+"*(\\d+)|))"+T+"*\\)|)","i"),POS:new RegExp(O,"ig"),needsContext:new RegExp("^"+T+"*[>+~]|"+O,"i")},X={},V=[],$={},J=[],K=function(e){return e.sizzleFilter=!0,e},Q=function(e){return function(t){return t.nodeName.toLowerCase()==="input"&&t.type===e}},G=function(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}},Z=function(e){var t=!1,n=v.createElement("div");try{t=e(n)}catch(r){}return n=null,t},et=Z(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),tt=Z(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",m.insertBefore(e,m.firstChild);var t=v.getElementsByName&&v.getElementsByName(x).length===2+v.getElementsByName(x+0).length;return d=!v.getElementById(x),m.removeChild(e),t}),nt=Z(function(e){return e.appendChild(v.createComment("")),e.getElementsByTagName("*").length===0}),rt=Z(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==g&&e.firstChild.getAttribute("href")==="#"}),it=Z(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||e.getElementsByClassName("e").length===0?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length!==1)}),st=function(e,t,n,r){n=n||[],t=t||v;var i,s,o,u,a=t.nodeType;if(a!==1&&a!==9)return[];if(!e||typeof e!="string")return n;o=at(t);if(!o&&!r)if(i=F.exec(e))if(u=i[1]){if(a===9){s=t.getElementById(u);if(!s||!s.parentNode)return n;if(s.id===u)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(u))&&ft(t,s)&&s.id===u)return n.push(s),n}else{if(i[2])return S.apply(n,E.call(t.getElementsByTagName(e),0)),n;if((u=i[3])&&it&&t.getElementsByClassName)return S.apply(n,E.call(t.getElementsByClassName(u),0)),n}return ht(e,t,n,r,o)},ot=st.selectors={cacheLength:50,match:W,order:["ID","TAG"],attrHandle:{},createPseudo:K,find:{ID:d?function(e,t,n){if(typeof t.getElementById!==g&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==g&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==g&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:nt?function(e,t){if(typeof t.getElementsByTagName!==g)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(z,""),e[3]=(e[4]||e[5]||"").replace(z,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||st.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=e[4];return W.CHILD.test(e[0])?null:(n&&(t=B.exec(n))&&t.pop()&&(e[0]=e[0].slice(0,t[0].length-n.length-1),n=t[0].slice(0,-1)),e.splice(2,3,n||e[3]),e)}},filter:{ID:d?function(e){return e=e.replace(z,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace(z,""),function(t){var n=typeof t.getAttributeNode!==g&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace(z,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=X[e];return t||(t=X[e]=new RegExp("(^|"+T+")"+e+"("+T+"|$)"),V.push(e),V.length>ot.cacheLength&&delete X[V.shift()]),function(e){return t.test(e.className||typeof e.getAttribute!==g&&e.getAttribute("class")||"")}},ATTR:function(e,t,n){return t?function(r){var i=st.attr(r,e),s=i+"";if(i==null)return t==="!=";switch(t){case"=":return s===n;case"!=":return s!==n;case"^=":return n&&s.indexOf(n)===0;case"*=":return n&&s.indexOf(n)>-1;case"$=":return n&&s.substr(s.length-n.length)===n;case"~=":return(" "+s+" ").indexOf(n)>-1;case"|=":return s===n||s.substr(0,n.length+1)===n+"-"}}:function(t){return st.attr(t,e)!=null}},CHILD:function(e,t,n,r){if(e==="nth"){var i=w++;return function(e){var t,s,o=0,u=e;if(n===1&&r===0)return!0;t=e.parentNode;if(t&&(t[x]!==i||!e.sizset)){for(u=t.firstChild;u;u=u.nextSibling)if(u.nodeType===1){u.sizset=++o;if(u===e)break}t[x]=i}return s=e.sizset-r,n===0?s===0:s%n===0&&s/n>=0}}return function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t,n,r){var i=ot.pseudos[e]||ot.pseudos[e.toLowerCase()];return i||st.error("unsupported pseudo: "+e),i.sizzleFilter?i(t,n,r):i}},pseudos:{not:K(function(e,t,n){var r=ct(e.replace(D,"$1"),t,n);return function(e){return!r(e)}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!ot.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},contains:K(function(e){return function(t){return(t.textContent||t.innerText||lt(t)).indexOf(e)>-1}}),has:K(function(e){return function(t){return st(e,t).length>0}}),header:function(e){return R.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:Q("radio"),checkbox:Q("checkbox"),file:Q("file"),password:Q("password"),image:Q("image"),submit:G("submit"),reset:G("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return U.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&(!!e.type||!!e.href)},active:function(e){return e===e.ownerDocument.activeElement}},setFilters:{first:function(e,t,n){return n?e.slice(1):[e[0]]},last:function(e,t,n){var r=e.pop();return n?e:[r]},even:function(e,t,n){var r=[],i=n?1:0,s=e.length;for(;i<s;i+=2)r.push(e[i]);return r},odd:function(e,t,n){var r=[],i=n?0:1,s=e.length;for(;i<s;i+=2)r.push(e[i]);return r},lt:function(e,t,n){return n?e.slice(+t):e.slice(0,+t)},gt:function(e,t,n){return n?e.slice(0,+t+1):e.slice(+t+1)},eq:function(e,t,n){var r=e.splice(+t,1);return n?e:r}}};ot.setFilters.nth=ot.setFilters.eq,ot.filters=ot.pseudos,rt||(ot.attrHandle={href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}}),tt&&(ot.order.push("NAME"),ot.find.NAME=function(e,t){if(typeof t.getElementsByName!==g)return t.getElementsByName(e)}),it&&(ot.order.splice(1,0,"CLASS"),ot.find.CLASS=function(e,t,n){if(typeof t.getElementsByClassName!==g&&!n)return t.getElementsByClassName(e)});try{E.call(m.childNodes,0)[0].nodeType}catch(ut){E=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}var at=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},ft=st.contains=m.compareDocumentPosition?function(e,t){return!!(e.compareDocumentPosition(t)&16)}:m.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},lt=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=lt(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=lt(t);return n};st.attr=function(e,t){var n,r=at(e);return r||(t=t.toLowerCase()),ot.attrHandle[t]?ot.attrHandle[t](e):et||r?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},st.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},[0,0].sort(function(){return b=0}),m.compareDocumentPosition?h=function(e,t){return e===t?(y=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:(h=function(e,t){if(e===t)return y=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return p(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return p(i[f],s[f]);return f===n?p(e,s[f],-1):p(i[f],t,1)},p=function(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}),st.uniqueSort=function(e){var t,n=1;if(h){y=b,e.sort(h);if(y)for(;t=e[n];n++)t===e[n-1]&&e.splice(n--,1)}return e};var ct=st.compile=function(e,t,n){var r,i,o,u=$[e];if(u&&u.context===t)return u;i=s(e,t,n);for(o=0;r=i[o];o++)i[o]=a(r,t,n);return u=$[e]=f(i),u.context=t,u.runs=u.dirruns=0,J.push(e),J.length>ot.cacheLength&&delete $[J.shift()],u};st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){return st(t,null,null,[e]).length>0};var ht=function(e,t,n,r,s){e=e.replace(D,"$1");var o,u,a,f,h,p,d,v,m,g=e.match(H),y=e.match(j),b=t.nodeType;if(W.POS.test(e))return i(e,t,n,r,g);if(r)o=E.call(r,0);else if(g&&g.length===1){if(y.length>1&&b===9&&!s&&(g=W.ID.exec(y[0]))){t=ot.find.ID(g[1],t,s)[0];if(!t)return n;e=e.slice(y.shift().length)}v=(g=I.exec(y[0]))&&!g.index&&t.parentNode||t,m=y.pop(),p=m.split(":not")[0];for(a=0,f=ot.order.length;a<f;a++){d=ot.order[a];if(g=W[d].exec(p)){o=ot.find[d]((g[1]||"").replace(z,""),v,s);if(o==null)continue;p===m&&(e=e.slice(0,e.length-m.length)+p.replace(W[d],""),e||S.apply(n,E.call(o,0)));break}}}if(e){u=ct(e,t,s),c=u.dirruns++,o==null&&(o=ot.find.TAG("*",I.test(e)&&t.parentNode||t));for(a=0;h=o[a];a++)l=u.runs++,u(h,t)&&n.push(h)}return n};v.querySelectorAll&&function(){var e,t=ht,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[],s=[":active"],o=m.matchesSelector||m.mozMatchesSelector||m.webkitMatchesSelector||m.oMatchesSelector||m.msMatchesSelector;Z(function(e){e.innerHTML="<select><option selected></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+T+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),Z(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+T+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=i.length&&new RegExp(i.join("|")),ht=function(e,r,s,o,u){if(!o&&!u&&(!i||!i.test(e)))if(r.nodeType===9)try{return S.apply(s,E.call(r.querySelectorAll(e),0)),s}catch(a){}else if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){var f=r.getAttribute("id"),l=f||x,c=I.test(e)&&r.parentNode||r;f?l=l.replace(n,"\\$&"):r.setAttribute("id",l);try{return S.apply(s,E.call(c.querySelectorAll(e.replace(H,"[id='"+l+"'] $&")),0)),s}catch(a){}finally{f||r.removeAttribute("id")}}return t(e,r,s,o,u)},o&&(Z(function(t){e=o.call(t,"div");try{o.call(t,"[test!='']:sizzle"),s.push(ot.match.PSEUDO)}catch(n){}}),s=new RegExp(s.join("|")),st.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!at(t)&&!s.test(n)&&(!i||!i.test(n)))try{var u=o.call(t,n);if(u||e||t.document&&t.document.nodeType!==11)return u}catch(a){}return st(n,null,null,[t]).length>0})}(),st.attr=Y.attr,Y.find=st,Y.expr=st.selectors,Y.expr[":"]=Y.expr.pseudos,Y.unique=st.uniqueSort,Y.text=st.getText,Y.isXMLDoc=st.isXML,Y.contains=st.contains}(e);var Pt=/Until$/,Ht=/^(?:parents|prev(?:Until|All))/,Bt=/^.[^:#\[\.,]*$/,jt=Y.expr.match.needsContext,Ft={children:!0,contents:!0,next:!0,prev:!0};Y.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return Y(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(Y.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,Y.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=Y(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(Y.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(f(this,e,!1),"not",e)},filter:function(e){return this.pushStack(f(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?jt.test(e)?Y(e,this.context).index(this[0])>=0:Y.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=jt.test(e)||typeof e!="string"?Y(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:Y.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?Y.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?Y.inArray(this[0],Y(e)):Y.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?Y(e,t):Y.makeArray(e&&e.nodeType?[e]:e),r=Y.merge(this.get(),n);return this.pushStack(u(n[0])||u(r[0])?r:Y.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),Y.fn.andSelf=Y.fn.addBack,Y.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return Y.dir(e,"parentNode")},parentsUntil:function(e,t,n){return Y.dir(e,"parentNode",n)},next:function(e){return a(e,"nextSibling")},prev:function(e){return a(e,"previousSibling")},nextAll:function(e){return Y.dir(e,"nextSibling")},prevAll:function(e){return Y.dir(e,"previousSibling")},nextUntil:function(e,t,n){return Y.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return Y.dir(e,"previousSibling",n)},siblings:function(e){return Y.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return Y.sibling(e.firstChild)},contents:function(e){return Y.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:Y.merge([],e.childNodes)}},function(e,t){Y.fn[e]=function(n,r){var i=Y.map(this,t,n);return Pt.test(e)||(r=n),r&&typeof r=="string"&&(i=Y.filter(r,i)),i=this.length>1&&!Ft[e]?Y.unique(i):i,this.length>1&&Ht.test(e)&&(i=i.reverse()),this.pushStack(i,e,$.call(arguments).join(","))}}),Y.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?Y.find.matchesSelector(t[0],e)?[t[0]]:[]:Y.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!Y(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var It="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",qt=/ jQuery\d+="(?:null|\d+)"/g,Rt=/^\s+/,Ut=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,zt=/<([\w:]+)/,Wt=/<tbody/i,Xt=/<|&#?\w+;/,Vt=/<(?:script|style|link)/i,$t=/<(?:script|object|embed|option|style)/i,Jt=new RegExp("<(?:"+It+")[\\s/>]","i"),Kt=/^(?:checkbox|radio)$/,Qt=/checked\s*(?:[^=]|=\s*.checked.)/i,Gt=/\/(java|ecma)script/i,Yt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Zt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},en=l(R),tn=en.appendChild(R.createElement("div"));Zt.optgroup=Zt.option,Zt.tbody=Zt.tfoot=Zt.colgroup=Zt.caption=Zt.thead,Zt.th=Zt.td,Y.support.htmlSerialize||(Zt._default=[1,"X<div>","</div>"]),Y.fn.extend({text:function(e){return Y.access(this,function(e){return e===t?Y.text(this):this.empty().append((this[0]&&this[0].ownerDocument||R).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(Y.isFunction(e))return this.each(function(t){Y(this).wrapAll(e.call(this,t))});if(this[0]){var t=Y(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return Y.isFunction(e)?this.each(function(t){Y(this).wrapInner(e.call(this,t))}):this.each(function(){var t=Y(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=Y.isFunction(e);return this.each(function(n){Y(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){Y.nodeName(this,"body"
)||Y(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!u(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=Y.clean(arguments);return this.pushStack(Y.merge(e,this),"before",this.selector)}},after:function(){if(!u(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=Y.clean(arguments);return this.pushStack(Y.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||Y.filter(e,[n]).length)!t&&n.nodeType===1&&(Y.cleanData(n.getElementsByTagName("*")),Y.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&Y.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return Y.clone(this,e,t)})},html:function(e){return Y.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(qt,""):t;if(typeof e=="string"&&!Vt.test(e)&&(Y.support.htmlSerialize||!Jt.test(e))&&(Y.support.leadingWhitespace||!Rt.test(e))&&!Zt[(zt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(Ut,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(Y.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return u(this[0])?this.length?this.pushStack(Y(Y.isFunction(e)?e():e),"replaceWith",e):this:Y.isFunction(e)?this.each(function(t){var n=Y(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=Y(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;Y(this).remove(),t?Y(t).before(e):Y(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],h=this.length;if(!Y.support.checkClone&&h>1&&typeof f=="string"&&Qt.test(f))return this.each(function(){Y(this).domManip(e,n,r)});if(Y.isFunction(f))return this.each(function(i){var s=Y(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=Y.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&Y.nodeName(s,"tr");for(u=i.cacheable||h-1;a<h;a++)r.call(n&&Y.nodeName(this[a],"table")?c(this[a],"tbody"):this[a],a===u?o:Y.clone(o,!0,!0))}o=s=null,l.length&&Y.each(l,function(e,t){t.src?Y.ajax?Y.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):Y.error("no ajax"):Y.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Yt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),Y.buildFragment=function(e,n,r){var i,s,o,u=e[0];return n=n||R,n=(n[0]||n).ownerDocument||n[0]||n,typeof n.createDocumentFragment=="undefined"&&(n=R),e.length===1&&typeof u=="string"&&u.length<512&&n===R&&u.charAt(0)==="<"&&!$t.test(u)&&(Y.support.checkClone||!Qt.test(u))&&(Y.support.html5Clone||!Jt.test(u))&&(s=!0,i=Y.fragments[u],o=i!==t),i||(i=n.createDocumentFragment(),Y.clean(e,n,i,r),s&&(Y.fragments[u]=o&&i)),{fragment:i,cacheable:s}},Y.fragments={},Y.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){Y.fn[e]=function(n){var r,i=0,s=[],o=Y(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),Y(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),Y.extend({clone:function(e,t,n){var r,i,s,o;Y.support.html5Clone||Y.isXMLDoc(e)||!Jt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(tn.innerHTML=e.outerHTML,tn.removeChild(o=tn.firstChild));if((!Y.support.noCloneEvent||!Y.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!Y.isXMLDoc(e)){p(e,o),r=d(e),i=d(o);for(s=0;r[s];++s)i[s]&&p(r[s],i[s])}if(t){h(e,o);if(n){r=d(e),i=d(o);for(s=0;r[s];++s)h(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var i,s,o,u,a,f,c,h,p,d,m,g,y=0,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=R;for(s=t===R&&en;(o=e[y])!=null;y++){typeof o=="number"&&(o+="");if(!o)continue;if(typeof o=="string")if(!Xt.test(o))o=t.createTextNode(o);else{s=s||l(t),c=c||s.appendChild(t.createElement("div")),o=o.replace(Ut,"<$1></$2>"),u=(zt.exec(o)||["",""])[1].toLowerCase(),a=Zt[u]||Zt._default,f=a[0],c.innerHTML=a[1]+o+a[2];while(f--)c=c.lastChild;if(!Y.support.tbody){h=Wt.test(o),p=u==="table"&&!h?c.firstChild&&c.firstChild.childNodes:a[1]==="<table>"&&!h?c.childNodes:[];for(i=p.length-1;i>=0;--i)Y.nodeName(p[i],"tbody")&&!p[i].childNodes.length&&p[i].parentNode.removeChild(p[i])}!Y.support.leadingWhitespace&&Rt.test(o)&&c.insertBefore(t.createTextNode(Rt.exec(o)[0]),c.firstChild),o=c.childNodes,c=s.lastChild}o.nodeType?b.push(o):b=Y.merge(b,o)}c&&(s.removeChild(c),o=c=s=null);if(!Y.support.appendChecked)for(y=0;(o=b[y])!=null;y++)Y.nodeName(o,"input")?v(o):typeof o.getElementsByTagName!="undefined"&&Y.grep(o.getElementsByTagName("input"),v);if(n){m=function(e){if(!e.type||Gt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(y=0;(o=b[y])!=null;y++)if(!Y.nodeName(o,"script")||!m(o))n.appendChild(o),typeof o.getElementsByTagName!="undefined"&&(g=Y.grep(Y.merge([],o.getElementsByTagName("script")),m),b.splice.apply(b,[y+1,0].concat(g)),y+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=Y.expando,a=Y.cache,f=Y.support.deleteExpando,l=Y.event.special;for(;(i=e[o])!=null;o++)if(t||Y.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?Y.event.remove(i,s):Y.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,Y.deletedIds.push(r))}}}}),function(){var e,t;Y.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=Y.uaMatch(z.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.webkit&&(t.safari=!0),Y.browser=t,Y.sub=function(){function e(t,n){return new e.fn.init(t,n)}Y.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function n(n,r){return r&&r instanceof Y&&!(r instanceof e)&&(r=e(r)),Y.fn.init.call(this,n,r,t)},e.fn.init.prototype=e.fn;var t=e(R);return e}}();var nn,rn,sn,on=/alpha\([^)]*\)/i,un=/opacity=([^)]*)/,an=/^(top|right|bottom|left)$/,fn=/^margin/,ln=new RegExp("^("+Z+")(.*)$","i"),cn=new RegExp("^("+Z+")(?!px)[a-z%]+$","i"),hn=new RegExp("^([-+])=("+Z+")","i"),pn={},dn={position:"absolute",visibility:"hidden",display:"block"},vn={letterSpacing:0,fontWeight:400,lineHeight:1},mn=["Top","Right","Bottom","Left"],gn=["Webkit","O","Moz","ms"],yn=Y.fn.toggle;Y.fn.extend({css:function(e,n){return Y.access(this,function(e,n,r){return r!==t?Y.style(e,n,r):Y.css(e,n)},e,n,arguments.length>1)},show:function(){return y(this,!0)},hide:function(){return y(this)},toggle:function(e,t){var n=typeof e=="boolean";return Y.isFunction(e)&&Y.isFunction(t)?yn.apply(this,arguments):this.each(function(){(n?e:g(this))?Y(this).show():Y(this).hide()})}}),Y.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=nn(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":Y.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=Y.camelCase(n),f=e.style;n=Y.cssProps[a]||(Y.cssProps[a]=m(f,a)),u=Y.cssHooks[n]||Y.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=hn.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(Y.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!Y.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=Y.camelCase(n);return n=Y.cssProps[a]||(Y.cssProps[a]=m(e.style,a)),u=Y.cssHooks[n]||Y.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=nn(e,n)),s==="normal"&&n in vn&&(s=vn[n]),r||i!==t?(o=parseFloat(s),r||Y.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?nn=function(e,t){var n,r,i,s,o=getComputedStyle(e,null),u=e.style;return o&&(n=o[t],n===""&&!Y.contains(e.ownerDocument.documentElement,e)&&(n=Y.style(e,t)),cn.test(n)&&fn.test(t)&&(r=u.width,i=u.minWidth,s=u.maxWidth,u.minWidth=u.maxWidth=u.width=n,n=o.width,u.width=r,u.minWidth=i,u.maxWidth=s)),n}:R.documentElement.currentStyle&&(nn=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),cn.test(i)&&!an.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),Y.each(["height","width"],function(e,t){Y.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth!==0||nn(e,"display")!=="none"?E(e,t,r):Y.swap(e,dn,function(){return E(e,t,r)})},set:function(e,n,r){return b(e,n,r?w(e,t,r,Y.support.boxSizing&&Y.css(e,"boxSizing")==="border-box"):0)}}}),Y.support.opacity||(Y.cssHooks.opacity={get:function(e,t){return un.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=Y.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&Y.trim(s.replace(on,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=on.test(s)?s.replace(on,i):s+" "+i}}),Y(function(){Y.support.reliableMarginRight||(Y.cssHooks.marginRight={get:function(e,t){return Y.swap(e,{display:"inline-block"},function(){if(t)return nn(e,"marginRight")})}}),!Y.support.pixelPosition&&Y.fn.position&&Y.each(["top","left"],function(e,t){Y.cssHooks[t]={get:function(e,n){if(n){var r=nn(e,t);return cn.test(r)?Y(e).position()[t]+"px":r}}}})}),Y.expr&&Y.expr.filters&&(Y.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!Y.support.reliableHiddenOffsets&&(e.style&&e.style.display||nn(e,"display"))==="none"},Y.expr.filters.visible=function(e){return!Y.expr.filters.hidden(e)}),Y.each({margin:"",padding:"",border:"Width"},function(e,t){Y.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+mn[r]+t]=i[r]||i[r-2]||i[0];return s}},fn.test(e)||(Y.cssHooks[e+t].set=b)});var bn=/%20/g,wn=/\[\]$/,En=/\r?\n/g,Sn=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,xn=/^(?:select|textarea)/i;Y.fn.extend({serialize:function(){return Y.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?Y.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||xn.test(this.nodeName)||Sn.test(this.type))}).map(function(e,t){var n=Y(this).val();return n==null?null:Y.isArray(n)?Y.map(n,function(e,n){return{name:t.name,value:e.replace(En,"\r\n")}}):{name:t.name,value:n.replace(En,"\r\n")}}).get()}}),Y.param=function(e,n){var r,i=[],s=function(e,t){t=Y.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=Y.ajaxSettings&&Y.ajaxSettings.traditional);if(Y.isArray(e)||e.jquery&&!Y.isPlainObject(e))Y.each(e,function(){s(this.name,this.value)});else for(r in e)x(r,e[r],n,s);return i.join("&").replace(bn,"+")};var Tn,Nn,Cn=/#.*$/,kn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,Ln=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,An=/^(?:GET|HEAD)$/,On=/^\/\//,Mn=/\?/,_n=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,Dn=/([?&])_=[^&]*/,Pn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Hn=Y.fn.load,Bn={},jn={},Fn=["*/"]+["*"];try{Tn=U.href}catch(In){Tn=R.createElement("a"),Tn.href="",Tn=Tn.href}Nn=Pn.exec(Tn.toLowerCase())||[],Y.fn.load=function(e,n,r){if(typeof e!="string"&&Hn)return Hn.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),Y.isFunction(n)?(r=n,n=t):typeof n=="object"&&(s="POST"),Y.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?Y("<div>").append(e.replace(_n,"")).find(i):e)}),this},Y.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){Y.fn[t]=function(e){return this.on(t,e)}}),Y.each(["get","post"],function(e,n){Y[n]=function(e,r,i,s){return Y.isFunction(r)&&(s=s||i,i=r,r=t),Y.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),Y.extend({getScript:function(e,n){return Y.get(e,t,n,"script")},getJSON:function(e,t,n){return Y.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?C(e,Y.ajaxSettings):(t=e,e=Y.ajaxSettings),C(e,t),e},ajaxSettings:{url:Tn,isLocal:Ln.test(Nn[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Fn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":Y.parseJSON,"text xml":Y.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:T(Bn),ajaxTransport:T(jn),ajax:function(e,n){function r(e,n,r,o){var f,c,y,b,E,x=n;if(w===2)return;w=2,a&&clearTimeout(a),u=t,s=o||"",S.readyState=e>0?4:0,r&&(b=k(h,S,r));if(e>=200&&e<300||e===304)h.ifModified&&(E=S.getResponseHeader("Last-Modified"),E&&(Y.lastModified[i]=E),E=S.getResponseHeader("Etag"),E&&(Y.etag[i]=E)),e===304?(x="notmodified",f=!0):(f=L(h,b),x=f.state,c=f.data,y=f.error,f=!y);else{y=x;if(!x||e)x="error",e<0&&(e=0)}S.status=e,S.statusText=""+(n||x),f?v.resolveWith(p,[c,x,S]):v.rejectWith(p,[S,x,y]),S.statusCode(g),g=t,l&&d.trigger("ajax"+(f?"Success":"Error"),[S,h,f?c:y]),m.fireWith(p,[S,x]),l&&(d.trigger("ajaxComplete",[S,h]),--Y.active||Y.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var i,s,o,u,a,f,l,c,h=Y.ajaxSetup({},n),p=h.context||h,d=p!==h&&(p.nodeType||p instanceof Y)?Y(p):Y.event,v=Y.Deferred(),m=Y.Callbacks("once memory"),g=h.statusCode||{},y={},b={},w=0,E="canceled",S={readyState:0,setRequestHeader:function(e,t){if(!w){var n=e.toLowerCase();e=b[n]=b[n]||e,y[e]=t}return this},getAllResponseHeaders:function(){return w===2?s:null},getResponseHeader:function(e){var n;if(w===2){if(!o){o={};while(n=kn.exec(s))o[n[1].toLowerCase()]=n[2]}n=o[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return w||(h.mimeType=e),this},abort:function(e){return e=e||E,u&&u.abort(e),r(0,e),this}};v.promise(S),S.success=S.done,S.error=S.fail,S.complete=m.add,S.statusCode=function(e){if(e){var t;if(w<2)for(t in e)g[t]=[g[t],e[t]];else t=e[S.status],S.always(t)}return this},h.url=((e||h.url)+"").replace(Cn,"").replace(On,Nn[1]+"//"),h.dataTypes=Y.trim(h.dataType||"*").toLowerCase().split(tt),h.crossDomain==null&&(f=Pn.exec(h.url.toLowerCase()),h.crossDomain=!(!f||f[1]==Nn[1]&&f[2]==Nn[2]&&(f[3]||(f[1]==="http:"?80:443))==(Nn[3]||(Nn[1]==="http:"?80:443)))),h.data&&h.processData&&typeof h.data!="string"&&(h.data=Y.param(h.data,h.traditional)),N(Bn,h,n,S);if(w===2)return S;l=h.global,h.type=h.type.toUpperCase(),h.hasContent=!An.test(h.type),l&&Y.active++===0&&Y.event.trigger("ajaxStart");if(!h.hasContent){h.data&&(h.url+=(Mn.test(h.url)?"&":"?")+h.data,delete h.data),i=h.url;if(h.cache===!1){var x=Y.now(),T=h.url.replace(Dn,"$1_="+x);h.url=T+(T===h.url?(Mn.test(h.url)?"&":"?")+"_="+x:"")}}(h.data&&h.hasContent&&h.contentType!==!1||n.contentType)&&S.setRequestHeader("Content-Type",h.contentType),h.ifModified&&(i=i||h.url,Y.lastModified[i]&&S.setRequestHeader("If-Modified-Since",Y.lastModified[i]),Y.etag[i]&&S.setRequestHeader("If-None-Match",Y.etag[i])),S.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+(h.dataTypes[0]!=="*"?", "+Fn+"; q=0.01":""):h.accepts["*"]);for(c in h.headers)S.setRequestHeader(c,h.headers[c]);if(!h.beforeSend||h.beforeSend.call(p,S,h)!==!1&&w!==2){E="abort";for(c in{success:1,error:1,complete:1})S[c](h[c]);u=N(jn,h,n,S);if(!u)r(-1,"No Transport");else{S.readyState=1,l&&d.trigger("ajaxSend",[S,h]),h.async&&h.timeout>0&&(a=setTimeout(function(){S.abort("timeout")},h.timeout));try{w=1,u.send(y,r)}catch(C){if(!(w<2))throw C;r(-1,C)}}return S}return S.abort()},active:0,lastModified:{},etag:{}});var qn=[],Rn=/\?/,Un=/(=)\?(?=&|$)|\?\?/,zn=Y.now();Y.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=qn.pop()||Y.expando+"_"+zn++;return this[e]=!0,e}}),Y.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Un.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Un.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=Y.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Un,"$1"+s):h?n.data=a.replace(Un,"$1"+s):l&&(n.url+=(Rn.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||Y.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,qn.push(s)),u&&Y.isFunction(o)&&o(u[0]),u=o=t}),"script"}),Y.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return Y.globalEval(e),e}}}),Y.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),Y.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=R.head||R.getElementsByTagName("head")[0]||R.documentElement;return{send:function(i,s){n=R.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||s(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Wn,Xn=e.ActiveXObject?function(){for(var e in Wn)Wn[e](0,1)}:!1,Vn=0;Y.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&A()||O()}:A,function(e){Y.extend(Y.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(Y.ajaxSettings.xhr()),Y.support.ajax&&Y.ajaxTransport(function(n){if(!n.crossDomain||Y.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=Y.noop,Xn&&delete Wn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(e){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++Vn,Xn&&(Wn||(Wn={},Y(e).unload(Xn)),Wn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var $n,Jn,Kn=/^(?:toggle|show|hide)$/,Qn=new RegExp("^(?:([-+])=|)("+Z+")([a-z%]*)$","i"),Gn=/queueHooks$/,Yn=[H],Zn={"*":[function(e,t){var n,r,i,s=this.createTween(e,t),o=Qn.exec(t),u=s.cur(),a=+u||0,f=1;if(o){n=+o[2],r=o[3]||(Y.cssNumber[e]?"":"px");if(r!=="px"&&a){a=Y.css(s.elem,e,!0)||n||1;do i=f=f||".5",a/=f,Y.style(s.elem,e,a+r),f=s.cur()/u;while(f!==1&&f!==i)}s.unit=r,s.start=a,s.end=o[1]?a+(o[1]+1)*n:n}return s}]};Y.Animation=Y.extend(D,{tweener:function(e,t){Y.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Zn[n]=Zn[n]||[],Zn[n].unshift(t)},prefilter:function(e,t){t?Yn.unshift(e):Yn.push(e)}}),Y.Tween=B,B.prototype={constructor:B,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(Y.cssNumber[n]?"":"px")},cur:function(){var e=B.propHooks[this.prop];return e&&e.get?e.get(this):B.propHooks._default.get(this)},run:function(e){var t,n=B.propHooks[this.prop];return this.pos=t=Y.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration),this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):B.propHooks._default.set(this),this}},B.prototype.init.prototype=B.prototype,B.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=Y.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){Y.fx.step[e.prop]?Y.fx.step[e.prop](e):e.elem.style&&(e.elem.style[Y.cssProps[e.prop]]!=null||Y.cssHooks[e.prop])?Y.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},B.propHooks.scrollTop=B.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},Y.each(["toggle","show","hide"],function(e,t){var n=Y.fn[t];Y.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&Y.isFunction(r)&&Y.isFunction(i)?n.apply(this,arguments):this.animate(j(t,!0),r,i,s)}}),Y.fn.extend({fadeTo:function(e,t,n,r){return this.filter(g).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=Y.isEmptyObject(e),s=Y.speed(t,n,r),o=function(){var t=D(this,Y.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=Y.timers,o=Y._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Gn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&Y.dequeue(this,e)})}}),Y.each({slideDown:j("show"),slideUp:j("hide"),slideToggle:j("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){Y.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),Y.speed=function(e,t,n){var r=e&&typeof e=="object"?Y.extend({},e):{complete:n||!n&&t||Y.isFunction(e)&&e,duration:e,easing:n&&t||t&&!Y.isFunction(t)&&t};r.duration=Y.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in Y.fx.speeds?Y.fx.speeds[r.duration]:Y.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){Y.isFunction(r.old)&&r.old.call(this),r.queue&&Y.dequeue(this,r.queue)},r},Y.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},Y.timers=[],Y.fx=B.prototype.init,Y.fx.tick=function(){var e,t=Y.timers,n=0;for(;n<t.length;n++)e=t[n],!e()&&t[n]===e&&t.splice(n--,1);t.length||Y.fx.stop()},Y.fx.timer=function(e){e()&&Y.timers.push(e)&&!Jn&&(Jn=setInterval(Y.fx.tick,Y.fx.interval))},Y.fx.interval=13,Y.fx.stop=function(){clearInterval(Jn),Jn=null},Y.fx.speeds={slow:600,fast:200,_default:400},Y.fx.step={},Y.expr&&Y.expr.filters&&(Y.expr.filters.animated=function(e){return Y.grep(Y.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;Y.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){Y.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f,l,c,h=this[0],p=h&&h.ownerDocument;if(!p)return;return(i=p.body)===h?Y.offset.bodyOffset(h):(r=p.documentElement,Y.contains(r,h)?(n=h.getBoundingClientRect(),s=F(p),o=r.clientTop||i.clientTop||0,u=r.clientLeft||i.clientLeft||0,a=s.pageYOffset||r.scrollTop,f=s.pageXOffset||r.scrollLeft,l=n.top+a-o,c=n.left+f-u,{top:l,left:c}):{top:0,left:0})},Y.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return Y.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(Y.css(e,"marginTop"))||0,n+=parseFloat(Y.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=Y.css(e,"position");r==="static"&&(e.style.position="relative");var i=Y(e),s=i.offset(),o=Y.css(e,"top"),u=Y.css(e,"left"),a=(r==="absolute"||r==="fixed")&&Y.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),Y.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},Y.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(Y.css(e,"marginTop"))||0,n.left-=parseFloat(Y.css(e,"marginLeft"))||0,r.top+=parseFloat(Y.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(Y.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||R.body;while(e&&!er.test(e.nodeName)&&Y.css(e,"position")==="static")e=e.offsetParent;return e||R.body})}}),Y.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);Y.fn[e]=function(i){return Y.access(this,function(e,i,s){var o=F(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?Y(o).scrollLeft():s,r?s:Y(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),Y.each({Height:"height",Width:"width"},function(e,n){Y.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){Y.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return Y.access(this,function(n,r,i){var s;return Y.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?Y.css(n,r,i,u):Y.style(n,r,i,u)},n,o?i:t,o)}})}),e.jQuery=e.$=Y,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return Y})})(window); |
app/main.js | ellheat/exercise-6-redux | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import React from 'react';
import ReactDOM from 'react-dom';
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// Import all the third party stuff
import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
import FontFaceObserver from 'fontfaceobserver';
import { useScroll } from 'react-router-scroll';
import 'normalize.css/normalize.css';
import './main.scss';
// Import selector for `syncHistoryWithStore`
import { selectLocationState } from './modules/router/router.selectors';
import configureStore from './modules/store';
// Import routes
import routes from './routes';
// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});
// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
document.body.classList.add('fontLoaded');
}, () => {
document.body.classList.remove('fontLoaded');
});
// Needed for onTouchTap
// Check this repo:
// https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState(),
});
if (process.env.NODE_ENV) {
const DevToolsComponent = require('./utils/devtools.component').default;
const devToolsRoot = window.document.createElement('div');
window.document.body.appendChild(devToolsRoot);
ReactDOM.render(
<Provider store={store}>
<DevToolsComponent />
</Provider>,
devToolsRoot
);
}
const render = () => {
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Router
history={history}
routes={routes}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</Provider>
</AppContainer>,
document.getElementById('app')
);
};
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(require('intl'));
}))
.then(() => Promise.all([
require('intl/locale-data/jsonp/en.js'),
require('intl/locale-data/jsonp/de.js'),
]))
.then(() => render())
.catch((err) => {
throw err;
});
} else {
render();
}
/* istanbul ignore next */
if (module.hot) {
module.hot.accept('./routes', () => {
render();
});
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require, import/no-extraneous-dependencies
}
|
ajax/libs/6to5/3.6.1/browser-polyfill.js | pvnr0082t/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){(function(global){"use strict";if(global._6to5Polyfill){throw new Error("only one instance of 6to5/polyfill is allowed")}global._6to5Polyfill=true;require("core-js/shim");require("regenerator-6to5/runtime")}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"core-js/shim":2,"regenerator-6to5/runtime":3}],2:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,parseInt=global.parseInt,isFinite=global.isFinite,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".",CONSOLE_METHODS="assert,clear,count,debug,dir,dirxml,error,exception,"+"group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,"+"markTimeline,profile,profileEnd,table,time,timeEnd,timeline,"+"timelineEnd,timeStamp,trace,warn";function isObject(it){return it!==null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return toString.call(it).slice(8,-1)}function classof(it){var O,T;return it==undefined?it===undefined?"Undefined":"Null":typeof(T=(O=Object(it))[SYMBOL_TAG])=="string"?T:cof(O)}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}function construct(target,argumentsList){var proto=assertFunction(arguments.length<3?target:arguments[2])[PROTOTYPE],instance=create(isObject(proto)?proto:ObjectProto),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,isFrozen=Object.isFrozen,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict;function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=toObject(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,pow=Math.pow,abs=Math.abs,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},"a",{get:function(){return 2}}).a==2}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_SPECIES=getWellKnownSymbol("species");function setSpecies(C){if(framework||!isNative(C))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description),sym=set(create(Symbol[PROTOTYPE]),TAG,tag);AllSymbols[tag]=sym;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return sym};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(AllSymbols[key]);return result}})}(safeSymbol("tag"),{},{},true);!function(tmp){var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"})}setToStringTag(Math,MATH,true);setToStringTag(global.JSON,"JSON",true)}({});!function(){function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames")}();!function(NAME){NAME in FunctionProto||defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}})}("name");!function(isInteger){$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt})}(Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it});!function(){var E=Math.E,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,sign=Math.sign||function(x){return(x=+x)==0||x!=x?x:x<0?-1:1};function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc})}();!function(RangeError,fromCharCode){function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fromCharCode(code):fromCharCode(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}})}(global.RangeError,String.fromCharCode);!function(){$define(STATIC,ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),mapfn=arguments[1],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,arguments[2],2):undefined,index=0,length,result,iter,step;if(isIterable(O))for(iter=getIterator(O),result=new(generic(this,Array));!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(result=new(generic(this,Array))(length=toLength(O.length));length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});if(framework){forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}setSpecies(Array)}();!function(at){defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)})}(createPointAt(true));!function(RegExpProto,_RegExp){function assertRegExpWrapper(fn){return function(){assert(cof(this)===REGEXP);return fn(this)}}if(DESC&&!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){RegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};forEach.call(getNames(_RegExp),function(key){key in RegExp||defineProperty(RegExp,key,{configurable:true,get:function(){return _RegExp[key]},set:function(it){_RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=RegExp;RegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,RegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:assertRegExpWrapper(createReplacer(/^.*\/(\w*)$/,"$1",true))});forEach.call(array("sticky,unicode"),function(key){key in/./||defineProperty(RegExpProto,key,DESC?{configurable:true,get:assertRegExpWrapper(function(){return false})}:descriptor(5,false))});setSpecies(RegExp)}(RegExp[PROTOTYPE],RegExp);isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(run,0,id)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&¬ify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&DEF in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),O1=safeSymbol("O1"),WEAK=safeSymbol("weak"),LEAK=safeSymbol("leak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0,tmp={};function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];if(framework)proto[key]=function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result}}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,FOR_EACH)&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,O1,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto;if(framework)proto[CONSTRUCTOR]=C}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,UID)){if(!create)return"E";hidden(it,UID,++uid)}return"O"+it[UID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}function def(that,key,value){var entry=getEntry(that,key),prev,index;if(entry)entry.v=value;else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that}var collectionMethods={clear:function(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return!!getEntry(this,key)}};Map=getCollection(Map,MAP,{get:function(key){var entry=getEntry(this,key);return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function defWeak(that,key,value){if(isFrozen(assertObject(key)))leakStore(that).set(key,value);else{has(key,WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value}return that}function leakStore(that){return that[LEAK]||hidden(that,LEAK,new Map)[LEAK]}var weakMethods={"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return has(key,WEAK)&&has(key[WEAK],this[UID])&&delete key[WEAK][this[UID]]},has:function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);
return has(key,WEAK)&&has(key[WEAK],this[UID])}};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[UID]]}},set:function(key,value){return defWeak(this,key,value)}},weakMethods,true,true);if(framework&&(new WeakMap).set(Object.freeze(tmp),7).get(tmp)!=7){forEach.call(array("delete,has,get,set"),function(key){var method=WeakMap[PROTOTYPE][key];WeakMap[PROTOTYPE][key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result}return method.call(this,a,b)}})}WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return defWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return has(desc,"value")?desc.value:desc.get===undefined?undefined:desc.get.call(receiver);return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],ownDesc=getOwnDescriptor(assertObject(target),propertyKey),existingDescriptor,proto;if(!ownDesc){if(isObject(proto=getPrototypeOf(target))){return reflectSet(proto,propertyKey,V,receiver)}ownDesc=descriptor(0)}if(has(ownDesc,"value")){if(ownDesc.writable===false||!isObject(receiver))return false;existingDescriptor=getOwnDescriptor(receiver,propertyKey)||descriptor(0);existingDescriptor.value=V;return defineProperty(receiver,propertyKey,existingDescriptor),true}return ownDesc.set===undefined?false:(ownDesc.set.call(receiver,V),true)}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({});!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList)}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),true)},{}],3:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryLocsList){return new Generator(innerFn,outerFn,self||null,tryLocsList||[])}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryLocsList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryLocsList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryLocsList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryLocsList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(locs){var entry={tryLoc:locs[0]};if(1 in locs){entry.catchLoc=locs[1]}if(2 in locs){entry.finallyLoc=locs[2];entry.afterLoc=locs[3]}this.tryEntries.push(entry)}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal";delete record.arg;entry.completion=record}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}];tryLocsList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record,afterLoc){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}else if(record.type==="normal"&&afterLoc){this.next=afterLoc}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion,entry.afterLoc)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[1]); |
ajax/libs/forerunnerdb/1.3.674/fdb-core.js | seogi1004/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":5,"../lib/Shim.IE8":29}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":25,"./Shared":28}],3:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
'*': function (data) {
return this.$main.call(this, data, {});
},
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback(); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted});
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
case '2d':
index = new Index2d(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],5:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],6:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],8:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":25,"./Shared":28}],11:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":28}],12:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":23,"./Shared":28}],13:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],14:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, data, options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],15:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":24,"./Serialiser":27}],16:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],17:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":24}],18:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":24}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":25,"./Shared":28}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],25:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":28}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":28}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.674',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}]},{},[1]);
|
packages/mineral-ui-icons/src/IconRssFeed.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconRssFeed(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<circle cx="6.18" cy="17.82" r="2.18"/><path d="M4 4.44v2.83c7.03 0 12.73 5.7 12.73 12.73h2.83c0-8.59-6.97-15.56-15.56-15.56zm0 5.66v2.83c3.9 0 7.07 3.17 7.07 7.07h2.83c0-5.47-4.43-9.9-9.9-9.9z"/>
</g>
</Icon>
);
}
IconRssFeed.displayName = 'IconRssFeed';
IconRssFeed.category = 'communication';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.