target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
---|---|---|
html.js | frontendyteam/www.frontendy.com | import React from 'react'
import DocumentTitle from 'react-document-title'
import { prefixLink } from 'gatsby-helpers'
import { TypographyStyle, GoogleFont } from 'react-typography'
import typography from './utils/typography'
const BUILD_TIME = new Date().getTime()
module.exports = React.createClass({
propTypes () {
return {
title: React.PropTypes.string,
}
},
render () {
const title = DocumentTitle.rewind()
let css
if (process.env.NODE_ENV === 'production') {
css = <style dangerouslySetInnerHTML={{ __html: require('!raw!./public/styles.css') }} />
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>{title}</title>
<TypographyStyle typography={typography} />
<GoogleFont typography={typography} />
{css}
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />
<script dangerouslySetInnerHTML={{ __html: require('!raw!./integrations/intercom.js') }} />
<script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} />
</body>
</html>
)
},
})
|
ajax/libs/react-inlinesvg/0.5.1/react-inlinesvg.min.js | holtkamp/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.ReactInlineSVG=e()}}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};t[a][0].call(l.exports,function(e){var n=t[a][1][e];return o(n?n:e)},l,l.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t,n){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};t.exports=o},{}],2:[function(e,t,n){"use strict";function r(e){return function(){return e}}function o(){}o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},t.exports=o},{}],3:[function(e,t,n){(function(e){"use strict";var n={};"production"!==e.env.NODE_ENV&&Object.freeze(n),t.exports=n}).call(this,e("_process"))},{_process:23}],4:[function(e,t,n){(function(e){"use strict";function n(t,n,r,o,i,a,s,u){if("production"!==e.env.NODE_ENV&&void 0===n)throw new Error("invariant requires an error message argument");if(!t){var c;if(void 0===n)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[r,o,i,a,s,u],p=0;c=new Error(n.replace(/%s/g,function(){return l[p++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}}t.exports=n}).call(this,e("_process"))},{_process:23}],5:[function(e,t,n){(function(n){"use strict";var r=e("./invariant"),o=function(e){var t,o={};e instanceof Object&&!Array.isArray(e)?void 0:"production"!==n.env.NODE_ENV?r(!1,"keyMirror(...): Argument must be an object."):r(!1);for(t in e)e.hasOwnProperty(t)&&(o[t]=t);return o};t.exports=o}).call(this,e("_process"))},{"./invariant":4,_process:23}],6:[function(e,t,n){"use strict";var r=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=r},{}],7:[function(e,t,n){"use strict";function r(e,t,n){if(!e)return null;var r={};for(var i in e)o.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}var o=Object.prototype.hasOwnProperty;t.exports=r},{}],8:[function(e,t,n){"use strict";var r,o=e("./ExecutionEnvironment");o.canUseDOM&&(r=window.performance||window.msPerformance||window.webkitPerformance),t.exports=r||{}},{"./ExecutionEnvironment":1}],9:[function(e,t,n){"use strict";var r,o=e("./performance");r=o.now?function(){return o.now()}:function(){return Date.now()},t.exports=r},{"./performance":8}],10:[function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function o(e,t){if(r(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(var a=0;a<n.length;a++)if(!i.call(t,n[a])||!r(e[n[a]],t[n[a]]))return!1;return!0}var i=Object.prototype.hasOwnProperty;t.exports=o},{}],11:[function(e,t,n){(function(n){"use strict";var r=e("./emptyFunction"),o=r;"production"!==n.env.NODE_ENV&&(o=function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(0!==t.indexOf("Failed Composite propType: ")&&!e){var i=0,a="Warning: "+t.replace(/%s/g,function(){return r[i++]});"undefined"!=typeof console&&console.error(a);try{throw new Error(a)}catch(e){}}}),t.exports=o}).call(this,e("_process"))},{"./emptyFunction":2,_process:23}],12:[function(e,t,n){"use strict";function r(e,t){var n=new Error(e);n.name="RequestError",this.name=n.name,this.message=n.message,n.stack&&(this.stack=n.stack),this.toString=function(){return this.message};for(var r in t)t.hasOwnProperty(r)&&(this[r]=t[r])}var o=e("./response"),i=e("./utils/extractResponseProps"),a=e("xtend");r.prototype=a(Error.prototype),r.prototype.constructor=r,r.create=function(e,t,n){var a=new r(e,n);return o.call(a,i(t)),a},t.exports=r},{"./response":15,"./utils/extractResponseProps":17,xtend:52}],13:[function(e,t,n){"use strict";function r(e,t){function n(n,r){var a,c,h,v,y,m;for(n=new p(f(e,n)),i=0;i<t.length;i++)c=t[i],c.processRequest&&c.processRequest(n);for(i=0;i<t.length;i++)if(c=t[i],c.createXHR){a=c.createXHR(n);break}a=a||new s,n.xhr=a,h=d(u(function(e){clearTimeout(y),a.onload=a.onerror=a.onabort=a.onreadystatechange=a.ontimeout=a.onprogress=null;var s=o(n,e),u=s||l.fromRequest(n);for(i=0;i<t.length;i++)c=t[i],c.processResponse&&c.processResponse(u);s&&n.onerror&&n.onerror(s),!s&&n.onload&&n.onload(u),r&&r(s,s?void 0:u)})),m="onload"in a&&"onerror"in a,a.onload=function(){h()},a.onerror=h,a.onabort=function(){h()},a.onreadystatechange=function(){if(4===a.readyState){if(n.aborted)return h();if(!m){var e;try{e=a.status}catch(e){}var t=0===e?new Error("Internal XHR Error"):null;return h(t)}}},a.ontimeout=function(){},a.onprogress=function(){},a.open(n.method,n.url),n.timeout&&(y=setTimeout(function(){n.timedOut=!0,h();try{a.abort()}catch(e){}},n.timeout));for(v in n.headers)n.headers.hasOwnProperty(v)&&a.setRequestHeader(v,n.headers[v]);return a.send(n.body),n}e=e||{},t=t||[];var a,h=["get","post","put","head","patch","delete"],v=function(e){return function(t,r){return t=new p(t),t.method=e,n(t,r)}};for(i=0;i<h.length;i++)a=h[i],n[a]=v(a);return n.plugins=function(){return t},n.defaults=function(n){return n?r(f(e,n),t):e},n.use=function(){var n=Array.prototype.slice.call(arguments,0);return r(e,t.concat(n))},n.bare=function(){return r()},n.Request=p,n.Response=l,n.RequestError=c,n}function o(e,t){if(e.aborted)return h("Request aborted",e,{name:"Abort"});if(e.timedOut)return h("Request timeout",e,{name:"Timeout"});var n,r=e.xhr,o=Math.floor(r.status/100);switch(o){case 0:case 2:if(!t)return;return h(t.message,e);case 4:if(404===r.status&&!e.errorOn404)return;n="Client";break;case 5:n="Server";break;default:n="HTTP"}var i=n+" Error: The server returned a status of "+r.status+' for the request "'+e.method.toUpperCase()+" "+e.url+'"';return h(i,e)}var i,a=e("../plugins/cleanurl"),s=e("./xhr"),u=e("./utils/delay"),c=e("./error"),l=e("./response"),p=e("./request"),f=e("xtend"),d=e("./utils/once"),h=c.create;t.exports=r({},[a])},{"../plugins/cleanurl":20,"./error":12,"./request":14,"./response":15,"./utils/delay":16,"./utils/once":18,"./xhr":19,xtend:52}],14:[function(e,t,n){"use strict";function r(e){var t="string"==typeof e?{url:e}:e||{};this.method=t.method?t.method.toUpperCase():"GET",this.url=t.url,this.headers=t.headers||{},this.body=t.body,this.timeout=t.timeout||0,this.errorOn404=null==t.errorOn404||t.errorOn404,this.onload=t.onload,this.onerror=t.onerror}r.prototype.abort=function(){if(!this.aborted)return this.aborted=!0,this.xhr.abort(),this},r.prototype.header=function(e,t){var n;for(n in this.headers)if(this.headers.hasOwnProperty(n)&&e.toLowerCase()===n.toLowerCase()){if(1===arguments.length)return this.headers[n];delete this.headers[n];break}if(null!=t)return this.headers[e]=t,t},t.exports=r},{}],15:[function(e,t,n){"use strict";function r(e){this.request=e.request,this.xhr=e.xhr,this.headers=e.headers||{},this.status=e.status||0,this.text=e.text,this.body=e.body,this.contentType=e.contentType,this.isHttpError=e.status>=400}var o=e("./request"),i=e("./utils/extractResponseProps");r.prototype.header=o.prototype.header,r.fromRequest=function(e){return new r(i(e))},t.exports=r},{"./request":14,"./utils/extractResponseProps":17}],16:[function(e,t,n){"use strict";t.exports=function(e){return function(){var t=Array.prototype.slice.call(arguments,0),n=function(){return e.apply(null,t)};setTimeout(n,0)}}},{}],17:[function(e,t,n){"use strict";var r=e("xtend");t.exports=function(e){var t=e.xhr,n={request:e,xhr:t};try{var o,i,a,s={};if(t.getAllResponseHeaders)for(o=t.getAllResponseHeaders().split("\n"),i=0;i<o.length;i++)(a=o[i].match(/\s*([^\s]+):\s+([^\s]+)/))&&(s[a[1]]=a[2]);n=r(n,{status:t.status,contentType:t.contentType||t.getResponseHeader&&t.getResponseHeader("Content-Type"),headers:s,text:t.responseText,body:t.response||t.responseText})}catch(e){}return n}},{xtend:52}],18:[function(e,t,n){"use strict";t.exports=function(e){var t,n=!1;return function(){return n||(n=!0,t=e.apply(this,arguments)),t}}},{}],19:[function(e,t,n){t.exports=window.XMLHttpRequest},{}],20:[function(e,t,n){"use strict";t.exports={processRequest:function(e){e.url=e.url.replace(/[^%]+/g,function(e){return encodeURI(e)})}}},{}],21:[function(e,t,n){"use strict";var r=e("urllite/lib/core"),o=e("../lib/utils/once"),i=!1,a=o(function(){return"undefined"!=typeof window&&null!==window&&window.XMLHttpRequest&&"withCredentials"in new window.XMLHttpRequest});t.exports={createXHR:function(e){var t,n,o;if("undefined"!=typeof window&&null!==window&&(t=r(e.url),n=r(window.location.href),t.host&&(t.protocol!==n.protocol||t.host!==n.host||t.port!==n.port))){if(!i&&e.headers)for(o in e.headers)if(e.headers.hasOwnProperty(o)){i=!0,window&&window.console&&window.console.warn&&window.console.warn("Request headers are ignored in old IE when using the oldiexdomain plugin.");break}if(window.XDomainRequest&&!a()){var s=new window.XDomainRequest;return s.setRequestHeader=function(){},s}}}}},{"../lib/utils/once":18,"urllite/lib/core":50}],22:[function(e,t,n){function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}var o=e("wrappy");t.exports=o(r),r.proto=r(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return r(this)},configurable:!0})})},{wrappy:51}],23:[function(e,t,n){function r(){l&&s&&(l=!1,s.length?c=s.concat(c):p=-1,c.length&&o())}function o(){if(!l){var e=setTimeout(r);l=!0;for(var t=c.length;t;){for(s=c,c=[];++p<t;)s&&s[p].run();p=-1,t=c.length}s=null,l=!1,clearTimeout(e)}}function i(e,t){this.fun=e,this.array=t}function a(){}var s,u=t.exports={},c=[],l=!1,p=-1;u.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];c.push(new i(e,t)),1!==c.length||l||setTimeout(o,0)},i.prototype.run=function(){this.fun.apply(null,this.array)},u.title="browser",u.browser=!0,u.env={},u.argv=[],u.version="",u.versions={},u.on=a,u.addListener=a,u.once=a,u.off=a,u.removeListener=a,u.removeAllListeners=a,u.emit=a,u.binding=function(e){throw new Error("process.binding is not supported")},u.cwd=function(){return"/"},u.chdir=function(e){throw new Error("process.chdir is not supported")},u.umask=function(){return 0}},{}],24:[function(e,t,n){"use strict";function r(e){var t=/[=:]/g,n={"=":"=0",":":"=2"},r=(""+e).replace(t,function(e){return n[e]});return"$"+r}function o(e){var t=/(=0|=2)/g,n={"=0":"=","=2":":"},r="."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1);return(""+r).replace(t,function(e){return n[e]})}var i={escape:r,unescape:o};t.exports=i},{}],25:[function(e,t,n){(function(n){"use strict";var r=e("fbjs/lib/invariant"),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},s=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},u=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},c=function(e){var t=this;e instanceof t?void 0:"production"!==n.env.NODE_ENV?r(!1,"Trying to release an instance into a pool of a different type."):r(!1),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},l=10,p=o,f=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||p,n.poolSize||(n.poolSize=l),n.release=c,n},d={addPoolingTo:f,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:s,fiveArgumentPooler:u};t.exports=d}).call(this,e("_process"))},{_process:23,"fbjs/lib/invariant":4}],26:[function(e,t,n){(function(n){"use strict";var r=e("object-assign"),o=e("./ReactChildren"),i=e("./ReactComponent"),a=e("./ReactClass"),s=e("./ReactDOMFactories"),u=e("./ReactElement"),c=e("./ReactElementValidator"),l=e("./ReactPropTypes"),p=e("./ReactVersion"),f=e("./onlyChild"),d=e("fbjs/lib/warning"),h=u.createElement,v=u.createFactory,y=u.cloneElement;"production"!==n.env.NODE_ENV&&(h=c.createElement,v=c.createFactory,y=c.cloneElement);var m=r;if("production"!==n.env.NODE_ENV){var b=!1;m=function(){return"production"!==n.env.NODE_ENV?d(b,"React.__spread is deprecated and should not be used. Use Object.assign directly or another helper function with similar semantics. You may be seeing this warning due to your compiler. See https://fb.me/react-spread-deprecation for more details."):void 0,b=!0,r.apply(null,arguments)}}var E={Children:{map:o.map,forEach:o.forEach,count:o.count,toArray:o.toArray,only:f},Component:i,createElement:h,cloneElement:y,isValidElement:u.isValidElement,PropTypes:l,createClass:a.createClass,createFactory:v,createMixin:function(e){return e},DOM:s,version:p,__spread:m};t.exports=E}).call(this,e("_process"))},{"./ReactChildren":27,"./ReactClass":28,"./ReactComponent":29,"./ReactDOMFactories":32,"./ReactElement":34,"./ReactElementValidator":35,"./ReactPropTypes":42,"./ReactVersion":43,"./onlyChild":46,_process:23,"fbjs/lib/warning":11,"object-assign":48}],27:[function(e,t,n){"use strict";function r(e){return(""+e).replace(g,"$&/")}function o(e,t){this.func=e,this.context=t,this.count=0}function i(e,t,n){var r=e.func,o=e.context;r.call(o,t,e.count++)}function a(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);m(e,i,r),o.release(r)}function s(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function u(e,t,n){var o=e.result,i=e.keyPrefix,a=e.func,s=e.context,u=a.call(s,t,e.count++);Array.isArray(u)?c(u,o,n,y.thatReturnsArgument):null!=u&&(v.isValidElement(u)&&(u=v.cloneAndReplaceKey(u,i+(!u.key||t&&t.key===u.key?"":r(u.key)+"/")+n)),o.push(u))}function c(e,t,n,o,i){var a="";null!=n&&(a=r(n)+"/");var c=s.getPooled(t,a,o,i);m(e,u,c),s.release(c)}function l(e,t,n){if(null==e)return e;var r=[];return c(e,r,null,t,n),r}function p(e,t,n){return null}function f(e,t){return m(e,p,null)}function d(e){var t=[];return c(e,t,null,y.thatReturnsArgument),t}var h=e("./PooledClass"),v=e("./ReactElement"),y=e("fbjs/lib/emptyFunction"),m=e("./traverseAllChildren"),b=h.twoArgumentPooler,E=h.fourArgumentPooler,g=/\/+/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},h.addPoolingTo(o,b),s.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},h.addPoolingTo(s,E);var N={forEach:a,map:l,mapIntoWithKeyPrefixInternal:c,count:f,toArray:d};t.exports=N},{"./PooledClass":25,"./ReactElement":34,"./traverseAllChildren":47,"fbjs/lib/emptyFunction":2}],28:[function(e,t,n){(function(n){"use strict";function r(e,t,r){for(var o in t)t.hasOwnProperty(o)&&("production"!==n.env.NODE_ENV?w("function"==typeof t[o],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e.displayName||"ReactClass",y[r],o):void 0)}function o(e,t){var r=R.hasOwnProperty(t)?R[t]:null;P.hasOwnProperty(t)&&(r!==O.OVERRIDE_BASE?"production"!==n.env.NODE_ENV?E(!1,"ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.",t):E(!1):void 0),e&&(r!==O.DEFINE_MANY&&r!==O.DEFINE_MANY_MERGED?"production"!==n.env.NODE_ENV?E(!1,"ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",t):E(!1):void 0)}function i(e,t){if(t){"function"==typeof t?"production"!==n.env.NODE_ENV?E(!1,"ReactClass: You're attempting to use a component class or function as a mixin. Instead, just use a regular object."):E(!1):void 0,h.isValidElement(t)?"production"!==n.env.NODE_ENV?E(!1,"ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object."):E(!1):void 0;var r=e.prototype,i=r.__reactAutoBindPairs;t.hasOwnProperty(_)&&x.mixins(e,t.mixins);for(var a in t)if(t.hasOwnProperty(a)&&a!==_){var s=t[a],l=r.hasOwnProperty(a);if(o(l,a),x.hasOwnProperty(a))x[a](e,s);else{var p=R.hasOwnProperty(a),f="function"==typeof s,d=f&&!p&&!l&&t.autobind!==!1;if(d)i.push(a,s),r[a]=s;else if(l){var v=R[a];!p||v!==O.DEFINE_MANY_MERGED&&v!==O.DEFINE_MANY?"production"!==n.env.NODE_ENV?E(!1,"ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.",v,a):E(!1):void 0,v===O.DEFINE_MANY_MERGED?r[a]=u(r[a],s):v===O.DEFINE_MANY&&(r[a]=c(r[a],s))}else r[a]=s,"production"!==n.env.NODE_ENV&&"function"==typeof s&&t.displayName&&(r[a].displayName=t.displayName+"_"+a)}}}}function a(e,t){if(t)for(var r in t){var o=t[r];if(t.hasOwnProperty(r)){var i=r in x;i?"production"!==n.env.NODE_ENV?E(!1,'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.',r):E(!1):void 0;var a=r in e;a?"production"!==n.env.NODE_ENV?E(!1,"ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",r):E(!1):void 0,e[r]=o}}}function s(e,t){e&&t&&"object"==typeof e&&"object"==typeof t?void 0:"production"!==n.env.NODE_ENV?E(!1,"mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects."):E(!1);for(var r in t)t.hasOwnProperty(r)&&(void 0!==e[r]?"production"!==n.env.NODE_ENV?E(!1,"mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.",r):E(!1):void 0,e[r]=t[r]);return e}function u(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return s(o,n),s(o,r),o}}function c(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function l(e,t){var r=t.bind(e);if("production"!==n.env.NODE_ENV){r.__reactBoundContext=e,r.__reactBoundMethod=t,r.__reactBoundArguments=null;var o=e.constructor.displayName,i=r.bind;r.bind=function(a){for(var s=arguments.length,u=Array(s>1?s-1:0),c=1;c<s;c++)u[c-1]=arguments[c];if(a!==e&&null!==a)"production"!==n.env.NODE_ENV?w(!1,"bind(): React component methods may only be bound to the component instance. See %s",o):void 0;else if(!u.length)return"production"!==n.env.NODE_ENV?w(!1,"bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See %s",o):void 0,r;var l=i.apply(r,arguments);return l.__reactBoundContext=e,l.__reactBoundMethod=t,l.__reactBoundArguments=u,l}}return r}function p(e){for(var t=e.__reactAutoBindPairs,n=0;n<t.length;n+=2){var r=t[n],o=t[n+1];e[r]=l(e,o)}}var f=e("object-assign"),d=e("./ReactComponent"),h=e("./ReactElement"),v=e("./ReactPropTypeLocations"),y=e("./ReactPropTypeLocationNames"),m=e("./ReactNoopUpdateQueue"),b=e("fbjs/lib/emptyObject"),E=e("fbjs/lib/invariant"),g=e("fbjs/lib/keyMirror"),N=e("fbjs/lib/keyOf"),w=e("fbjs/lib/warning"),_=N({mixins:null}),O=g({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),D=[],R={mixins:O.DEFINE_MANY,statics:O.DEFINE_MANY,propTypes:O.DEFINE_MANY,contextTypes:O.DEFINE_MANY,childContextTypes:O.DEFINE_MANY,getDefaultProps:O.DEFINE_MANY_MERGED,getInitialState:O.DEFINE_MANY_MERGED,getChildContext:O.DEFINE_MANY_MERGED,render:O.DEFINE_ONCE,componentWillMount:O.DEFINE_MANY,componentDidMount:O.DEFINE_MANY,componentWillReceiveProps:O.DEFINE_MANY,shouldComponentUpdate:O.DEFINE_ONCE,componentWillUpdate:O.DEFINE_MANY,componentDidUpdate:O.DEFINE_MANY,componentWillUnmount:O.DEFINE_MANY,updateComponent:O.OVERRIDE_BASE},x={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)i(e,t[n])},childContextTypes:function(e,t){"production"!==n.env.NODE_ENV&&r(e,t,v.childContext),e.childContextTypes=f({},e.childContextTypes,t)},contextTypes:function(e,t){"production"!==n.env.NODE_ENV&&r(e,t,v.context),e.contextTypes=f({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=u(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){"production"!==n.env.NODE_ENV&&r(e,t,v.prop),e.propTypes=f({},e.propTypes,t)},statics:function(e,t){a(e,t)},autobind:function(){}},P={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t,"replaceState")},isMounted:function(){return this.updater.isMounted(this)}},j=function(){};f(j.prototype,d.prototype,P);var C={createClass:function(e){var t=function(e,r,o){"production"!==n.env.NODE_ENV&&("production"!==n.env.NODE_ENV?w(this instanceof t,"Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory"):void 0),this.__reactAutoBindPairs.length&&p(this),this.props=e,this.context=r,this.refs=b,this.updater=o||m,this.state=null;var i=this.getInitialState?this.getInitialState():null;"production"!==n.env.NODE_ENV&&void 0===i&&this.getInitialState._isMockFunction&&(i=null),"object"!=typeof i||Array.isArray(i)?"production"!==n.env.NODE_ENV?E(!1,"%s.getInitialState(): must return an object or null",t.displayName||"ReactCompositeComponent"):E(!1):void 0,this.state=i};t.prototype=new j,t.prototype.constructor=t,t.prototype.__reactAutoBindPairs=[],D.forEach(i.bind(null,t)),i(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),"production"!==n.env.NODE_ENV&&(t.getDefaultProps&&(t.getDefaultProps.isReactClassApproved={}),t.prototype.getInitialState&&(t.prototype.getInitialState.isReactClassApproved={})),t.prototype.render?void 0:"production"!==n.env.NODE_ENV?E(!1,"createClass(...): Class specification must implement a `render` method."):E(!1),"production"!==n.env.NODE_ENV&&("production"!==n.env.NODE_ENV?w(!t.prototype.componentShouldUpdate,"%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.",e.displayName||"A component"):void 0,"production"!==n.env.NODE_ENV?w(!t.prototype.componentWillRecieveProps,"%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",e.displayName||"A component"):void 0);for(var r in R)t.prototype[r]||(t.prototype[r]=null);return t},injection:{injectMixin:function(e){D.push(e)}}};t.exports=C}).call(this,e("_process"))},{"./ReactComponent":29,"./ReactElement":34,"./ReactNoopUpdateQueue":39,"./ReactPropTypeLocationNames":40,"./ReactPropTypeLocations":41,_process:23,"fbjs/lib/emptyObject":3,"fbjs/lib/invariant":4,"fbjs/lib/keyMirror":5,"fbjs/lib/keyOf":6,"fbjs/lib/warning":11,"object-assign":48}],29:[function(e,t,n){(function(n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=s,this.updater=n||o}var o=e("./ReactNoopUpdateQueue"),i=e("./ReactInstrumentation"),a=e("./canDefineProperty"),s=e("fbjs/lib/emptyObject"),u=e("fbjs/lib/invariant"),c=e("fbjs/lib/warning");if(r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e?"production"!==n.env.NODE_ENV?u(!1,"setState(...): takes an object of state variables to update or a function which returns an object of state variables."):u(!1):void 0,"production"!==n.env.NODE_ENV&&(i.debugTool.onSetState(),"production"!==n.env.NODE_ENV?c(null!=e,"setState(...): You passed an undefined or null state object; instead, use forceUpdate()."):void 0),this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t,"setState")},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e,"forceUpdate")},"production"!==n.env.NODE_ENV){var l={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]},p=function(e,t){a&&Object.defineProperty(r.prototype,e,{get:function(){"production"!==n.env.NODE_ENV?c(!1,"%s(...) is deprecated in plain JavaScript React classes. %s",t[0],t[1]):void 0}})};for(var f in l)l.hasOwnProperty(f)&&p(f,l[f])}t.exports=r}).call(this,e("_process"))},{"./ReactInstrumentation":36,"./ReactNoopUpdateQueue":39,"./canDefineProperty":44,_process:23,"fbjs/lib/emptyObject":3,"fbjs/lib/invariant":4,"fbjs/lib/warning":11}],30:[function(e,t,n){(function(n){"use strict";function r(e,t){a[e]||(a[e]={parentID:null,ownerID:null,text:null,childIDs:[],displayName:"Unknown",isMounted:!1,updateCount:0}),t(a[e])}function o(e){var t=a[e];if(t){var n=t.childIDs;delete a[e],n.forEach(o)}}var i=e("fbjs/lib/invariant"),a={},s=[],u={onSetDisplayName:function(e,t){r(e,function(e){return e.displayName=t})},onSetChildren:function(e,t){r(e,function(r){var o=r.childIDs;r.childIDs=t,t.forEach(function(t){var r=a[t];r?void 0:"production"!==n.env.NODE_ENV?i(!1,"Expected devtool events to fire for the child before its parent includes it in onSetChildren()."):i(!1),null==r.displayName?"production"!==n.env.NODE_ENV?i(!1,"Expected onSetDisplayName() to fire for the child before its parent includes it in onSetChildren()."):i(!1):void 0,null==r.childIDs&&null==r.text?"production"!==n.env.NODE_ENV?i(!1,"Expected onSetChildren() or onSetText() to fire for the child before its parent includes it in onSetChildren()."):i(!1):void 0,r.isMounted?void 0:"production"!==n.env.NODE_ENV?i(!1,"Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren()."):i(!1),o.indexOf(t)===-1&&(r.parentID=e)})})},onSetOwner:function(e,t){r(e,function(e){return e.ownerID=t})},onSetText:function(e,t){r(e,function(e){return e.text=t})},onMountComponent:function(e){r(e,function(e){return e.isMounted=!0})},onMountRootComponent:function(e){s.push(e)},onUpdateComponent:function(e){r(e,function(e){return e.updateCount++})},onUnmountComponent:function(e){r(e,function(e){return e.isMounted=!1}),s=s.filter(function(t){return t!==e})},purgeUnmountedComponents:function(){u._preventPurging||Object.keys(a).filter(function(e){return!a[e].isMounted}).forEach(o)},isMounted:function(e){var t=a[e];return!!t&&t.isMounted},getChildIDs:function(e){var t=a[e];return t?t.childIDs:[]},getDisplayName:function(e){var t=a[e];return t?t.displayName:"Unknown"},getOwnerID:function(e){var t=a[e];return t?t.ownerID:null},getParentID:function(e){var t=a[e];return t?t.parentID:null},getText:function(e){var t=a[e];return t?t.text:null},getUpdateCount:function(e){var t=a[e];return t?t.updateCount:0},getRootIDs:function(){return s},getRegisteredIDs:function(){return Object.keys(a)}};t.exports=u}).call(this,e("_process"))},{_process:23,"fbjs/lib/invariant":4}],31:[function(e,t,n){"use strict";var r={current:null};t.exports=r},{}],32:[function(e,t,n){(function(n){"use strict";function r(e){return"production"!==n.env.NODE_ENV?i.createFactory(e):o.createFactory(e)}var o=e("./ReactElement"),i=e("./ReactElementValidator"),a=e("fbjs/lib/mapObject"),s=a({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hgroup:"hgroup",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul",var:"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",image:"image",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},r);t.exports=s}).call(this,e("_process"))},{"./ReactElement":34,"./ReactElementValidator":35,_process:23,"fbjs/lib/mapObject":7}],33:[function(e,t,n){(function(n){"use strict";function r(e,t,r,o,i,a){"production"!==n.env.NODE_ENV&&p.forEach(function(s){try{s[e]&&s[e](t,r,o,i,a)}catch(t){"production"!==n.env.NODE_ENV?l(!f[e],"exception thrown by devtool while handling %s: %s",e,t.message):void 0,f[e]=!0}})}function o(){O.purgeUnmountedComponents(),_.clearHistory()}function i(e){return e.reduce(function(e,t){var n=O.getOwnerID(t),r=O.getParentID(t);return e[t]={displayName:O.getDisplayName(t),text:O.getText(t),updateCount:O.getUpdateCount(t),childIDs:O.getChildIDs(t),ownerID:n||O.getOwnerID(r),parentID:r},e},{})}function a(){if("production"!==n.env.NODE_ENV){var e=m,t=y||[],r=_.getHistory();if(!d||0===v)return m=null,y=null,void o();if(t.length||r.length){var a=O.getRegisteredIDs();h.push({duration:c()-e,measurements:t||[],operations:r||[],treeSnapshot:i(a)})}o(),m=c(),y=[]}}function s(e){"production"!==n.env.NODE_ENV?l(e,"ReactDebugTool: debugID may not be empty."):void 0}var u=e("fbjs/lib/ExecutionEnvironment"),c=e("fbjs/lib/performanceNow"),l=e("fbjs/lib/warning"),p=[],f={},d=!1,h=[],v=0,y=null,m=null,b=null,E=null,g=null,N={addDevtool:function(e){p.push(e)},removeDevtool:function(e){for(var t=0;t<p.length;t++)p[t]===e&&(p.splice(t,1),t--)},beginProfiling:function(){if("production"!==n.env.NODE_ENV){if(d)return;d=!0,h.length=0,a()}},endProfiling:function(){if("production"!==n.env.NODE_ENV){if(!d)return;d=!1,a()}},getFlushHistory:function(){if("production"!==n.env.NODE_ENV)return h},onBeginFlush:function(){"production"!==n.env.NODE_ENV&&(v++,a()),r("onBeginFlush")},onEndFlush:function(){"production"!==n.env.NODE_ENV&&(a(),v--),r("onEndFlush")},onBeginLifeCycleTimer:function(e,t){s(e),r("onBeginLifeCycleTimer",e,t),"production"!==n.env.NODE_ENV&&d&&v>0&&("production"!==n.env.NODE_ENV?l(!g,"There is an internal error in the React performance measurement code. Did not expect %s timer to start while %s timer is still in progress for %s instance.",t,g||"no",e===b?"the same":"another"):void 0,E=c(),b=e,g=t)},onEndLifeCycleTimer:function(e,t){s(e),"production"!==n.env.NODE_ENV&&d&&v>0&&("production"!==n.env.NODE_ENV?l(g===t,"There is an internal error in the React performance measurement code. We did not expect %s timer to stop while %s timer is still in progress for %s instance. Please report this as a bug in React.",t,g||"no",e===b?"the same":"another"):void 0,
y.push({timerType:t,instanceID:e,duration:c()-E}),E=null,b=null,g=null),r("onEndLifeCycleTimer",e,t)},onBeginReconcilerTimer:function(e,t){s(e),r("onBeginReconcilerTimer",e,t)},onEndReconcilerTimer:function(e,t){s(e),r("onEndReconcilerTimer",e,t)},onBeginProcessingChildContext:function(){r("onBeginProcessingChildContext")},onEndProcessingChildContext:function(){r("onEndProcessingChildContext")},onNativeOperation:function(e,t,n){s(e),r("onNativeOperation",e,t,n)},onSetState:function(){r("onSetState")},onSetDisplayName:function(e,t){s(e),r("onSetDisplayName",e,t)},onSetChildren:function(e,t){s(e),r("onSetChildren",e,t)},onSetOwner:function(e,t){s(e),r("onSetOwner",e,t)},onSetText:function(e,t){s(e),r("onSetText",e,t)},onMountRootComponent:function(e){s(e),r("onMountRootComponent",e)},onMountComponent:function(e){s(e),r("onMountComponent",e)},onUpdateComponent:function(e){s(e),r("onUpdateComponent",e)},onUnmountComponent:function(e){s(e),r("onUnmountComponent",e)}};if("production"!==n.env.NODE_ENV){var w=e("./ReactInvalidSetStateWarningDevTool"),_=e("./ReactNativeOperationHistoryDevtool"),O=e("./ReactComponentTreeDevtool");N.addDevtool(w),N.addDevtool(O),N.addDevtool(_);var D=u.canUseDOM&&window.location.href||"";/[?&]react_perf\b/.test(D)&&N.beginProfiling()}t.exports=N}).call(this,e("_process"))},{"./ReactComponentTreeDevtool":30,"./ReactInvalidSetStateWarningDevTool":37,"./ReactNativeOperationHistoryDevtool":38,_process:23,"fbjs/lib/ExecutionEnvironment":1,"fbjs/lib/performanceNow":9,"fbjs/lib/warning":11}],34:[function(e,t,n){(function(n){"use strict";var r,o,i=e("object-assign"),a=e("./ReactCurrentOwner"),s=e("fbjs/lib/warning"),u=e("./canDefineProperty"),c="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,l={key:!0,ref:!0,__self:!0,__source:!0},p=function(e,t,r,o,i,a,s){var l={$$typeof:c,type:e,key:t,ref:r,props:s,_owner:a};return"production"!==n.env.NODE_ENV&&(l._store={},u?(Object.defineProperty(l._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(l,"_self",{configurable:!1,enumerable:!1,writable:!1,value:o}),Object.defineProperty(l,"_source",{configurable:!1,enumerable:!1,writable:!1,value:i})):(l._store.validated=!1,l._self=o,l._source=i),Object.freeze&&(Object.freeze(l.props),Object.freeze(l))),l};p.createElement=function(e,t,i){var u,f={},d=null,h=null,v=null,y=null;if(null!=t){"production"!==n.env.NODE_ENV?("production"!==n.env.NODE_ENV?s(null==t.__proto__||t.__proto__===Object.prototype,"React.createElement(...): Expected props argument to be a plain object. Properties defined in its prototype chain will be ignored."):void 0,h=!t.hasOwnProperty("ref")||Object.getOwnPropertyDescriptor(t,"ref").get?null:t.ref,d=!t.hasOwnProperty("key")||Object.getOwnPropertyDescriptor(t,"key").get?null:""+t.key):(h=void 0===t.ref?null:t.ref,d=void 0===t.key?null:""+t.key),v=void 0===t.__self?null:t.__self,y=void 0===t.__source?null:t.__source;for(u in t)t.hasOwnProperty(u)&&!l.hasOwnProperty(u)&&(f[u]=t[u])}var m=arguments.length-2;if(1===m)f.children=i;else if(m>1){for(var b=Array(m),E=0;E<m;E++)b[E]=arguments[E+2];f.children=b}if(e&&e.defaultProps){var g=e.defaultProps;for(u in g)void 0===f[u]&&(f[u]=g[u])}return"production"!==n.env.NODE_ENV&&("undefined"!=typeof f.$$typeof&&f.$$typeof===c||(f.hasOwnProperty("key")||Object.defineProperty(f,"key",{get:function(){r||(r=!0,"production"!==n.env.NODE_ENV?s(!1,"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)","function"==typeof e&&"displayName"in e?e.displayName:"Element"):void 0)},configurable:!0}),f.hasOwnProperty("ref")||Object.defineProperty(f,"ref",{get:function(){o||(o=!0,"production"!==n.env.NODE_ENV?s(!1,"%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)","function"==typeof e&&"displayName"in e?e.displayName:"Element"):void 0)},configurable:!0}))),p(e,d,h,v,y,a.current,f)},p.createFactory=function(e){var t=p.createElement.bind(null,e);return t.type=e,t},p.cloneAndReplaceKey=function(e,t){var n=p(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},p.cloneElement=function(e,t,r){var o,u=i({},e.props),c=e.key,f=e.ref,d=e._self,h=e._source,v=e._owner;if(null!=t){"production"!==n.env.NODE_ENV&&("production"!==n.env.NODE_ENV?s(null==t.__proto__||t.__proto__===Object.prototype,"React.cloneElement(...): Expected props argument to be a plain object. Properties defined in its prototype chain will be ignored."):void 0),void 0!==t.ref&&(f=t.ref,v=a.current),void 0!==t.key&&(c=""+t.key);var y;e.type&&e.type.defaultProps&&(y=e.type.defaultProps);for(o in t)t.hasOwnProperty(o)&&!l.hasOwnProperty(o)&&(void 0===t[o]&&void 0!==y?u[o]=y[o]:u[o]=t[o])}var m=arguments.length-2;if(1===m)u.children=r;else if(m>1){for(var b=Array(m),E=0;E<m;E++)b[E]=arguments[E+2];u.children=b}return p(e.type,c,f,d,h,v,u)},p.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===c},t.exports=p}).call(this,e("_process"))},{"./ReactCurrentOwner":31,"./canDefineProperty":44,_process:23,"fbjs/lib/warning":11,"object-assign":48}],35:[function(e,t,n){(function(n){"use strict";function r(){if(f.current){var e=f.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var r=i("uniqueKey",e,t);null!==r&&("production"!==n.env.NODE_ENV?y(!1,'Each child in an array or iterator should have a unique "key" prop.%s%s%s',r.parentOrOwner||"",r.childOwner||"",r.url||""):void 0)}}function i(e,t,n){var o=r();if(!o){var i="string"==typeof n?n:n.displayName||n.name;i&&(o=" Check the top-level render call using <"+i+">.")}var a=m[e]||(m[e]={});if(a[o])return null;a[o]=!0;var s={parentOrOwner:o,url:" See https://fb.me/react-warning-keys for more information.",childOwner:null};return t&&t._owner&&t._owner!==f.current&&(s.childOwner=" It was passed a child from "+t._owner.getName()+"."),s}function a(e,t){if("object"==typeof e)if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];c.isValidElement(r)&&o(r,t)}else if(c.isValidElement(e))e._store&&(e._store.validated=!0);else if(e){var i=h(e);if(i&&i!==e.entries)for(var a,s=i.call(e);!(a=s.next()).done;)c.isValidElement(a.value)&&o(a.value,t)}}function s(e,t,o,i){for(var a in t)if(t.hasOwnProperty(a)){var s;try{"function"!=typeof t[a]?"production"!==n.env.NODE_ENV?v(!1,"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e||"React class",p[i],a):v(!1):void 0,s=t[a](o,a,e,i)}catch(e){s=e}if("production"!==n.env.NODE_ENV?y(!s||s instanceof Error,"%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",e||"React class",p[i],a,typeof s):void 0,s instanceof Error&&!(s.message in b)){b[s.message]=!0;var u=r();"production"!==n.env.NODE_ENV?y(!1,"Failed propType: %s%s",s.message,u):void 0}}}function u(e){var t=e.type;if("function"==typeof t){var r=t.displayName||t.name;t.propTypes&&s(r,t.propTypes,e.props,l.prop),"function"==typeof t.getDefaultProps&&("production"!==n.env.NODE_ENV?y(t.getDefaultProps.isReactClassApproved,"getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."):void 0)}}var c=e("./ReactElement"),l=e("./ReactPropTypeLocations"),p=e("./ReactPropTypeLocationNames"),f=e("./ReactCurrentOwner"),d=e("./canDefineProperty"),h=e("./getIteratorFn"),v=e("fbjs/lib/invariant"),y=e("fbjs/lib/warning"),m={},b={},E={createElement:function(e,t,o){var i="string"==typeof e||"function"==typeof e;"production"!==n.env.NODE_ENV?y(i,"React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).%s",r()):void 0;var s=c.createElement.apply(this,arguments);if(null==s)return s;if(i)for(var l=2;l<arguments.length;l++)a(arguments[l],e);return u(s),s},createFactory:function(e){var t=E.createElement.bind(null,e);return t.type=e,"production"!==n.env.NODE_ENV&&d&&Object.defineProperty(t,"type",{enumerable:!1,get:function(){return"production"!==n.env.NODE_ENV?y(!1,"Factory.type is deprecated. Access the class directly before passing it to createFactory."):void 0,Object.defineProperty(this,"type",{value:e}),e}}),t},cloneElement:function(e,t,n){for(var r=c.cloneElement.apply(this,arguments),o=2;o<arguments.length;o++)a(arguments[o],r.type);return u(r),r}};t.exports=E}).call(this,e("_process"))},{"./ReactCurrentOwner":31,"./ReactElement":34,"./ReactPropTypeLocationNames":40,"./ReactPropTypeLocations":41,"./canDefineProperty":44,"./getIteratorFn":45,_process:23,"fbjs/lib/invariant":4,"fbjs/lib/warning":11}],36:[function(e,t,n){"use strict";var r=e("./ReactDebugTool");t.exports={debugTool:r}},{"./ReactDebugTool":33}],37:[function(e,t,n){(function(n){"use strict";var r=e("fbjs/lib/warning");if("production"!==n.env.NODE_ENV)var o=!1,i=function(){"production"!==n.env.NODE_ENV?r(!o,"setState(...): Cannot call setState() inside getChildContext()"):void 0};var a={onBeginProcessingChildContext:function(){o=!0},onEndProcessingChildContext:function(){o=!1},onSetState:function(){i()}};t.exports=a}).call(this,e("_process"))},{_process:23,"fbjs/lib/warning":11}],38:[function(e,t,n){"use strict";var r=[],o={onNativeOperation:function(e,t,n){r.push({instanceID:e,type:t,payload:n})},clearHistory:function(){o._preventClearing||(r=[])},getHistory:function(){return r}};t.exports=o},{}],39:[function(e,t,n){(function(n){"use strict";function r(e,t){"production"!==n.env.NODE_ENV&&("production"!==n.env.NODE_ENV?o(!1,"%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op. Please check the code for the %s component.",t,t,e.constructor&&e.constructor.displayName||""):void 0)}var o=e("fbjs/lib/warning"),i={isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e,t){r(e,"replaceState")},enqueueSetState:function(e,t){r(e,"setState")}};t.exports=i}).call(this,e("_process"))},{_process:23,"fbjs/lib/warning":11}],40:[function(e,t,n){(function(e){"use strict";var n={};"production"!==e.env.NODE_ENV&&(n={prop:"prop",context:"context",childContext:"child context"}),t.exports=n}).call(this,e("_process"))},{_process:23}],41:[function(e,t,n){"use strict";var r=e("fbjs/lib/keyMirror"),o=r({prop:null,context:null,childContext:null});t.exports=o},{"fbjs/lib/keyMirror":5}],42:[function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function o(e){function t(t,n,r,o,i,a){if(o=o||_,a=a||r,null==n[r]){var s=g[i];return t?new Error("Required "+s+" `"+a+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,i,a)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function i(e){function t(t,n,r,o,i){var a=t[n],s=y(a);if(s!==e){var u=g[o],c=m(a);return new Error("Invalid "+u+" `"+i+"` of type "+("`"+c+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return o(t)}function a(){return o(N.thatReturns(null))}function s(e){function t(t,n,r,o,i){if("function"!=typeof e)return new Error("Property `"+i+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var a=t[n];if(!Array.isArray(a)){var s=g[o],u=y(a);return new Error("Invalid "+s+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an array."))}for(var c=0;c<a.length;c++){var l=e(a,c,r,o,i+"["+c+"]");if(l instanceof Error)return l}return null}return o(t)}function u(){function e(e,t,n,r,o){if(!E.isValidElement(e[t])){var i=g[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a single ReactElement."))}return null}return o(e)}function c(e){function t(t,n,r,o,i){if(!(t[n]instanceof e)){var a=g[o],s=e.name||_,u=b(t[n]);return new Error("Invalid "+a+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected ")+("instance of `"+s+"`."))}return null}return o(t)}function l(e){function t(t,n,o,i,a){for(var s=t[n],u=0;u<e.length;u++)if(r(s,e[u]))return null;var c=g[i],l=JSON.stringify(e);return new Error("Invalid "+c+" `"+a+"` of value `"+s+"` "+("supplied to `"+o+"`, expected one of "+l+"."))}return o(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function p(e){function t(t,n,r,o,i){if("function"!=typeof e)return new Error("Property `"+i+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var a=t[n],s=y(a);if("object"!==s){var u=g[o];return new Error("Invalid "+u+" `"+i+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an object."))}for(var c in a)if(a.hasOwnProperty(c)){var l=e(a,c,r,o,i+"."+c);if(l instanceof Error)return l}return null}return o(t)}function f(e){function t(t,n,r,o,i){for(var a=0;a<e.length;a++){var s=e[a];if(null==s(t,n,r,o,i))return null}var u=g[o];return new Error("Invalid "+u+" `"+i+"` supplied to "+("`"+r+"`."))}return o(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function d(){function e(e,t,n,r,o){if(!v(e[t])){var i=g[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return o(e)}function h(e){function t(t,n,r,o,i){var a=t[n],s=y(a);if("object"!==s){var u=g[o];return new Error("Invalid "+u+" `"+i+"` of type `"+s+"` "+("supplied to `"+r+"`, expected `object`."))}for(var c in e){var l=e[c];if(l){var p=l(a,c,r,o,i+"."+c);if(p)return p}}return null}return o(t)}function v(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(v);if(null===e||E.isValidElement(e))return!0;var t=w(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!v(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!v(o[1]))return!1}return!0;default:return!1}}function y(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=y(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function b(e){return e.constructor&&e.constructor.name?e.constructor.name:_}var E=e("./ReactElement"),g=e("./ReactPropTypeLocationNames"),N=e("fbjs/lib/emptyFunction"),w=e("./getIteratorFn"),_="<<anonymous>>",O={array:i("array"),bool:i("boolean"),func:i("function"),number:i("number"),object:i("object"),string:i("string"),any:a(),arrayOf:s,element:u(),instanceOf:c,node:d(),objectOf:p,oneOf:l,oneOfType:f,shape:h};t.exports=O},{"./ReactElement":34,"./ReactPropTypeLocationNames":40,"./getIteratorFn":45,"fbjs/lib/emptyFunction":2}],43:[function(e,t,n){"use strict";t.exports="15.1.0"},{}],44:[function(e,t,n){(function(e){"use strict";var n=!1;if("production"!==e.env.NODE_ENV)try{Object.defineProperty({},"x",{get:function(){}}),n=!0}catch(e){}t.exports=n}).call(this,e("_process"))},{_process:23}],45:[function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[i]);if("function"==typeof t)return t}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";t.exports=r},{}],46:[function(e,t,n){(function(n){"use strict";function r(e){return o.isValidElement(e)?void 0:"production"!==n.env.NODE_ENV?i(!1,"onlyChild must be passed a children with exactly one child."):i(!1),e}var o=e("./ReactElement"),i=e("fbjs/lib/invariant");t.exports=r}).call(this,e("_process"))},{"./ReactElement":34,_process:23,"fbjs/lib/invariant":4}],47:[function(e,t,n){(function(n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?l.escape(e.key):t.toString(36)}function o(e,t,i,v){var y=typeof e;if("undefined"!==y&&"boolean"!==y||(e=null),null===e||"string"===y||"number"===y||s.isValidElement(e))return i(v,e,""===t?f+r(e,0):t),1;var m,b,E=0,g=""===t?f:t+d;if(Array.isArray(e))for(var N=0;N<e.length;N++)m=e[N],b=g+r(m,N),E+=o(m,b,i,v);else{var w=u(e);if(w){var _,O=w.call(e);if(w!==e.entries)for(var D=0;!(_=O.next()).done;)m=_.value,b=g+r(m,D++),E+=o(m,b,i,v);else for("production"!==n.env.NODE_ENV&&("production"!==n.env.NODE_ENV?p(h,"Using Maps as children is not yet fully supported. It is an experimental feature that might be removed. Convert it to a sequence / iterable of keyed ReactElements instead."):void 0,h=!0);!(_=O.next()).done;){var R=_.value;R&&(m=R[1],b=g+l.escape(R[0])+d+r(m,0),E+=o(m,b,i,v))}}else if("object"===y){var x="";if("production"!==n.env.NODE_ENV&&(x=" If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.",e._isReactElement&&(x=" It looks like you're using an element created by a different version of React. Make sure to use only one copy of React."),a.current)){var P=a.current.getName();P&&(x+=" Check the render method of `"+P+"`.")}var j=String(e);"production"!==n.env.NODE_ENV?c(!1,"Objects are not valid as a React child (found: %s).%s","[object Object]"===j?"object with keys {"+Object.keys(e).join(", ")+"}":j,x):c(!1)}}return E}function i(e,t,n){return null==e?0:o(e,"",t,n)}var a=e("./ReactCurrentOwner"),s=e("./ReactElement"),u=e("./getIteratorFn"),c=e("fbjs/lib/invariant"),l=e("./KeyEscapeUtils"),p=e("fbjs/lib/warning"),f=".",d=":",h=!1;t.exports=i}).call(this,e("_process"))},{"./KeyEscapeUtils":24,"./ReactCurrentOwner":31,"./ReactElement":34,"./getIteratorFn":45,_process:23,"fbjs/lib/invariant":4,"fbjs/lib/warning":11}],48:[function(e,t,n){"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function o(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(e){return!1}}var i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;t.exports=o()?Object.assign:function(e,t){for(var n,o,s=r(e),u=1;u<arguments.length;u++){n=Object(arguments[u]);for(var c in n)i.call(n,c)&&(s[c]=n[c]);if(Object.getOwnPropertySymbols){o=Object.getOwnPropertySymbols(n);for(var l=0;l<o.length;l++)a.call(n,o[l])&&(s[o[l]]=n[o[l]])}}return s}},{}],49:[function(e,t,n){"use strict";t.exports=e("./lib/React")},{"./lib/React":26}],50:[function(e,t,n){(function(){var e,n,r,o,i={}.hasOwnProperty;n=/^(?:(?:([^:\/?\#]+:)\/+|(\/\/))(?:([a-z0-9-\._~%]+)(?::([a-z0-9-\._~%]+))?@)?(([a-z0-9-\._~%!$&'()*+,;=]+)(?::([0-9]+))?)?)?([^?\#]*?)(\?[^\#]*)?(\#.*)?$/,o=function(e,t){return o.URL.parse(e,t)},o.URL=e=function(){function e(e){var t,n,o;for(t in r)i.call(r,t)&&(n=r[t],this[t]=null!=(o=e[t])?o:n);this.host||(this.host=this.hostname&&this.port?""+this.hostname+":"+this.port:this.hostname?this.hostname:""),this.origin||(this.origin=this.protocol?""+this.protocol+"//"+this.host:""),this.isAbsolutePathRelative=!this.host&&"/"===this.pathname.charAt(0),this.isPathRelative=!this.host&&"/"!==this.pathname.charAt(0),this.isRelative=this.isSchemeRelative||this.isAbsolutePathRelative||this.isPathRelative,this.isAbsolute=!this.isRelative}return e.parse=function(e){var t,r,i;return t=e.toString().match(n),r=t[8]||"",i=t[1],new o.URL({protocol:i,username:t[3],password:t[4],hostname:t[6],port:t[7],pathname:i&&"/"!==r.charAt(0)?"/"+r:r,search:t[9],hash:t[10],isSchemeRelative:null!=t[2]})},e}(),r={protocol:"",username:"",password:"",host:"",hostname:"",port:"",pathname:"",search:"",hash:"",origin:"",isSchemeRelative:!1},t.exports=o}).call(this)},{}],51:[function(e,t,n){function r(e,t){function n(){for(var t=new Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),o=t[t.length-1];return"function"==typeof r&&r!==o&&Object.keys(o).forEach(function(e){r[e]=o[e]}),r}if(e&&t)return r(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach(function(t){n[t]=e[t]}),n}t.exports=r},{}],52:[function(e,t,n){function r(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var r in n)n.hasOwnProperty(r)&&(e[r]=n[r])}return e}t.exports=r},{}],53:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(n,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=e("react"),c=r(u),l=e("once"),p=r(l),f=e("httpplease"),d=r(f),h=e("httpplease/plugins/oldiexdomain"),v=r(h),y=e("./shouldComponentUpdate"),m=d.default.use(v.default),b={PENDING:"pending",LOADING:"loading",LOADED:"loaded",FAILED:"failed",UNSUPPORTED:"unsupported"},E=(0,p.default)(function(){if(!document)return!1;var e=document.createElement("div");return e.innerHTML="<svg />",e.firstChild&&"http://www.w3.org/2000/svg"===e.firstChild.namespaceURI}),g=(0,p.default)(function(){return(("undefined"!=typeof window&&null!==window?window.XMLHttpRequest:void 0)||("undefined"!=typeof window&&null!==window?window.XDomainRequest:void 0))&&E()}),N=function(){var e=function(e){return"(?:(?:\\s|\\:)"+e+")"},t=new RegExp("(?:("+e("id")+')="([^"]+)")|(?:('+e("href")+"|"+e("role")+"|"+e("arcrole")+')="\\#([^"]+)")|(?:="url\\(\\#([^\\)]+)\\)")',"g");return function(e,n){var r=function(e){return e+"___"+n};return e.replace(t,function(e,t,n,o,i,a){return n?t+'="'+r(n)+'"':i?o+'="#'+r(i)+'"':a?'="url(#'+r(a)+')"':void 0})}}(),w=function(e){var t=void 0,n=0,r=void 0,o=void 0,i=void 0;if(!e)return n;for(r=0,o=0,i=e.length;i<=0?o<i:o>i;r=i<=0?++o:--o)t=e.charCodeAt(r),n=(n<<5)-n+t,n&=n;return n},_=function(e){function t(e){var n;o(this,t);var r=i(this,Object.getPrototypeOf(t).call(this));return r.name="InlineSVGError",r.isSupportedBrowser=!0,r.isConfigurationError=!1,r.isUnsupportedBrowserError=!1,r.message=e,n=r,i(r,n)}return a(t,e),t}(Error),O=function(e,t){var n=new _(e);return Object.keys(t).forEach(function(e){n[e]=t[e]}),n},D=function(e){var t=e;return null===t&&(t="Unsupported Browser"),O(t,{isSupportedBrowser:!1,isUnsupportedBrowserError:!0})},R=function(e){return O(e,{isConfigurationError:!0})},x=function(e){function t(e){o(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.shouldComponentUpdate=y.shouldComponentUpdate,n.state={status:b.PENDING},n.handleLoad=n.handleLoad.bind(n),n}return a(t,e),s(t,[{key:"componentWillMount",value:function(){this.state.status===b.PENDING&&(this.props.supportTest()?this.props.src?this.setState({status:b.LOADING},this.load):this.fail(R("Missing source")):this.fail(D()))}},{key:"fail",value:function(e){var t=this,n=e.isUnsupportedBrowserError?b.UNSUPPORTED:b.FAILED;this.setState({status:n},function(){"function"==typeof t.props.onError&&t.props.onError(e)})}},{key:"handleLoad",value:function(e,t){var n=this;return e?void this.fail(e):void this.setState({loadedText:t.text,status:b.LOADED},function(){return"function"==typeof n.props.onLoad?n.props.onLoad():null})}},{key:"load",value:function(){var e=this.props.src.match(/data:image\/svg[^,]*?(;base64)?,(.*)/);return e?this.handleLoad(null,{text:e[1]?atob(e[2]):decodeURIComponent(e[2])}):m.get(this.props.src,this.handleLoad)}},{key:"getClassName",value:function(){var e="isvg "+this.state.status;return this.props.className&&(e+=" "+this.props.className),e}},{key:"processSVG",value:function(e){return this.props.uniquifyIDs?N(e,w(this.props.src)):e}},{key:"renderContents",value:function(){switch(this.state.status){case b.UNSUPPORTED:return this.props.children;default:return this.props.preloader}}},{key:"render",value:function(){return this.props.wrapper({className:this.getClassName(),dangerouslySetInnerHTML:this.state.loadedText?{__html:this.processSVG(this.state.loadedText)}:void 0},this.renderContents())}}]),t}(c.default.Component);x.propTypes={children:c.default.PropTypes.node,className:c.default.PropTypes.string,onError:c.default.PropTypes.func,onLoad:c.default.PropTypes.func,preloader:c.default.PropTypes.func,src:c.default.PropTypes.string.isRequired,supportTest:c.default.PropTypes.func,uniquifyIDs:c.default.PropTypes.bool,wrapper:c.default.PropTypes.func},x.defaultProps={wrapper:c.default.DOM.span,supportTest:g,uniquifyIDs:!0},n.default=x,t.exports=n.default},{"./shouldComponentUpdate":54,httpplease:13,"httpplease/plugins/oldiexdomain":21,once:22,react:49}],54:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){return!(0,s.default)(this.props,e)||!(0,s.default)(this.state,t)}function i(e,t,n){return!(0,s.default)(this.props,e)||!(0,s.default)(this.state,t)||!(0,s.default)(this.context,n)}Object.defineProperty(n,"__esModule",{value:!0}),n.shouldComponentUpdate=o,n.shouldComponentUpdateContext=i;var a=e("fbjs/lib/shallowEqual"),s=r(a);n.default={shouldComponentUpdate:o,shouldComponentUpdateContext:i}},{"fbjs/lib/shallowEqual":10}]},{},[53])(53)}); |
docs/src/examples/modules/Checkbox/States/index.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import { Message } from 'semantic-ui-react'
import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection'
const CheckboxStatesExamples = () => (
<ExampleSection title='States'>
<ComponentExample
title='Read Only'
description='A checkbox can be read-only and unable to change states.'
examplePath='modules/Checkbox/States/CheckboxExampleReadOnly'
/>
<ComponentExample
title='Checked'
description='A checkbox can be checked.'
examplePath='modules/Checkbox/States/CheckboxExampleChecked'
>
<Message>
Use{' '}
<a
href='https://facebook.github.io/react/docs/forms.html#default-value'
rel='noopener noreferrer'
target='_blank'
>
<code>defaultChecked</code>
</a>{' '}
as you normally would to set default form values.
</Message>
</ComponentExample>
<ComponentExample
title='Indeterminate'
description='A checkbox can be indeterminate.'
examplePath='modules/Checkbox/States/CheckboxExampleIndeterminate'
/>
<ComponentExample
title='Disabled'
description='A checkbox can be read-only and unable to change states.'
examplePath='modules/Checkbox/States/CheckboxExampleDisabled'
/>
</ExampleSection>
)
export default CheckboxStatesExamples
|
app/components/MyProfileBox/index.js | yoohan-dex/myBlog | /**
*
* MyProfileBox
*
*/
import React from 'react';
import styles from './styles.css';
function MyProfileBox() {
return (
<div className={styles.myProfileBox}>
</div>
);
}
export default MyProfileBox;
|
web/index.js | mrcnc/spatialconnect-server | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { syncHistoryWithStore, routerReducer, routerMiddleware } from 'react-router-redux';
import throttle from 'lodash/throttle';
import appReducer from './ducks';
import { loginPersistedUser } from './ducks/auth';
import AppContainer from './containers/AppContainer';
import { loadState, saveState, requireAuthentication } from './utils';
import HomeContainer from './containers/HomeContainer';
import SignUpContainer from './containers/SignUpContainer';
import SignInContainer from './containers/SignInContainer';
import DataStoresContainer from './containers/DataStoresContainer';
import FormsContainer from './containers/FormsContainer';
import FormDetailsContainer from './containers/FormDetailsContainer';
import DataStoresDetailsContainer from './containers/DataStoresDetailsContainer';
import DataContainer from './containers/DataContainer';
import TeamsContainer from './containers/TeamsContainer';
import TeamDetailsContainer from './containers/TeamDetailsContainer';
import MessageContainer from './containers/MessageContainer';
import './style/Globals.less';
// combine all the reducers into a single reducing function
const rootReducer = combineReducers({
sc: appReducer,
routing: routerReducer,
});
// create the redux store that holds the state for this app
// http://redux.js.org/docs/api/createStore.html
const middleware = routerMiddleware(browserHistory);
const store = createStore(
rootReducer,
applyMiddleware(middleware, thunk, createLogger()) // logger must be the last in the chain
);
const persistedUser = loadState();
const token = persistedUser ? persistedUser.token : null;
const user = persistedUser ? persistedUser.user : null;
if (token !== null && user !== null) {
store.dispatch(loginPersistedUser(token, user));
}
store.subscribe(
throttle(() => {
saveState({
user: store.getState().sc.auth.user,
token: store.getState().sc.auth.token,
});
}, 1000)
);
// create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);
// wrap the App component with the react-redux Provider component to make the
// store available to all container components without passing it down
// explicitly as a prop
render(
<Provider store={store}>
<Router history={history}>
<Route path="/" name="Home" component={AppContainer}>
<IndexRoute component={requireAuthentication(HomeContainer)} />
<Route path="/login" name="Login" component={SignInContainer} />
<Route path="/signup" name="Sign Up" component={SignUpContainer} />
<Route path="/stores" name="Stores" component={requireAuthentication(DataStoresContainer)}>
<Route
path="/stores/:id"
staticName
component={requireAuthentication(DataStoresDetailsContainer)}
/>
</Route>
<Route path="/forms" name="Forms" component={requireAuthentication(FormsContainer)}>
<Route
path="/forms/:form_key"
staticName
component={requireAuthentication(FormDetailsContainer)}
/>
</Route>
<Route path="/data" name="Data" component={requireAuthentication(DataContainer)} />
<Route path="/teams" name="Teams" component={requireAuthentication(TeamsContainer)}>
<Route
path="/teams/:id"
staticName
component={requireAuthentication(TeamDetailsContainer)}
/>
</Route>
<Route
path="/messages"
name="Messages"
component={requireAuthentication(MessageContainer)}
/>
</Route>
</Router>
</Provider>,
document.getElementById('root')
);
|
views/ios/main.js | MervynFang/playwithreactnative | /**
* @Author: MervynFang
* @Date: 2016,May,01 18:08:02
* @Last modified by: Mervyn
* @Last modified time: 2016,Aug,01 01:17:14
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Alert,
ScrollView,
Image,
Platform,
ToastAndroid,
TouchableHighlight,
TouchableOpacity
} from 'react-native';
import {ImagePickerManager} from 'NativeModules';
import {Screen} from 'NativeModules';
import {MKButton, MKColor} from 'react-native-material-kit';
import {Cam} from './cam';
import {styles} from '../../styles/styles';
const BasicButton = MKButton.coloredFab()
.withBackgroundColor(MKColor.Cyan)
// .withText('Add Pic')
// .withOnPress(() => {
// this.selectImage();
// })
// .withShadowColor('black')
.withStyle({
width: 60,
height: 60,
borderRadius: 30,
// todo 这里开了chrome debug 卡顿,不过也没有关系啦
elevation: 0, // 去掉阴影
})
.build();
const MainButton = MKButton.coloredButton()
.withBackgroundColor(MKColor.Cyan)
.withStyle({
width: 80,
height: 80,
borderRadius: 40,
elevation: 0, // 去掉阴影
})
.build();
class Main extends Component {
// state = {
// selectedImage: null
// };
constructor(props) {
super(props);
this.state = {
selectedImage: null, // 选中图片的路径
imageData: null, // 图像的base64数据
faceData: null, // 脸部的数据 json
imageWidth: null, // 图片原来的宽度
imageHeight: null, // 图片原来的高度
regTag: 0 // 是否显示识别框
};
}
selectImage() {
const options = {
title: 'Please select image',
cancelButtonTitle: 'Cancel',
takePhotoButtonTitle: 'Camera',
chooseFromLibraryButtonTitle: 'Gallery',
// quality: 0.5,
// maxWidth: 300,
// maxHeight: 300,
allowsEditing: false,
aspectX: 3, // android only - aspectX:aspectY, the cropping image's ratio of width to height
aspectY: 4, // android only
};
ImagePickerManager.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
// camera always be here
}
else if (response.error) {
console.log('ImagePickerManager Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
// You can display the image using either:
//const source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true};
var source, image;
if (Platform.OS === 'android') {
source = {uri: 'file://' + response.path, isStatic: true};
console.log(source);
image = response.data;
} else {
source = {uri: response.uri.replace('file://', ''), isStatic: true};
}
this.setState({
selectedImage: source,
imageData: image,
imageWidth: response.width,
imageHeight: response.height,
regTag: 0
});
}
});
}
getObject(obj) {
let a = '';
for(let i in this.state.selectedImage){
a = a + i + ':' + this.state.selectedImage[i];
}
return a;
}
handleState() {
this.setState({
regTag: 1
});
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity
onPress={this.selectImage.bind(this)}>
{this.state.selectedImage === null
? <View style={styles.selectdesp}>
<Text style={styles.desptxt}>Please select image</Text>
</View>
: <Image
source={this.state.selectedImage}
resizeMode={Image.resizeMode.contain}
style={styles.pic}/>}
</TouchableOpacity>
<View style={styles.btn2}>
<BasicButton
onPress={() => {
if (this.state.selectedImage === null) {
ToastAndroid.show('Please select image', ToastAndroid.SHORT)
} else {
Alert.alert('Save to Gallery', 'Would you like to save to Gallery?', [
{
text: 'Cancel',
onPress: () => ToastAndroid.show('Save fail', ToastAndroid.SHORT)
},
{
text: 'OK',
onPress: () => {
ToastAndroid.show('Save succeed', ToastAndroid.SHORT);
Screen.screenShot();
}
}
]);
}
}}>
<Image
pointerEvents='none'
style={styles.gall}
source={require('../../images/gallery.png')} />
</BasicButton>
</View>
{
// <Cam
// selectedImage={this.state.selectedImage}
// imageData={this.state.imageData}
// imageWidth={this.state.imageWidth}
// imageHeight={this.state.imageHeight}
// regTag={this.state.regTag}
// handleState={this.handleState.bind(this)}></Cam>
}
<View style={styles.mainbtn}>
<MainButton
onPress={() => {
if (selectedImage === null) {
ToastAndroid.show('Please select image', ToastAndroid.SHORT)
} else {
ToastAndroid.show('Intelegent Recognizing', ToastAndroid.SHORT)
this.detectFace();
}
}
}>
<Image
pointerEvents='none'
source={require('../../images/main.png')} />
</MainButton>
</View>
<View style={styles.btn}>
<BasicButton
onPress={this.selectImage.bind(this)}>
<Image
pointerEvents='none'
style={styles.plus}
source={require('../../images/plus_white.png')} />
</BasicButton>
</View>
</View>
);
}
}
export {Main}; |
containerComponents/src/PersonList.js | wandarkaf/React-Bible | import React, { Component } from 'react';
class PersonList extends Component {
render() {
return <ul>{this.props.people.map(this.renderPerson)}</ul>
}
renderPerson(person) {
return <li key={person.sha1}>{person.name.first} {person.name.last}</li>
}
}
export default PersonList;
|
src/js/schedule-app/components/filters/index.js | DevFestNordeste/ne.devfest.com.br | import React from 'react';
import Popover from 'react-popover';
export const FilterCheckbox = ({ checked, onChange, label, ...props }) => (
<label className="schedule_category" { ...props }>
<input
checked={checked}
type="checkbox"
onChange={onChange}
/>
{` ${label}`}
</label>
)
export const EventTypeFilter = ({ types, onChange, filter }) => (
<div className="category-filter">
{types.map(type => (
<FilterCheckbox
checked={filter.includes(type)}
onChange={() => onChange(type)}
label={type}
key={type}
/>
))}
</div>
)
export const CategoryFilter = ({ categories, onChange, filter }) => (
<div className="category-filter">
{categories.map(category => (
<FilterCheckbox
checked={filter.includes(category)}
key={category}
onChange={() => onChange(category)}
label={category}
/>
))}
</div>
)
export class FilterBox extends React.Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e) {
e.preventDefault();
this.input.blur();
}
render() {
const { value, onChange, onClick, isPopoverOpened, advancedFilters } = this.props;
return (
<div className="filter-box">
<form onSubmit={this.onSubmit} className="filters-search">
<i className="material-icons">search</i>
<input
ref={input => this.input = input}
value={value}
onChange={onChange}
placeholder="Pesquisar palestra, autor, sala, categoria..."
/>
</form>
<Popover
preferPlace="below"
refreshIntervalMs={100}
enterExitTransitionDurationMs={0}
onOuterAction={onClick}
isOpen={isPopoverOpened}
body={advancedFilters}
>
<button onClick={onClick} className="filters-button">
<i className="material-icons">filter_list</i>
</button>
</Popover>
</div>
);
}
}
|
ajax/libs/js-data/2.2.3/js-data.js | jdh8/cdnjs | /*!
* js-data
* @version 2.2.3 - Homepage <http://www.js-data.io/>
* @author Jason Dobry <jason.dobry@gmail.com>
* @copyright (c) 2014-2015 Jason Dobry
* @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE>
*
* @overview Robust framework-agnostic data store.
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define(factory);
else if(typeof exports === 'object')
exports["JSData"] = factory();
else
root["JSData"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var _datastoreIndex = __webpack_require__(1);
var _utils = __webpack_require__(2);
var _errors = __webpack_require__(3);
/**
* The library export.
* - window.JSData
* - require('js-data')
* - define(['js-data', function (JSData) { ... }]);
* - import JSData from 'js-data'
*/
module.exports = {
DS: _datastoreIndex['default'],
DSUtils: _utils['default'],
DSErrors: _errors['default'],
createStore: function createStore(options) {
return new _datastoreIndex['default'](options);
},
version: {
full: '2.2.3',
major: parseInt('2', 10),
minor: parseInt('2', 10),
patch: parseInt('3', 10),
alpha: true ? 'false' : false,
beta: true ? 'false' : false
}
};
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
/* jshint eqeqeq:false */
var _utils = __webpack_require__(2);
var _errors = __webpack_require__(3);
var _sync_methodsIndex = __webpack_require__(4);
var _async_methodsIndex = __webpack_require__(5);
function lifecycleNoopCb(resource, attrs, cb) {
cb(null, attrs);
}
function lifecycleNoop(resource, attrs) {
return attrs;
}
function compare(_x, _x2, _x3, _x4) {
var _again = true;
_function: while (_again) {
var orderBy = _x,
index = _x2,
a = _x3,
b = _x4;
def = cA = cB = undefined;
_again = false;
var def = orderBy[index];
var cA = _utils['default'].get(a, def[0]),
cB = _utils['default'].get(b, def[0]);
if (_utils['default']._s(cA)) {
cA = _utils['default'].upperCase(cA);
}
if (_utils['default']._s(cB)) {
cB = _utils['default'].upperCase(cB);
}
if (def[1] === 'DESC') {
if (cB < cA) {
return -1;
} else if (cB > cA) {
return 1;
} else {
if (index < orderBy.length - 1) {
_x = orderBy;
_x2 = index + 1;
_x3 = a;
_x4 = b;
_again = true;
continue _function;
} else {
return 0;
}
}
} else {
if (cA < cB) {
return -1;
} else if (cA > cB) {
return 1;
} else {
if (index < orderBy.length - 1) {
_x = orderBy;
_x2 = index + 1;
_x3 = a;
_x4 = b;
_again = true;
continue _function;
} else {
return 0;
}
}
}
}
}
var Defaults = (function () {
function Defaults() {
_classCallCheck(this, Defaults);
}
_createClass(Defaults, [{
key: 'errorFn',
value: function errorFn(a, b) {
if (this.error && typeof this.error === 'function') {
try {
if (typeof a === 'string') {
throw new Error(a);
} else {
throw a;
}
} catch (err) {
a = err;
}
this.error(this.name || null, a || null, b || null);
}
}
}]);
return Defaults;
})();
var defaultsPrototype = Defaults.prototype;
defaultsPrototype.actions = {};
defaultsPrototype.afterCreate = lifecycleNoopCb;
defaultsPrototype.afterCreateCollection = lifecycleNoop;
defaultsPrototype.afterCreateInstance = lifecycleNoop;
defaultsPrototype.afterDestroy = lifecycleNoopCb;
defaultsPrototype.afterEject = lifecycleNoop;
defaultsPrototype.afterInject = lifecycleNoop;
defaultsPrototype.afterReap = lifecycleNoop;
defaultsPrototype.afterUpdate = lifecycleNoopCb;
defaultsPrototype.afterValidate = lifecycleNoopCb;
defaultsPrototype.allowSimpleWhere = true;
defaultsPrototype.basePath = '';
defaultsPrototype.beforeCreate = lifecycleNoopCb;
defaultsPrototype.beforeCreateCollection = lifecycleNoop;
defaultsPrototype.beforeCreateInstance = lifecycleNoop;
defaultsPrototype.beforeDestroy = lifecycleNoopCb;
defaultsPrototype.beforeEject = lifecycleNoop;
defaultsPrototype.beforeInject = lifecycleNoop;
defaultsPrototype.beforeReap = lifecycleNoop;
defaultsPrototype.beforeUpdate = lifecycleNoopCb;
defaultsPrototype.beforeValidate = lifecycleNoopCb;
defaultsPrototype.bypassCache = false;
defaultsPrototype.cacheResponse = !!_utils['default'].w;
defaultsPrototype.clearEmptyQueries = true;
defaultsPrototype.computed = {};
defaultsPrototype.defaultAdapter = 'http';
defaultsPrototype.debug = false;
defaultsPrototype.defaultValues = {};
defaultsPrototype.eagerEject = false;
// TODO: Implement eagerInject in DS#create
defaultsPrototype.eagerInject = false;
defaultsPrototype.endpoint = '';
defaultsPrototype.error = console ? function (a, b, c) {
return console[typeof console.error === 'function' ? 'error' : 'log'](a, b, c);
} : false;
defaultsPrototype.fallbackAdapters = ['http'];
defaultsPrototype.findStrictCache = false;
defaultsPrototype.idAttribute = 'id';
defaultsPrototype.ignoredChanges = [/\$/];
defaultsPrototype.instanceEvents = !!_utils['default'].w;
defaultsPrototype.keepChangeHistory = false;
defaultsPrototype.linkRelations = true;
defaultsPrototype.log = console ? function (a, b, c, d, e) {
return console[typeof console.info === 'function' ? 'info' : 'log'](a, b, c, d, e);
} : false;
defaultsPrototype.logFn = function (a, b, c, d) {
var _this = this;
if (_this.debug && _this.log && typeof _this.log === 'function') {
_this.log(_this.name || null, a || null, b || null, c || null, d || null);
}
};
defaultsPrototype.maxAge = false;
defaultsPrototype.methods = {};
defaultsPrototype.notify = !!_utils['default'].w;
defaultsPrototype.omit = [];
defaultsPrototype.onConflict = 'merge';
defaultsPrototype.reapAction = !!_utils['default'].w ? 'inject' : 'none';
defaultsPrototype.reapInterval = !!_utils['default'].w ? 30000 : false;
defaultsPrototype.relationsEnumerable = false;
defaultsPrototype.resetHistoryOnInject = true;
defaultsPrototype.returnMeta = false;
defaultsPrototype.strategy = 'single';
defaultsPrototype.upsert = !!_utils['default'].w;
defaultsPrototype.useClass = true;
defaultsPrototype.useFilter = false;
defaultsPrototype.validate = lifecycleNoopCb;
defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) {
var filtered = collection;
var where = null;
var reserved = {
skip: '',
offset: '',
where: '',
limit: '',
orderBy: '',
sort: ''
};
params = params || {};
options = options || {};
if (_utils['default']._o(params.where)) {
where = params.where;
} else {
where = {};
}
if (options.allowSimpleWhere) {
_utils['default'].forOwn(params, function (value, key) {
if (!(key in reserved) && !(key in where)) {
where[key] = {
'==': value
};
}
});
}
if (_utils['default'].isEmpty(where)) {
where = null;
}
if (where) {
filtered = _utils['default'].filter(filtered, function (attrs) {
var first = true;
var keep = true;
_utils['default'].forOwn(where, function (clause, field) {
if (!_utils['default']._o(clause)) {
clause = {
'==': clause
};
}
_utils['default'].forOwn(clause, function (term, op) {
var expr = undefined;
var isOr = op[0] === '|';
var val = _utils['default'].get(attrs, field);
op = isOr ? op.substr(1) : op;
if (op === '==') {
expr = val == term;
} else if (op === '===') {
expr = val === term;
} else if (op === '!=') {
expr = val != term;
} else if (op === '!==') {
expr = val !== term;
} else if (op === '>') {
expr = val > term;
} else if (op === '>=') {
expr = val >= term;
} else if (op === '<') {
expr = val < term;
} else if (op === '<=') {
expr = val <= term;
} else if (op === 'isectEmpty') {
expr = !_utils['default'].intersection(val || [], term || []).length;
} else if (op === 'isectNotEmpty') {
expr = _utils['default'].intersection(val || [], term || []).length;
} else if (op === 'in') {
if (_utils['default']._s(term)) {
expr = term.indexOf(val) !== -1;
} else {
expr = _utils['default'].contains(term, val);
}
} else if (op === 'notIn') {
if (_utils['default']._s(term)) {
expr = term.indexOf(val) === -1;
} else {
expr = !_utils['default'].contains(term, val);
}
} else if (op === 'contains') {
if (_utils['default']._s(val)) {
expr = val.indexOf(term) !== -1;
} else {
expr = _utils['default'].contains(val, term);
}
} else if (op === 'notContains') {
if (_utils['default']._s(val)) {
expr = val.indexOf(term) === -1;
} else {
expr = !_utils['default'].contains(val, term);
}
}
if (expr !== undefined) {
keep = first ? expr : isOr ? keep || expr : keep && expr;
}
first = false;
});
});
return keep;
});
}
var orderBy = null;
if (_utils['default']._s(params.orderBy)) {
orderBy = [[params.orderBy, 'ASC']];
} else if (_utils['default']._a(params.orderBy)) {
orderBy = params.orderBy;
}
if (!orderBy && _utils['default']._s(params.sort)) {
orderBy = [[params.sort, 'ASC']];
} else if (!orderBy && _utils['default']._a(params.sort)) {
orderBy = params.sort;
}
// Apply 'orderBy'
if (orderBy) {
(function () {
var index = 0;
_utils['default'].forEach(orderBy, function (def, i) {
if (_utils['default']._s(def)) {
orderBy[i] = [def, 'ASC'];
} else if (!_utils['default']._a(def)) {
throw new _errors['default'].IA('DS.filter("' + resourceName + '"[, params][, options]): ' + _utils['default'].toJson(def) + ': Must be a string or an array!', {
params: {
'orderBy[i]': {
actual: typeof def,
expected: 'string|array'
}
}
});
}
});
filtered = _utils['default'].sort(filtered, function (a, b) {
return compare(orderBy, index, a, b);
});
})();
}
var limit = _utils['default']._n(params.limit) ? params.limit : null;
var skip = null;
if (_utils['default']._n(params.skip)) {
skip = params.skip;
} else if (_utils['default']._n(params.offset)) {
skip = params.offset;
}
// Apply 'limit' and 'skip'
if (limit && skip) {
filtered = _utils['default'].slice(filtered, skip, Math.min(filtered.length, skip + limit));
} else if (_utils['default']._n(limit)) {
filtered = _utils['default'].slice(filtered, 0, Math.min(filtered.length, limit));
} else if (_utils['default']._n(skip)) {
if (skip < filtered.length) {
filtered = _utils['default'].slice(filtered, skip);
} else {
filtered = [];
}
}
if (filtered === collection) {
return filtered.slice();
} else {
return filtered;
}
};
var DS = (function () {
function DS(options) {
_classCallCheck(this, DS);
var _this = this;
options = options || {};
_this.store = {};
_this.definitions = {};
_this.adapters = {};
_this.defaults = new Defaults();
_this.observe = _utils['default'].observe;
_utils['default'].forOwn(options, function (v, k) {
if (k === 'omit') {
_this.defaults.omit = v.concat(Defaults.prototype.omit);
} else {
_this.defaults[k] = v;
}
});
var P = _utils['default'].Promise;
if (P && !P.prototype.spread) {
P.prototype.spread = function (cb) {
return this.then(function (arr) {
return cb.apply(this, arr);
});
};
}
_utils['default'].Events(_this);
}
_createClass(DS, [{
key: 'getAdapterName',
value: function getAdapterName(options) {
var errorIfNotExist = false;
options = options || {};
if (_utils['default']._s(options)) {
errorIfNotExist = true;
options = {
adapter: options
};
}
if (this.adapters[options.adapter]) {
return options.adapter;
} else if (errorIfNotExist) {
throw new Error(options.adapter + ' is not a registered adapter!');
} else {
return options.defaultAdapter;
}
}
}, {
key: 'getAdapter',
value: function getAdapter(options) {
options = options || {};
return this.adapters[this.getAdapterName(options)];
}
}, {
key: 'registerAdapter',
value: function registerAdapter(name, Adapter, options) {
var _this = this;
options = options || {};
if (_utils['default'].isFunction(Adapter)) {
_this.adapters[name] = new Adapter(options);
} else {
_this.adapters[name] = Adapter;
}
if (options['default']) {
_this.defaults.defaultAdapter = name;
}
}
}, {
key: 'is',
value: function is(resourceName, instance) {
var definition = this.definitions[resourceName];
if (!definition) {
throw new _errors['default'].NER(resourceName);
}
return instance instanceof definition[definition['class']];
}
}, {
key: 'clear',
value: function clear() {
var _this2 = this;
var ejected = {};
_utils['default'].forOwn(this.definitions, function (definition) {
var name = definition.name;
ejected[name] = definition.ejectAll();
_this2.store[name].completedQueries = {};
_this2.store[name].queryData = {};
});
return ejected;
}
}]);
return DS;
})();
var dsPrototype = DS.prototype;
dsPrototype.getAdapterName.shorthand = false;
dsPrototype.getAdapter.shorthand = false;
dsPrototype.registerAdapter.shorthand = false;
dsPrototype.errors = _errors['default'];
dsPrototype.utils = _utils['default'];
function addMethods(target, obj) {
_utils['default'].forOwn(obj, function (v, k) {
target[k] = v;
target[k].before = function (fn) {
var orig = target[k];
target[k] = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return orig.apply(this, fn.apply(this, args) || args);
};
};
});
}
addMethods(dsPrototype, _sync_methodsIndex['default']);
addMethods(dsPrototype, _async_methodsIndex['default']);
exports['default'] = DS;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/* jshint eqeqeq:false */
/**
* Mix of ES6 and CommonJS module imports because the interop of Babel + Webpack + ES6 modules + CommonJS isn't very good.
*/
var _errors = __webpack_require__(3);
var BinaryHeap = __webpack_require__(7);
var forEach = __webpack_require__(8);
var slice = __webpack_require__(9);
var forOwn = __webpack_require__(13);
var contains = __webpack_require__(10);
var deepMixIn = __webpack_require__(14);
var pascalCase = __webpack_require__(19);
var remove = __webpack_require__(11);
var pick = __webpack_require__(15);
var _keys = __webpack_require__(16);
var sort = __webpack_require__(12);
var upperCase = __webpack_require__(20);
var get = __webpack_require__(17);
var set = __webpack_require__(18);
var observe = __webpack_require__(6);
var w = undefined;
var objectProto = Object.prototype;
var toString = objectProto.toString;
var P = undefined;
/**
* Attempt to detect the global Promise constructor.
* JSData will still work without one, as long you do something like this:
*
* var JSData = require('js-data');
* JSData.DSUtils.Promise = MyPromiseLib;
*/
try {
P = Promise;
} catch (err) {
console.error('js-data requires a global Promise constructor!');
}
var isArray = Array.isArray || function isArray(value) {
return toString.call(value) == '[object Array]' || false;
};
var isRegExp = function isRegExp(value) {
return toString.call(value) == '[object RegExp]' || false;
};
// adapted from lodash.isString
var isString = function isString(value) {
return typeof value == 'string' || value && typeof value == 'object' && toString.call(value) == '[object String]' || false;
};
var isObject = function isObject(value) {
return toString.call(value) == '[object Object]' || false;
};
// adapted from lodash.isDate
var isDate = function isDate(value) {
return value && typeof value == 'object' && toString.call(value) == '[object Date]' || false;
};
// adapted from lodash.isNumber
var isNumber = function isNumber(value) {
var type = typeof value;
return type == 'number' || value && type == 'object' && toString.call(value) == '[object Number]' || false;
};
// adapted from lodash.isFunction
var isFunction = function isFunction(value) {
return typeof value == 'function' || value && toString.call(value) === '[object Function]' || false;
};
// shorthand argument checking functions, using these shaves 1.18 kb off of the minified build
var isStringOrNumber = function isStringOrNumber(value) {
return isString(value) || isNumber(value);
};
var isStringOrNumberErr = function isStringOrNumberErr(field) {
return new _errors['default'].IA('"' + field + '" must be a string or a number!');
};
var isObjectErr = function isObjectErr(field) {
return new _errors['default'].IA('"' + field + '" must be an object!');
};
var isArrayErr = function isArrayErr(field) {
return new _errors['default'].IA('"' + field + '" must be an array!');
};
// adapted from mout.isEmpty
var isEmpty = function isEmpty(val) {
if (val == null) {
// jshint ignore:line
// typeof null == 'object' so we check it first
return true;
} else if (typeof val === 'string' || isArray(val)) {
return !val.length;
} else if (typeof val === 'object') {
var result = true;
forOwn(val, function () {
result = false;
return false; // break loop
});
return result;
} else {
return true;
}
};
// Find the intersection between two arrays
var intersection = function intersection(array1, array2) {
if (!array1 || !array2) {
return [];
}
var result = [];
var item = undefined;
for (var i = 0, _length = array1.length; i < _length; i++) {
item = array1[i];
if (contains(result, item)) {
continue;
}
if (contains(array2, item)) {
result.push(item);
}
}
return result;
};
var filter = function filter(array, cb, thisObj) {
var results = [];
forEach(array, function (value, key, arr) {
if (cb(value, key, arr)) {
results.push(value);
}
}, thisObj);
return results;
};
/**
* Attempt to detect whether we are in the browser.
*/
try {
w = window;
w = {};
} catch (e) {
w = null;
}
/**
* Event mixin. Usage:
*
* function handler() { ... }
* Events(myObject);
* myObject.on('foo', handler);
* myObject.emit('foo', 'some', 'data');
* myObject.off('foo', handler);
*/
function Events(target) {
var events = {};
target = target || this;
target.on = function (type, func, ctx) {
events[type] = events[type] || [];
events[type].push({
f: func,
c: ctx
});
};
target.off = function (type, func) {
var listeners = events[type];
if (!listeners) {
events = {};
} else if (func) {
for (var i = 0; i < listeners.length; i++) {
if (listeners[i].f === func) {
listeners.splice(i, 1);
break;
}
}
} else {
listeners.splice(0, listeners.length);
}
};
target.emit = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var listeners = events[args.shift()] || [];
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].f.apply(listeners[i].c, args);
}
}
};
}
/**
* Lifecycle hooks that should support promises.
*/
var toPromisify = ['beforeValidate', 'validate', 'afterValidate', 'beforeCreate', 'afterCreate', 'beforeUpdate', 'afterUpdate', 'beforeDestroy', 'afterDestroy'];
/**
* Return whether "prop" is in the blacklist.
*/
var isBlacklisted = observe.isBlacklisted;
// adapted from angular.copy
var copy = function copy(source, destination, stackSource, stackDest, blacklist) {
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, [], stackSource, stackDest, blacklist);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isRegExp(source)) {
destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
destination.lastIndex = source.lastIndex;
} else if (isObject(source)) {
destination = copy(source, Object.create(Object.getPrototypeOf(source)), stackSource, stackDest, blacklist);
}
}
} else {
if (source === destination) {
throw new Error('Cannot copy! Source and destination are identical.');
}
stackSource = stackSource || [];
stackDest = stackDest || [];
if (isObject(source)) {
var index = stackSource.indexOf(source);
if (index !== -1) {
return stackDest[index];
}
stackSource.push(source);
stackDest.push(destination);
}
var result = undefined;
if (isArray(source)) {
var i = undefined;
destination.length = 0;
for (i = 0; i < source.length; i++) {
result = copy(source[i], null, stackSource, stackDest, blacklist);
if (isObject(source[i])) {
stackSource.push(source[i]);
stackDest.push(result);
}
destination.push(result);
}
} else {
if (isArray(destination)) {
destination.length = 0;
} else {
forEach(destination, function (value, key) {
delete destination[key];
});
}
for (var key in source) {
if (source.hasOwnProperty(key)) {
if (isBlacklisted(key, blacklist)) {
continue;
}
result = copy(source[key], null, stackSource, stackDest, blacklist);
if (isObject(source[key])) {
stackSource.push(source[key]);
stackDest.push(result);
}
destination[key] = result;
}
}
}
}
return destination;
};
// adapted from angular.equals
var equals = function equals(_x, _x2) {
var _again = true;
_function: while (_again) {
var o1 = _x,
o2 = _x2;
t1 = t2 = length = key = keySet = undefined;
_again = false;
if (o1 === o2) {
return true;
}
if (o1 === null || o2 === null) {
return false;
}
if (o1 !== o1 && o2 !== o2) {
return true;
} // NaN === NaN
var t1 = typeof o1,
t2 = typeof o2,
length,
key,
keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if (!isArray(o2)) {
return false;
}
if ((length = o1.length) == o2.length) {
// jshint ignore:line
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) {
return false;
}
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) {
return false;
}
_x = o1.getTime();
_x2 = o2.getTime();
_again = true;
continue _function;
} else if (isRegExp(o1) && isRegExp(o2)) {
return o1.toString() == o2.toString();
} else {
if (isArray(o2)) {
return false;
}
keySet = {};
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) {
continue;
}
if (!equals(o1[key], o2[key])) {
return false;
}
keySet[key] = true;
}
for (key in o2) {
if (!keySet.hasOwnProperty(key) && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) {
return false;
}
}
return true;
}
}
}
return false;
}
};
/**
* Given either an instance or the primary key of an instance, return the primary key.
*/
var resolveId = function resolveId(definition, idOrInstance) {
if (isString(idOrInstance) || isNumber(idOrInstance)) {
return idOrInstance;
} else if (idOrInstance && definition) {
return idOrInstance[definition.idAttribute] || idOrInstance;
} else {
return idOrInstance;
}
};
/**
* Given either an instance or the primary key of an instance, return the instance.
*/
var resolveItem = function resolveItem(resource, idOrInstance) {
if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) {
return resource.index[idOrInstance] || idOrInstance;
} else {
return idOrInstance;
}
};
var isValidString = function isValidString(val) {
return val != null && val !== ''; // jshint ignore:line
};
var join = function join(items, separator) {
separator = separator || '';
return filter(items, isValidString).join(separator);
};
var makePath = function makePath() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var result = join(args, '/');
return result.replace(/([^:\/]|^)\/{2,}/g, '$1/');
};
exports['default'] = {
Promise: P,
/**
* Method to wrap an "options" object so that it will inherit from
* some parent object, such as a resource definition.
*/
_: function _(parent, options) {
var _this = this;
parent = parent || {};
options = options || {};
if (options && options.constructor === parent.constructor) {
return options;
} else if (!isObject(options)) {
throw new _errors['default'].IA('"options" must be an object!');
}
forEach(toPromisify, function (name) {
if (typeof options[name] === 'function' && options[name].toString().indexOf('for (var _len = arg') === -1) {
options[name] = _this.promisify(options[name]);
}
});
// Dynamic constructor function
var O = function Options(attrs) {
var self = this;
forOwn(attrs, function (value, key) {
self[key] = value;
});
};
// Inherit from some parent object
O.prototype = parent;
// Give us a way to get the original options back.
O.prototype.orig = function () {
var orig = {};
forOwn(this, function (value, key) {
orig[key] = value;
});
return orig;
};
return new O(options);
},
_n: isNumber,
_s: isString,
_sn: isStringOrNumber,
_snErr: isStringOrNumberErr,
_o: isObject,
_oErr: isObjectErr,
_a: isArray,
_aErr: isArrayErr,
compute: function compute(fn, field) {
var _this = this;
var args = [];
forEach(fn.deps, function (dep) {
args.push(get(_this, dep));
});
// compute property
set(_this, field, fn[fn.length - 1].apply(_this, args));
},
contains: contains,
copy: copy,
deepMixIn: deepMixIn,
diffObjectFromOldObject: observe.diffObjectFromOldObject,
BinaryHeap: BinaryHeap,
equals: equals,
Events: Events,
filter: filter,
fillIn: function fillIn(target, obj) {
forOwn(obj, function (v, k) {
if (!(k in target)) {
target[k] = v;
}
});
return target;
},
forEach: forEach,
forOwn: forOwn,
fromJson: function fromJson(json) {
return isString(json) ? JSON.parse(json) : json;
},
get: get,
intersection: intersection,
isArray: isArray,
isBlacklisted: isBlacklisted,
isEmpty: isEmpty,
isFunction: isFunction,
isObject: isObject,
isNumber: isNumber,
isString: isString,
keys: _keys,
makePath: makePath,
observe: observe,
omit: function omit(obj, bl) {
var toRemove = [];
forOwn(obj, function (v, k) {
if (isBlacklisted(k, bl)) {
toRemove.push(k);
}
});
forEach(toRemove, function (k) {
delete obj[k];
});
return obj;
},
pascalCase: pascalCase,
pick: pick,
// Turn the given node-style callback function into one that can return a promise.
promisify: function promisify(fn, target) {
var _this = this;
if (!fn) {
return;
} else if (typeof fn !== 'function') {
throw new Error('Can only promisify functions!');
}
return function () {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return new _this.Promise(function (resolve, reject) {
args.push(function (err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
try {
var promise = fn.apply(target || this, args);
if (promise && promise.then) {
promise.then(resolve, reject);
}
} catch (err) {
reject(err);
}
});
};
},
remove: remove,
set: set,
slice: slice,
sort: sort,
toJson: JSON.stringify,
updateTimestamp: function updateTimestamp(timestamp) {
var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime();
if (timestamp && newTimestamp <= timestamp) {
return timestamp + 1;
} else {
return newTimestamp;
}
},
upperCase: upperCase,
// Return a copy of "object" with cycles removed.
removeCircular: function removeCircular(object) {
return (function rmCirc(value, ctx) {
var i = undefined;
var nu = undefined;
if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) {
// check if current object points back to itself
var cur = ctx.cur;
var parent = ctx.ctx;
while (parent) {
if (parent.cur === cur) {
return undefined;
}
parent = parent.ctx;
}
if (isArray(value)) {
nu = [];
for (i = 0; i < value.length; i += 1) {
nu[i] = rmCirc(value[i], { ctx: ctx, cur: value[i] });
}
} else {
nu = {};
forOwn(value, function (v, k) {
nu[k] = rmCirc(value[k], { ctx: ctx, cur: value[k] });
});
}
return nu;
}
return value;
})(object, { ctx: null, cur: object });
},
resolveItem: resolveItem,
resolveId: resolveId,
respond: function respond(response, meta, options) {
if (options.returnMeta === 'array') {
return [response, meta];
} else if (options.returnMeta === 'object') {
return { response: response, meta: meta };
} else {
return response;
}
},
w: w,
// This is where the magic of relations happens.
applyRelationGettersToTarget: function applyRelationGettersToTarget(store, definition, target) {
this.forEach(definition.relationList, function (def) {
var relationName = def.relation;
var localField = def.localField;
var localKey = def.localKey;
var foreignKey = def.foreignKey;
var localKeys = def.localKeys;
var enumerable = typeof def.enumerable === 'boolean' ? def.enumerable : !!definition.relationsEnumerable;
if (typeof def.link === 'boolean' ? def.link : !!definition.linkRelations) {
delete target[localField];
var prop = {
enumerable: enumerable,
set: function set() {}
};
if (def.type === 'belongsTo') {
prop.get = function () {
return get(this, localKey) ? definition.getResource(relationName).get(get(this, localKey)) : undefined;
};
} else if (def.type === 'hasMany') {
prop.get = function () {
var params = {};
if (foreignKey) {
params[foreignKey] = this[definition.idAttribute];
return definition.getResource(relationName).defaultFilter.call(store, store.store[relationName].collection, relationName, params, { allowSimpleWhere: true });
} else if (localKeys) {
var keys = get(this, localKeys) || [];
return definition.getResource(relationName).getAll(isArray(keys) ? keys : _keys(keys));
}
return undefined;
};
} else if (def.type === 'hasOne') {
if (localKey) {
prop.get = function () {
return get(this, localKey) ? definition.getResource(relationName).get(get(this, localKey)) : undefined;
};
} else {
prop.get = function () {
var params = {};
params[foreignKey] = this[definition.idAttribute];
var items = params[foreignKey] ? definition.getResource(relationName).defaultFilter.call(store, store.store[relationName].collection, relationName, params, { allowSimpleWhere: true }) : [];
if (items.length) {
return items[0];
}
return undefined;
};
}
}
if (def.get) {
(function () {
var orig = prop.get;
prop.get = function () {
var _this2 = this;
return def.get(definition, def, this, function () {
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return orig.apply(_this2, args);
});
};
})();
}
Object.defineProperty(target, def.localField, prop);
}
});
}
};
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
/**
* Thrown during a method call when an argument passed into the method is invalid.
*/
var IllegalArgumentError = (function (_Error) {
_inherits(IllegalArgumentError, _Error);
function IllegalArgumentError(message) {
_classCallCheck(this, IllegalArgumentError);
_get(Object.getPrototypeOf(IllegalArgumentError.prototype), 'constructor', this).call(this);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
}
this.type = this.constructor.name;
this.message = message;
}
return IllegalArgumentError;
})(Error)
/**
* Thrown when an invariant is violated or unrecoverable error is encountered during execution.
*/
;
var RuntimeError = (function (_Error2) {
_inherits(RuntimeError, _Error2);
function RuntimeError(message) {
_classCallCheck(this, RuntimeError);
_get(Object.getPrototypeOf(RuntimeError.prototype), 'constructor', this).call(this);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
}
this.type = this.constructor.name;
this.message = message;
}
return RuntimeError;
})(Error)
/**
* Thrown when attempting to access or work with a non-existent resource.
*/
;
var NonexistentResourceError = (function (_Error3) {
_inherits(NonexistentResourceError, _Error3);
function NonexistentResourceError(resourceName) {
_classCallCheck(this, NonexistentResourceError);
_get(Object.getPrototypeOf(NonexistentResourceError.prototype), 'constructor', this).call(this);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
}
this.type = this.constructor.name;
this.message = resourceName + ' is not a registered resource!';
}
return NonexistentResourceError;
})(Error);
exports['default'] = {
IllegalArgumentError: IllegalArgumentError,
IA: IllegalArgumentError,
RuntimeError: RuntimeError,
R: RuntimeError,
NonexistentResourceError: NonexistentResourceError,
NER: NonexistentResourceError
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
var _utils = __webpack_require__(2);
var _errors = __webpack_require__(3);
var NER = _errors['default'].NER;
var IA = _errors['default'].IA;
var R = _errors['default'].R;
var fakeId = 'DS_' + new Date().getTime();
function diffIsEmpty(diff) {
return !(_utils['default'].isEmpty(diff.added) && _utils['default'].isEmpty(diff.removed) && _utils['default'].isEmpty(diff.changed));
}
function check(fnName, resourceName, id, options) {
var _this = this;
var definition = _this.definitions[resourceName];
options = options || {};
id = _utils['default'].resolveId(definition, id);
if (!definition) {
throw new NER(resourceName);
} else if (!_utils['default']._sn(id)) {
throw _utils['default']._snErr('id');
}
id = id === fakeId ? undefined : id;
options = _utils['default']._(definition, options);
return { _this: _this, definition: definition, _resourceName: resourceName, _id: id, _options: options };
}
exports['default'] = {
// Return the changes for the given item, if any.
//
// @param resourceName The name of the type of resource of the item whose changes are to be returned.
// @param id The primary key of the item whose changes are to be returned.
// @param options Optional configuration.
// @param options.ignoredChanges Array of strings or regular expressions of fields, the changes of which are to be ignored.
// @returns The changes of the given item, if any.
changes: function changes(resourceName, id, options) {
var _check$call = check.call(this, 'changes', resourceName, id, options);
var _this = _check$call._this;
var definition = _check$call.definition;
var _resourceName = _check$call._resourceName;
var _id = _check$call._id;
var _options = _check$call._options;
var item = definition.get(_id);
if (item) {
var _ret = (function () {
if (_utils['default'].w) {
// force observation handler to be fired for item if there are changes and `Object.observe` is not available
_this.store[_resourceName].observers[_id].deliver();
}
var ignoredChanges = _options.ignoredChanges || [];
// add linked relations to list of ignored changes
_utils['default'].forEach(definition.relationFields, function (field) {
if (!_utils['default'].contains(ignoredChanges, field)) {
ignoredChanges.push(field);
}
});
// calculate changes
var diff = _utils['default'].diffObjectFromOldObject(item, _this.store[_resourceName].previousAttributes[_id], _utils['default'].equals, ignoredChanges);
// remove functions from diff
_utils['default'].forOwn(diff, function (changeset, name) {
var toKeep = [];
_utils['default'].forOwn(changeset, function (value, field) {
if (!_utils['default'].isFunction(value)) {
toKeep.push(field);
}
});
diff[name] = _utils['default'].pick(diff[name], toKeep);
});
// definitely ignore changes to linked relations
_utils['default'].forEach(definition.relationFields, function (field) {
delete diff.added[field];
delete diff.removed[field];
delete diff.changed[field];
});
return {
v: diff
};
})();
if (typeof _ret === 'object') return _ret.v;
}
},
// Return the change history of the given item, if any.
//
// @param resourceName The name of the type of resource of the item whose change history is to be returned.
// @param id The primary key of the item whose change history is to be returned.
// @returns The change history of the given item, if any.
changeHistory: function changeHistory(resourceName, id) {
var _check$call2 = check.call(this, 'changeHistory', resourceName, id || fakeId);
var _this = _check$call2._this;
var definition = _check$call2.definition;
var _resourceName = _check$call2._resourceName;
var _id = _check$call2._id;
var resource = _this.store[_resourceName];
if (!definition.keepChangeHistory) {
definition.errorFn('changeHistory is disabled for this resource!');
} else {
if (_resourceName) {
var item = definition.get(_id);
if (item) {
return resource.changeHistories[_id];
}
} else {
return resource.changeHistory;
}
}
},
// Re-compute the computed properties of the given item.
//
// @param resourceName The name of the type of resource of the item whose computed properties are to be re-computed.
// @param instance The instance whose computed properties are to be re-computed.
// @returns The item whose computed properties were re-computed.
compute: function compute(resourceName, instance) {
var _this = this;
var definition = _this.definitions[resourceName];
instance = _utils['default'].resolveItem(_this.store[resourceName], instance);
if (!definition) {
throw new NER(resourceName);
} else if (!instance) {
throw new R('Item not in the store!');
} else if (!_utils['default']._o(instance) && !_utils['default']._sn(instance)) {
throw new IA('"instance" must be an object, string or number!');
}
// re-compute all computed properties
_utils['default'].forOwn(definition.computed, function (fn, field) {
_utils['default'].compute.call(instance, fn, field);
});
return instance;
},
// Factory function to create an instance of the specified Resource.
//
// @param resourceName The name of the type of resource of which to create an instance.
// @param attrs Hash of properties with which to initialize the instance.
// @param options Optional configuration.
// @param options.defaults Default values with which to initialize the instance.
// @returns The new instance.
createInstance: function createInstance(resourceName, attrs, options) {
var definition = this.definitions[resourceName];
var item = undefined;
attrs = attrs || {};
if (!definition) {
throw new NER(resourceName);
} else if (attrs && !_utils['default'].isObject(attrs)) {
throw new IA('"attrs" must be an object!');
}
options = _utils['default']._(definition, options);
// lifecycle
options.beforeCreateInstance(options, attrs);
// grab instance constructor function from Resource definition
var Constructor = definition[definition['class']];
// create instance
item = new Constructor();
// add default values
if (options.defaultValues) {
_utils['default'].deepMixIn(item, options.defaultValues);
}
_utils['default'].deepMixIn(item, attrs);
// compute computed properties
if (definition.computed) {
definition.compute(item);
}
// lifecycle
options.afterCreateInstance(options, item);
return item;
},
// Create a new collection of the specified Resource.
//
// @param resourceName The name of the type of resource of which to create a collection
// @param arr Possibly empty array of data from which to create the collection.
// @param params The criteria by which to filter items. Will be passed to `DS#findAll` if `fetch` is called. See http://www.js-data.io/docs/query-syntax
// @param options Optional configuration.
// @param options.notify Whether to call the beforeCreateCollection and afterCreateCollection lifecycle hooks..
// @returns The new collection.
createCollection: function createCollection(resourceName, arr, params, options) {
var _this = this;
var definition = _this.definitions[resourceName];
arr = arr || [];
params = params || {};
if (!definition) {
throw new NER(resourceName);
} else if (arr && !_utils['default'].isArray(arr)) {
throw new IA('"arr" must be an array!');
}
options = _utils['default']._(definition, options);
// lifecycle
options.beforeCreateCollection(options, arr);
// define the API for this collection
Object.defineProperties(arr, {
// Call DS#findAll with the params of this collection, filling the collection with the results.
fetch: {
value: function value(params, options) {
var __this = this;
__this.params = params || __this.params;
return definition.findAll(__this.params, options).then(function (data) {
if (data === __this) {
return __this;
}
data.unshift(__this.length);
data.unshift(0);
__this.splice.apply(__this, data);
data.shift();
data.shift();
if (data.$$injected) {
_this.store[resourceName].queryData[_utils['default'].toJson(__this.params)] = __this;
__this.$$injected = true;
}
return __this;
});
}
},
// params for this collection. See http://www.js-data.io/docs/query-syntax
params: {
value: params,
writable: true
},
// name of the resource type of this collection
resourceName: {
value: resourceName
}
});
// lifecycle
options.afterCreateCollection(options, arr);
return arr;
},
defineResource: __webpack_require__(27),
digest: function digest() {
this.observe.Platform.performMicrotaskCheckpoint();
},
eject: __webpack_require__(28),
ejectAll: __webpack_require__(29),
filter: __webpack_require__(30),
// Return the item with the given primary key if its in the store.
//
// @param resourceName The name of the type of resource of the item to retrieve.
// @param id The primary key of the item to retrieve.
// @returns The item with the given primary key if it's in the store.
///
get: function get(resourceName, id) {
var _check$call3 = check.call(this, 'get', resourceName, id);
// return the item if it exists
var _this = _check$call3._this;
var _resourceName = _check$call3._resourceName;
var _id = _check$call3._id;
return _this.store[_resourceName].index[_id];
},
// Return the items in the store that have the given primary keys.
//
// @param resourceName The name of the type of resource of the items to retrieve.
// @param ids The primary keys of the items to retrieve.
// @returns The items with the given primary keys if they're in the store.
getAll: function getAll(resourceName, ids) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var collection = [];
if (!definition) {
throw new NER(resourceName);
} else if (ids && !_utils['default']._a(ids)) {
throw _utils['default']._aErr('ids');
}
if (_utils['default']._a(ids)) {
// return just the items with the given primary keys
var _length = ids.length;
for (var i = 0; i < _length; i++) {
if (resource.index[ids[i]]) {
collection.push(resource.index[ids[i]]);
}
}
} else {
// most efficient of retrieving ALL items from the store
collection = resource.collection.slice();
}
return collection;
},
// Return the whether the item with the given primary key has any changes.
//
// @param resourceName The name of the type of resource of the item.
// @param id The primary key of the item.
// @returns Whether the item with the given primary key has any changes.
hasChanges: function hasChanges(resourceName, id) {
var _check$call4 = check.call(this, 'hasChanges', resourceName, id);
var definition = _check$call4.definition;
var _id = _check$call4._id;
return definition.get(_id) ? diffIsEmpty(definition.changes(_id)) : false;
},
inject: __webpack_require__(31),
// Return the timestamp from the last time the item with the given primary key was changed.
//
// @param resourceName The name of the type of resource of the item.
// @param id The primary key of the item.
// @returns Timestamp from the last time the item was changed.
lastModified: function lastModified(resourceName, id) {
var _check$call5 = check.call(this, 'lastModified', resourceName, id || fakeId);
var _this = _check$call5._this;
var _resourceName = _check$call5._resourceName;
var _id = _check$call5._id;
var resource = _this.store[_resourceName];
if (_id) {
if (!(_id in resource.modified)) {
resource.modified[_id] = 0;
}
return resource.modified[_id];
}
return resource.collectionModified;
},
// Return the timestamp from the last time the item with the given primary key was saved via an adapter.
//
// @param resourceName The name of the type of resource of the item.
// @param id The primary key of the item.
// @returns Timestamp from the last time the item was saved.
lastSaved: function lastSaved(resourceName, id) {
var _check$call6 = check.call(this, 'lastSaved', resourceName, id || fakeId);
var _this = _check$call6._this;
var _resourceName = _check$call6._resourceName;
var _id = _check$call6._id;
var resource = _this.store[_resourceName];
if (!(_id in resource.saved)) {
resource.saved[_id] = 0;
}
return resource.saved[_id];
},
// Return the previous attributes of the item with the given primary key before it was changed.
//
// @param resourceName The name of the type of resource of the item.
// @param id The primary key of the item.
// @returns The previous attributes of the item
previous: function previous(resourceName, id) {
var _check$call7 = check.call(this, 'previous', resourceName, id);
var _this = _check$call7._this;
var _resourceName = _check$call7._resourceName;
var _id = _check$call7._id;
var resource = _this.store[_resourceName];
// return resource from cache
return resource.previousAttributes[_id] ? _utils['default'].copy(resource.previousAttributes[_id]) : undefined;
},
// Revert all attributes of the item with the given primary key to their previous values.
//
// @param resourceName The name of the type of resource of the item.
// @param id The primary key of the item.
// @returns The reverted item
revert: function revert(resourceName, id) {
var _check$call8 = check.call(this, 'revert', resourceName, id);
var _this = _check$call8._this;
var definition = _check$call8.definition;
var _resourceName = _check$call8._resourceName;
var _id = _check$call8._id;
return definition.inject(_this.previous(_resourceName, _id));
}
};
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
exports['default'] = {
create: __webpack_require__(32),
destroy: __webpack_require__(33),
destroyAll: __webpack_require__(34),
find: __webpack_require__(35),
findAll: __webpack_require__(36),
loadRelations: __webpack_require__(37),
reap: __webpack_require__(38),
refresh: function refresh(resourceName, id, options) {
var _this = this;
var DSUtils = _this.utils;
return new DSUtils.Promise(function (resolve, reject) {
var definition = _this.definitions[resourceName];
id = DSUtils.resolveId(_this.definitions[resourceName], id);
if (!definition) {
reject(new _this.errors.NER(resourceName));
} else if (!DSUtils._sn(id)) {
reject(DSUtils._snErr('id'));
} else {
options = DSUtils._(definition, options);
options.bypassCache = true;
resolve(_this.get(resourceName, id));
}
}).then(function (item) {
return item ? _this.find(resourceName, id, options) : item;
});
},
refreshAll: function refreshAll(resourceName, params, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
params = params || {};
return new DSUtils.Promise(function (resolve, reject) {
if (!definition) {
reject(new _this.errors.NER(resourceName));
} else if (!DSUtils._o(params)) {
reject(DSUtils._oErr('params'));
} else {
options = DSUtils._(definition, options);
options.bypassCache = true;
resolve(_this.filter(resourceName, params, options));
}
}).then(function (existing) {
options.bypassCache = true;
return _this.findAll(resourceName, params, options).then(function (found) {
DSUtils.forEach(existing, function (item) {
if (found.indexOf(item) === -1) {
definition.eject(item);
}
});
return found;
});
});
},
save: __webpack_require__(39),
update: __webpack_require__(40),
updateAll: __webpack_require__(41)
};
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/*
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// Modifications
// Copyright 2014-2015 Jason Dobry
//
// Summary of modifications:
// Fixed use of "delete" keyword for IE8 compatibility
// Exposed diffObjectFromOldObject on the exported object
// Added the "equals" argument to diffObjectFromOldObject to be used to check equality
// Added a way in diffObjectFromOldObject to ignore changes to certain properties
// Removed all code related to:
// - ArrayObserver
// - ArraySplice
// - PathObserver
// - CompoundObserver
// - Path
// - ObserverTransform
(function(global) {
var testingExposeCycleCount = global.testingExposeCycleCount;
// Detect and do basic sanity checking on Object/Array.observe.
function detectObjectObserve() {
if (typeof Object.observe !== 'function' ||
typeof Array.observe !== 'function') {
return false;
}
var records = [];
function callback(recs) {
records = recs;
}
var test = {};
var arr = [];
Object.observe(test, callback);
Array.observe(arr, callback);
test.id = 1;
test.id = 2;
delete test.id;
arr.push(1, 2);
arr.length = 0;
Object.deliverChangeRecords(callback);
if (records.length !== 5)
return false;
if (records[0].type != 'add' ||
records[1].type != 'update' ||
records[2].type != 'delete' ||
records[3].type != 'splice' ||
records[4].type != 'splice') {
return false;
}
Object.unobserve(test, callback);
Array.unobserve(arr, callback);
return true;
}
var hasObserve = detectObjectObserve();
var createObject = ('__proto__' in {}) ?
function(obj) { return obj; } :
function(obj) {
var proto = obj.__proto__;
if (!proto)
return obj;
var newObject = Object.create(proto);
Object.getOwnPropertyNames(obj).forEach(function(name) {
Object.defineProperty(newObject, name,
Object.getOwnPropertyDescriptor(obj, name));
});
return newObject;
};
var MAX_DIRTY_CHECK_CYCLES = 1000;
function dirtyCheck(observer) {
var cycles = 0;
while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) {
cycles++;
}
if (testingExposeCycleCount)
global.dirtyCheckCycleCount = cycles;
return cycles > 0;
}
function objectIsEmpty(object) {
for (var prop in object)
return false;
return true;
}
function diffIsEmpty(diff) {
return objectIsEmpty(diff.added) &&
objectIsEmpty(diff.removed) &&
objectIsEmpty(diff.changed);
}
function isBlacklisted(prop, bl) {
if (!bl || !bl.length) {
return false;
}
var matches;
for (var i = 0; i < bl.length; i++) {
if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) {
return matches = prop;
}
}
return !!matches;
}
function diffObjectFromOldObject(object, oldObject, equals, bl) {
var added = {};
var removed = {};
var changed = {};
for (var prop in oldObject) {
var newValue = object[prop];
if (isBlacklisted(prop, bl))
continue;
if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop]))
continue;
if (!(prop in object)) {
removed[prop] = undefined;
continue;
}
if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop])
changed[prop] = newValue;
}
for (var prop in object) {
if (prop in oldObject)
continue;
if (isBlacklisted(prop, bl))
continue;
added[prop] = object[prop];
}
if (Array.isArray(object) && object.length !== oldObject.length)
changed.length = object.length;
return {
added: added,
removed: removed,
changed: changed
};
}
var eomTasks = [];
function runEOMTasks() {
if (!eomTasks.length)
return false;
for (var i = 0; i < eomTasks.length; i++) {
eomTasks[i]();
}
eomTasks.length = 0;
return true;
}
var runEOM = hasObserve ? (function(){
return function(fn) {
return Promise.resolve().then(fn);
}
})() :
(function() {
return function(fn) {
eomTasks.push(fn);
};
})();
var observedObjectCache = [];
function newObservedObject() {
var observer;
var object;
var discardRecords = false;
var first = true;
function callback(records) {
if (observer && observer.state_ === OPENED && !discardRecords)
observer.check_(records);
}
return {
open: function(obs) {
if (observer)
throw Error('ObservedObject in use');
if (!first)
Object.deliverChangeRecords(callback);
observer = obs;
first = false;
},
observe: function(obj, arrayObserve) {
object = obj;
if (arrayObserve)
Array.observe(object, callback);
else
Object.observe(object, callback);
},
deliver: function(discard) {
discardRecords = discard;
Object.deliverChangeRecords(callback);
discardRecords = false;
},
close: function() {
observer = undefined;
Object.unobserve(object, callback);
observedObjectCache.push(this);
}
};
}
function getObservedObject(observer, object, arrayObserve) {
var dir = observedObjectCache.pop() || newObservedObject();
dir.open(observer);
dir.observe(object, arrayObserve);
return dir;
}
var UNOPENED = 0;
var OPENED = 1;
var CLOSED = 2;
var nextObserverId = 1;
function Observer() {
this.state_ = UNOPENED;
this.callback_ = undefined;
this.target_ = undefined; // TODO(rafaelw): Should be WeakRef
this.directObserver_ = undefined;
this.value_ = undefined;
this.id_ = nextObserverId++;
}
Observer.prototype = {
open: function(callback, target) {
if (this.state_ != UNOPENED)
throw Error('Observer has already been opened.');
addToAll(this);
this.callback_ = callback;
this.target_ = target;
this.connect_();
this.state_ = OPENED;
return this.value_;
},
close: function() {
if (this.state_ != OPENED)
return;
removeFromAll(this);
this.disconnect_();
this.value_ = undefined;
this.callback_ = undefined;
this.target_ = undefined;
this.state_ = CLOSED;
},
deliver: function() {
if (this.state_ != OPENED)
return;
dirtyCheck(this);
},
report_: function(changes) {
try {
this.callback_.apply(this.target_, changes);
} catch (ex) {
Observer._errorThrownDuringCallback = true;
console.error('Exception caught during observer callback: ' +
(ex.stack || ex));
}
},
discardChanges: function() {
this.check_(undefined, true);
return this.value_;
}
}
var collectObservers = !hasObserve;
var allObservers;
Observer._allObserversCount = 0;
if (collectObservers) {
allObservers = [];
}
function addToAll(observer) {
Observer._allObserversCount++;
if (!collectObservers)
return;
allObservers.push(observer);
}
function removeFromAll(observer) {
Observer._allObserversCount--;
}
var runningMicrotaskCheckpoint = false;
global.Platform = global.Platform || {};
global.Platform.performMicrotaskCheckpoint = function() {
if (runningMicrotaskCheckpoint)
return;
if (!collectObservers)
return;
runningMicrotaskCheckpoint = true;
var cycles = 0;
var anyChanged, toCheck;
do {
cycles++;
toCheck = allObservers;
allObservers = [];
anyChanged = false;
for (var i = 0; i < toCheck.length; i++) {
var observer = toCheck[i];
if (observer.state_ != OPENED)
continue;
if (observer.check_())
anyChanged = true;
allObservers.push(observer);
}
if (runEOMTasks())
anyChanged = true;
} while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged);
if (testingExposeCycleCount)
global.dirtyCheckCycleCount = cycles;
runningMicrotaskCheckpoint = false;
};
if (collectObservers) {
global.Platform.clearObservers = function() {
allObservers = [];
};
}
function ObjectObserver(object) {
Observer.call(this);
this.value_ = object;
this.oldObject_ = undefined;
}
ObjectObserver.prototype = createObject({
__proto__: Observer.prototype,
arrayObserve: false,
connect_: function(callback, target) {
if (hasObserve) {
this.directObserver_ = getObservedObject(this, this.value_,
this.arrayObserve);
} else {
this.oldObject_ = this.copyObject(this.value_);
}
},
copyObject: function(object) {
var copy = Array.isArray(object) ? [] : {};
for (var prop in object) {
copy[prop] = object[prop];
};
if (Array.isArray(object))
copy.length = object.length;
return copy;
},
check_: function(changeRecords, skipChanges) {
var diff;
var oldValues;
if (hasObserve) {
if (!changeRecords)
return false;
oldValues = {};
diff = diffObjectFromChangeRecords(this.value_, changeRecords,
oldValues);
} else {
oldValues = this.oldObject_;
diff = diffObjectFromOldObject(this.value_, this.oldObject_);
}
if (diffIsEmpty(diff))
return false;
if (!hasObserve)
this.oldObject_ = this.copyObject(this.value_);
this.report_([
diff.added || {},
diff.removed || {},
diff.changed || {},
function(property) {
return oldValues[property];
}
]);
return true;
},
disconnect_: function() {
if (hasObserve) {
this.directObserver_.close();
this.directObserver_ = undefined;
} else {
this.oldObject_ = undefined;
}
},
deliver: function() {
if (this.state_ != OPENED)
return;
if (hasObserve)
this.directObserver_.deliver(false);
else
dirtyCheck(this);
},
discardChanges: function() {
if (this.directObserver_)
this.directObserver_.deliver(true);
else
this.oldObject_ = this.copyObject(this.value_);
return this.value_;
}
});
var observerSentinel = {};
var expectedRecordTypes = {
add: true,
update: true,
'delete': true
};
function diffObjectFromChangeRecords(object, changeRecords, oldValues) {
var added = {};
var removed = {};
for (var i = 0; i < changeRecords.length; i++) {
var record = changeRecords[i];
if (!expectedRecordTypes[record.type]) {
console.error('Unknown changeRecord type: ' + record.type);
console.error(record);
continue;
}
if (!(record.name in oldValues))
oldValues[record.name] = record.oldValue;
if (record.type == 'update')
continue;
if (record.type == 'add') {
if (record.name in removed)
delete removed[record.name];
else
added[record.name] = true;
continue;
}
// type = 'delete'
if (record.name in added) {
delete added[record.name];
delete oldValues[record.name];
} else {
removed[record.name] = true;
}
}
for (var prop in added)
added[prop] = object[prop];
for (var prop in removed)
removed[prop] = undefined;
var changed = {};
for (var prop in oldValues) {
if (prop in added || prop in removed)
continue;
var newValue = object[prop];
if (oldValues[prop] !== newValue)
changed[prop] = newValue;
}
return {
added: added,
removed: removed,
changed: changed
};
}
// Export the observe-js object for **Node.js**, with backwards-compatibility
// for the old `require()` API. Also ensure `exports` is not a DOM Element.
// If we're in the browser, export as a global object.
global.Observer = Observer;
global.isBlacklisted = isBlacklisted;
global.Observer.runEOM_ = runEOM;
global.Observer.observerSentinel_ = observerSentinel; // for testing.
global.Observer.hasObjectObserve = hasObserve;
global.diffObjectFromOldObject = diffObjectFromOldObject;
global.ObjectObserver = ObjectObserver;
})(exports);
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
/*!
* yabh
* @version 1.1.0 - Homepage <http://jmdobry.github.io/yabh/>
* @author Jason Dobry <jason.dobry@gmail.com>
* @copyright (c) 2015 Jason Dobry
* @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE>
*
* @overview Yet another Binary Heap.
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(true)
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("yabh", factory);
else if(typeof exports === 'object')
exports["BinaryHeap"] = factory();
else
root["BinaryHeap"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/**
* @method bubbleUp
* @param {array} heap The heap.
* @param {function} weightFunc The weight function.
* @param {number} n The index of the element to bubble up.
*/
function bubbleUp(heap, weightFunc, n) {
var element = heap[n];
var weight = weightFunc(element);
// When at 0, an element can not go up any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor((n + 1) / 2) - 1;
var _parent = heap[parentN];
// If the parent has a lesser weight, things are in order and we
// are done.
if (weight >= weightFunc(_parent)) {
break;
} else {
heap[parentN] = element;
heap[n] = _parent;
n = parentN;
}
}
}
/**
* @method bubbleDown
* @param {array} heap The heap.
* @param {function} weightFunc The weight function.
* @param {number} n The index of the element to sink down.
*/
var bubbleDown = function bubbleDown(heap, weightFunc, n) {
var length = heap.length;
var node = heap[n];
var nodeWeight = weightFunc(node);
while (true) {
var child2N = (n + 1) * 2,
child1N = child2N - 1;
var swap = null;
if (child1N < length) {
var child1 = heap[child1N],
child1Weight = weightFunc(child1);
// If the score is less than our node's, we need to swap.
if (child1Weight < nodeWeight) {
swap = child1N;
}
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = heap[child2N],
child2Weight = weightFunc(child2);
if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) {
swap = child2N;
}
}
if (swap === null) {
break;
} else {
heap[n] = heap[swap];
heap[swap] = node;
n = swap;
}
}
};
function BinaryHeap(weightFunc, compareFunc) {
if (!weightFunc) {
weightFunc = function (x) {
return x;
};
}
if (!compareFunc) {
compareFunc = function (x, y) {
return x === y;
};
}
if (typeof weightFunc !== 'function') {
throw new Error('BinaryHeap([weightFunc][, compareFunc]): "weightFunc" must be a function!');
}
if (typeof compareFunc !== 'function') {
throw new Error('BinaryHeap([weightFunc][, compareFunc]): "compareFunc" must be a function!');
}
this.weightFunc = weightFunc;
this.compareFunc = compareFunc;
this.heap = [];
}
var BHProto = BinaryHeap.prototype;
BHProto.push = function (node) {
this.heap.push(node);
bubbleUp(this.heap, this.weightFunc, this.heap.length - 1);
};
BHProto.peek = function () {
return this.heap[0];
};
BHProto.pop = function () {
var front = this.heap[0];
var end = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = end;
bubbleDown(this.heap, this.weightFunc, 0);
}
return front;
};
BHProto.remove = function (node) {
var length = this.heap.length;
for (var i = 0; i < length; i++) {
if (this.compareFunc(this.heap[i], node)) {
var removed = this.heap[i];
var end = this.heap.pop();
if (i !== length - 1) {
this.heap[i] = end;
bubbleUp(this.heap, this.weightFunc, i);
bubbleDown(this.heap, this.weightFunc, i);
}
return removed;
}
}
return null;
};
BHProto.removeAll = function () {
this.heap = [];
};
BHProto.size = function () {
return this.heap.length;
};
module.exports = BinaryHeap;
/***/ }
/******/ ])
});
;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/**
* Array forEach
*/
function forEach(arr, callback, thisObj) {
if (arr == null) {
return;
}
var i = -1,
len = arr.length;
while (++i < len) {
// we iterate over sparse items since there is no way to make it
// work properly on IE 7-8. see #64
if ( callback.call(thisObj, arr[i], i, arr) === false ) {
break;
}
}
}
module.exports = forEach;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
/**
* Create slice of source array or array-like object
*/
function slice(arr, start, end){
var len = arr.length;
if (start == null) {
start = 0;
} else if (start < 0) {
start = Math.max(len + start, 0);
} else {
start = Math.min(start, len);
}
if (end == null) {
end = len;
} else if (end < 0) {
end = Math.max(len + end, 0);
} else {
end = Math.min(end, len);
}
var result = [];
while (start < end) {
result.push(arr[start++]);
}
return result;
}
module.exports = slice;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
var indexOf = __webpack_require__(21);
/**
* If array contains values.
*/
function contains(arr, val) {
return indexOf(arr, val) !== -1;
}
module.exports = contains;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
var indexOf = __webpack_require__(21);
/**
* Remove a single item from the array.
* (it won't remove duplicates, just a single item)
*/
function remove(arr, item){
var idx = indexOf(arr, item);
if (idx !== -1) arr.splice(idx, 1);
}
module.exports = remove;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
/**
* Merge sort (http://en.wikipedia.org/wiki/Merge_sort)
*/
function mergeSort(arr, compareFn) {
if (arr == null) {
return [];
} else if (arr.length < 2) {
return arr;
}
if (compareFn == null) {
compareFn = defaultCompare;
}
var mid, left, right;
mid = ~~(arr.length / 2);
left = mergeSort( arr.slice(0, mid), compareFn );
right = mergeSort( arr.slice(mid, arr.length), compareFn );
return merge(left, right, compareFn);
}
function defaultCompare(a, b) {
return a < b ? -1 : (a > b? 1 : 0);
}
function merge(left, right, compareFn) {
var result = [];
while (left.length && right.length) {
if (compareFn(left[0], right[0]) <= 0) {
// if 0 it should preserve same order (stable)
result.push(left.shift());
} else {
result.push(right.shift());
}
}
if (left.length) {
result.push.apply(result, left);
}
if (right.length) {
result.push.apply(result, right);
}
return result;
}
module.exports = mergeSort;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var hasOwn = __webpack_require__(22);
var forIn = __webpack_require__(23);
/**
* Similar to Array/forEach but works over object properties and fixes Don't
* Enum bug on IE.
* based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
*/
function forOwn(obj, fn, thisObj){
forIn(obj, function(val, key){
if (hasOwn(obj, key)) {
return fn.call(thisObj, obj[key], key, obj);
}
});
}
module.exports = forOwn;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
var forOwn = __webpack_require__(13);
var isPlainObject = __webpack_require__(24);
/**
* Mixes objects into the target object, recursively mixing existing child
* objects.
*/
function deepMixIn(target, objects) {
var i = 0,
n = arguments.length,
obj;
while(++i < n){
obj = arguments[i];
if (obj) {
forOwn(obj, copyProp, target);
}
}
return target;
}
function copyProp(val, key) {
var existing = this[key];
if (isPlainObject(val) && isPlainObject(existing)) {
deepMixIn(existing, val);
} else {
this[key] = val;
}
}
module.exports = deepMixIn;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
var slice = __webpack_require__(9);
/**
* Return a copy of the object, filtered to only have values for the whitelisted keys.
*/
function pick(obj, var_keys){
var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1),
out = {},
i = 0, key;
while (key = keys[i++]) {
out[key] = obj[key];
}
return out;
}
module.exports = pick;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
var forOwn = __webpack_require__(13);
/**
* Get object keys
*/
var keys = Object.keys || function (obj) {
var keys = [];
forOwn(obj, function(val, key){
keys.push(key);
});
return keys;
};
module.exports = keys;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var isPrimitive = __webpack_require__(25);
/**
* get "nested" object property
*/
function get(obj, prop){
var parts = prop.split('.'),
last = parts.pop();
while (prop = parts.shift()) {
obj = obj[prop];
if (obj == null) return;
}
return obj[last];
}
module.exports = get;
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
var namespace = __webpack_require__(26);
/**
* set "nested" object property
*/
function set(obj, prop, val){
var parts = (/^(.+)\.(.+)$/).exec(prop);
if (parts){
namespace(obj, parts[1])[parts[2]] = val;
} else {
obj[prop] = val;
}
}
module.exports = set;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
var toString = __webpack_require__(42);
var camelCase = __webpack_require__(43);
var upperCase = __webpack_require__(20);
/**
* camelCase + UPPERCASE first char
*/
function pascalCase(str){
str = toString(str);
return camelCase(str).replace(/^[a-z]/, upperCase);
}
module.exports = pascalCase;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
var toString = __webpack_require__(42);
/**
* "Safer" String.toUpperCase()
*/
function upperCase(str){
str = toString(str);
return str.toUpperCase();
}
module.exports = upperCase;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
/**
* Array.indexOf
*/
function indexOf(arr, item, fromIndex) {
fromIndex = fromIndex || 0;
if (arr == null) {
return -1;
}
var len = arr.length,
i = fromIndex < 0 ? len + fromIndex : fromIndex;
while (i < len) {
// we iterate over sparse items since there is no way to make it
// work properly on IE 7-8. see #64
if (arr[i] === item) {
return i;
}
i++;
}
return -1;
}
module.exports = indexOf;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
/**
* Safer Object.hasOwnProperty
*/
function hasOwn(obj, prop){
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = hasOwn;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
var hasOwn = __webpack_require__(22);
var _hasDontEnumBug,
_dontEnums;
function checkDontEnum(){
_dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
_hasDontEnumBug = true;
for (var key in {'toString': null}) {
_hasDontEnumBug = false;
}
}
/**
* Similar to Array/forEach but works over object properties and fixes Don't
* Enum bug on IE.
* based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
*/
function forIn(obj, fn, thisObj){
var key, i = 0;
// no need to check if argument is a real object that way we can use
// it for arrays, functions, date, etc.
//post-pone check till needed
if (_hasDontEnumBug == null) checkDontEnum();
for (key in obj) {
if (exec(fn, obj, key, thisObj) === false) {
break;
}
}
if (_hasDontEnumBug) {
var ctor = obj.constructor,
isProto = !!ctor && obj === ctor.prototype;
while (key = _dontEnums[i++]) {
// For constructor, if it is a prototype object the constructor
// is always non-enumerable unless defined otherwise (and
// enumerated above). For non-prototype objects, it will have
// to be defined on this object, since it cannot be defined on
// any prototype objects.
//
// For other [[DontEnum]] properties, check if the value is
// different than Object prototype value.
if (
(key !== 'constructor' ||
(!isProto && hasOwn(obj, key))) &&
obj[key] !== Object.prototype[key]
) {
if (exec(fn, obj, key, thisObj) === false) {
break;
}
}
}
}
}
function exec(fn, obj, key, thisObj){
return fn.call(thisObj, obj[key], key, obj);
}
module.exports = forIn;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
/**
* Checks if the value is created by the `Object` constructor.
*/
function isPlainObject(value) {
return (!!value && typeof value === 'object' &&
value.constructor === Object);
}
module.exports = isPlainObject;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/**
* Checks if the object is a primitive
*/
function isPrimitive(value) {
// Using switch fallthrough because it's simple to read and is
// generally fast: http://jsperf.com/testing-value-is-primitive/5
switch (typeof value) {
case "string":
case "number":
case "boolean":
return true;
}
return value == null;
}
module.exports = isPrimitive;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
var forEach = __webpack_require__(8);
/**
* Create nested object if non-existent
*/
function namespace(obj, path){
if (!path) return obj;
forEach(path.split('.'), function(key){
if (!obj[key]) {
obj[key] = {};
}
obj = obj[key];
});
return obj;
}
module.exports = namespace;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
/*jshint evil:true, loopfunc:true*/
var _utils = __webpack_require__(2);
var _errors = __webpack_require__(3);
/**
* These are DS methods that will be proxied by instances. e.g.
*
* var store = new JSData.DS();
* var User = store.defineResource('user');
* var user = User.createInstance({ id: 1 });
*
* store.update(resourceName, id, attrs[, options]) // DS method
* User.update(id, attrs[, options]) // DS method proxied on a Resource
* user.DSUpdate(attrs[, options]) // DS method proxied on an Instance
*/
var instanceMethods = ['compute', 'eject', 'refresh', 'save', 'update', 'destroy', 'loadRelations', 'changeHistory', 'changes', 'hasChanges', 'lastModified', 'lastSaved', 'previous', 'revert'];
module.exports = function defineResource(definition) {
var _this = this;
var definitions = _this.definitions;
/**
* This allows the name-only definition shorthand.
* store.defineResource('user') is the same as store.defineResource({ name: 'user'})
*/
if (_utils['default']._s(definition)) {
definition = {
name: definition.replace(/\s/gi, '')
};
}
if (!_utils['default']._o(definition)) {
throw _utils['default']._oErr('definition');
} else if (!_utils['default']._s(definition.name)) {
throw new _errors['default'].IA('"name" must be a string!');
} else if (definitions[definition.name]) {
throw new _errors['default'].R(definition.name + ' is already registered!');
}
/**
* Dynamic Resource constructor function.
*
* A Resource inherits from the defaults of the data store that created it.
*/
function Resource(options) {
this.defaultValues = {};
this.methods = {};
this.computed = {};
_utils['default'].deepMixIn(this, options);
var parent = _this.defaults;
if (definition['extends'] && definitions[definition['extends']]) {
parent = definitions[definition['extends']];
}
_utils['default'].fillIn(this.defaultValues, parent.defaultValues);
_utils['default'].fillIn(this.methods, parent.methods);
_utils['default'].fillIn(this.computed, parent.computed);
this.endpoint = 'endpoint' in options ? options.endpoint : this.name;
}
try {
var def;
var _class;
var _ret = (function () {
// Resources can inherit from another resource instead of inheriting directly from the data store defaults.
if (definition['extends'] && definitions[definition['extends']]) {
// Inherit from another resource
Resource.prototype = definitions[definition['extends']];
} else {
// Inherit from global defaults
Resource.prototype = _this.defaults;
}
definitions[definition.name] = new Resource(definition);
def = definitions[definition.name];
def.getResource = function (resourceName) {
return _this.definitions[resourceName];
};
if (!_utils['default']._s(def.idAttribute)) {
throw new _errors['default'].IA('"idAttribute" must be a string!');
}
// Setup nested parent configuration
if (def.relations) {
def.relationList = [];
def.relationFields = [];
_utils['default'].forOwn(def.relations, function (relatedModels, type) {
_utils['default'].forOwn(relatedModels, function (defs, relationName) {
if (!_utils['default']._a(defs)) {
relatedModels[relationName] = [defs];
}
_utils['default'].forEach(relatedModels[relationName], function (d) {
d.type = type;
d.relation = relationName;
d.name = def.name;
def.relationList.push(d);
if (d.localField) {
def.relationFields.push(d.localField);
}
});
});
});
if (def.relations.belongsTo) {
_utils['default'].forOwn(def.relations.belongsTo, function (relatedModel, modelName) {
_utils['default'].forEach(relatedModel, function (relation) {
if (relation.parent) {
def.parent = modelName;
def.parentKey = relation.localKey;
def.parentField = relation.localField;
}
});
});
}
if (typeof Object.freeze === 'function') {
Object.freeze(def.relations);
Object.freeze(def.relationList);
}
}
// Create the wrapper class for the new resource
_class = def['class'] = _utils['default'].pascalCase(def.name);
try {
if (typeof def.useClass === 'function') {
eval('function ' + _class + '() { def.useClass.call(this); }');
def[_class] = eval(_class);
def[_class].prototype = (function (proto) {
function Ctor() {}
Ctor.prototype = proto;
return new Ctor();
})(def.useClass.prototype);
} else {
eval('function ' + _class + '() {}');
def[_class] = eval(_class);
}
} catch (e) {
def[_class] = function () {};
}
// Apply developer-defined instance methods
_utils['default'].forOwn(def.methods, function (fn, m) {
def[_class].prototype[m] = fn;
});
/**
* var user = User.createInstance({ id: 1 });
* user.set('foo', 'bar');
*/
def[_class].prototype.set = function (key, value) {
var _this2 = this;
_utils['default'].set(this, key, value);
def.compute(this);
if (def.instanceEvents) {
setTimeout(function () {
_this2.emit('DS.change', def, _this2);
}, 0);
}
def.handleChange(this);
return this;
};
/**
* var user = User.createInstance({ id: 1 });
* user.get('id'); // 1
*/
def[_class].prototype.get = function (key) {
return _utils['default'].get(this, key);
};
if (def.instanceEvents) {
_utils['default'].Events(def[_class].prototype);
}
// Setup the relation links
_utils['default'].applyRelationGettersToTarget(_this, def, def[_class].prototype);
var parentOmit = null;
if (!def.hasOwnProperty('omit')) {
parentOmit = def.omit;
def.omit = [];
} else {
parentOmit = _this.defaults.omit;
}
def.omit = def.omit.concat(parentOmit || []);
// Prepare for computed properties
_utils['default'].forOwn(def.computed, function (fn, field) {
if (_utils['default'].isFunction(fn)) {
def.computed[field] = [fn];
fn = def.computed[field];
}
if (def.methods && field in def.methods) {
def.errorFn('Computed property "' + field + '" conflicts with previously defined prototype method!');
}
def.omit.push(field);
var deps;
if (fn.length === 1) {
var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/);
deps = match[1].split(',');
def.computed[field] = deps.concat(fn);
fn = def.computed[field];
if (deps.length) {
def.errorFn('Use the computed property array syntax for compatibility with minified code!');
}
}
deps = fn.slice(0, fn.length - 1);
_utils['default'].forEach(deps, function (val, index) {
deps[index] = val.trim();
});
fn.deps = _utils['default'].filter(deps, function (dep) {
return !!dep;
});
});
// add instance proxies of DS methods
_utils['default'].forEach(instanceMethods, function (name) {
def[_class].prototype['DS' + _utils['default'].pascalCase(name)] = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
args.unshift(this[def.idAttribute] || this);
args.unshift(def.name);
return _this[name].apply(_this, args);
};
});
// manually add instance proxy for DS#create
def[_class].prototype.DSCreate = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
args.unshift(this);
args.unshift(def.name);
return _this.create.apply(_this, args);
};
// Initialize store data for the new resource
_this.store[def.name] = {
collection: [],
expiresHeap: new _utils['default'].BinaryHeap(function (x) {
return x.expires;
}, function (x, y) {
return x.item === y;
}),
completedQueries: {},
queryData: {},
pendingQueries: {},
index: {},
modified: {},
saved: {},
previousAttributes: {},
observers: {},
changeHistories: {},
changeHistory: [],
collectionModified: 0
};
var resource = _this.store[def.name];
// start the reaping
if (def.reapInterval) {
setInterval(function () {
return def.reap();
}, def.reapInterval);
}
// proxy DS methods with shorthand ones
var fns = ['registerAdapter', 'getAdapterName', 'getAdapter', 'is', '!clear'];
for (var key in _this) {
if (typeof _this[key] === 'function') {
fns.push(key);
}
}
/**
* Create the Resource shorthands that proxy DS methods. e.g.
*
* var store = new JSData.DS();
* var User = store.defineResource('user');
*
* store.update(resourceName, id, attrs[, options]) // DS method
* User.update(id, attrs[, options]) // DS method proxied on a Resource
*/
_utils['default'].forEach(fns, function (key) {
var k = key;
if (k[0] === '!') {
return;
}
if (_this[k].shorthand !== false) {
def[k] = function () {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
args.unshift(def.name);
return _this[k].apply(_this, args);
};
def[k].before = function (fn) {
var orig = def[k];
def[k] = function () {
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return orig.apply(def, fn.apply(def, args) || args);
};
};
} else {
def[k] = function () {
for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
return _this[k].apply(_this, args);
};
}
});
def.beforeValidate = _utils['default'].promisify(def.beforeValidate);
def.validate = _utils['default'].promisify(def.validate);
def.afterValidate = _utils['default'].promisify(def.afterValidate);
def.beforeCreate = _utils['default'].promisify(def.beforeCreate);
def.afterCreate = _utils['default'].promisify(def.afterCreate);
def.beforeUpdate = _utils['default'].promisify(def.beforeUpdate);
def.afterUpdate = _utils['default'].promisify(def.afterUpdate);
def.beforeDestroy = _utils['default'].promisify(def.beforeDestroy);
def.afterDestroy = _utils['default'].promisify(def.afterDestroy);
var defaultAdapter = undefined;
if (def.hasOwnProperty('defaultAdapter')) {
defaultAdapter = def.defaultAdapter;
}
// setup "actions"
_utils['default'].forOwn(def.actions, function (action, name) {
if (def[name] && !def.actions[name]) {
throw new Error('Cannot override existing method "' + name + '"!');
}
action.request = action.request || function (config) {
return config;
};
action.response = action.response || function (response) {
return response;
};
action.responseError = action.responseError || function (err) {
return _utils['default'].Promise.reject(err);
};
def[name] = function (id, options) {
if (_utils['default']._o(id)) {
options = id;
}
options = options || {};
var adapter = def.getAdapter(action.adapter || defaultAdapter || 'http');
var config = _utils['default'].deepMixIn({}, action);
if (!options.hasOwnProperty('endpoint') && config.endpoint) {
options.endpoint = config.endpoint;
}
if (typeof options.getEndpoint === 'function') {
config.url = options.getEndpoint(def, options);
} else {
var args = [options.basePath || adapter.defaults.basePath || def.basePath, adapter.getEndpoint(def, _utils['default']._sn(id) ? id : null, options)];
if (_utils['default']._sn(id)) {
args.push(id);
}
args.push(action.pathname || name);
config.url = _utils['default'].makePath.apply(null, args);
}
config.method = config.method || 'GET';
_utils['default'].deepMixIn(config, options);
return new _utils['default'].Promise(function (r) {
return r(config);
}).then(options.request || action.request).then(function (config) {
return adapter.HTTP(config);
}).then(options.response || action.response, options.responseError || action.responseError);
};
});
// mix in events
_utils['default'].Events(def);
def.handleChange = function (data) {
resource.collectionModified = _utils['default'].updateTimestamp(resource.collectionModified);
if (def.notify) {
setTimeout(function () {
def.emit('DS.change', def, data);
}, 0);
}
};
return {
v: def
};
})();
if (typeof _ret === 'object') return _ret.v;
} catch (err) {
_this.defaults.errorFn(err);
delete definitions[definition.name];
delete _this.store[definition.name];
throw err;
}
};
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
/**
* Eject an item from the store, if it is currently in the store.
*
* @param resourceName The name of the resource type of the item eject.
* @param id The primary key of the item to eject.
* @param options Optional configuration.
* @param options.notify Whether to emit the "DS.beforeEject" and "DS.afterEject" events
* @param options.clearEmptyQueries Whether to remove cached findAll queries that become empty as a result of this method call.
* @returns The ejected item if one was ejected.
*/
module.exports = function eject(resourceName, id, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var item = undefined;
var found = false;
id = DSUtils.resolveId(definition, id);
if (!definition) {
throw new _this.errors.NER(resourceName);
} else if (!DSUtils._sn(id)) {
throw DSUtils._snErr('id');
}
options = DSUtils._(definition, options);
// find the item to eject
for (var i = 0; i < resource.collection.length; i++) {
if (resource.collection[i][definition.idAttribute] == id) {
// jshint ignore:line
item = resource.collection[i];
// remove its expiration timestamp
resource.expiresHeap.remove(item);
found = true;
break;
}
}
if (found) {
var _ret = (function () {
// lifecycle
definition.beforeEject(options, item);
if (options.notify) {
definition.emit('DS.beforeEject', definition, item);
}
// find the item in any ($$injected) cached queries
var toRemove = [];
DSUtils.forOwn(resource.queryData, function (items, queryHash) {
if (items.$$injected) {
DSUtils.remove(items, item);
}
// optionally remove any empty queries
if (!items.length && options.clearEmptyQueries) {
toRemove.push(queryHash);
}
});
// clean up
DSUtils.forEach(resource.changeHistories[id], function (changeRecord) {
DSUtils.remove(resource.changeHistory, changeRecord);
});
DSUtils.forEach(toRemove, function (queryHash) {
delete resource.completedQueries[queryHash];
delete resource.queryData[queryHash];
});
if (DSUtils.w) {
// stop observation
resource.observers[id].close();
}
delete resource.observers[id];
delete resource.index[id];
delete resource.previousAttributes[id];
delete resource.completedQueries[id];
delete resource.pendingQueries[id];
delete resource.changeHistories[id];
delete resource.modified[id];
delete resource.saved[id];
// remove it from the store
resource.collection.splice(i, 1);
// collection has been modified
definition.handleChange(item);
// lifecycle
definition.afterEject(options, item);
if (options.notify) {
definition.emit('DS.afterEject', definition, item);
}
return {
v: item
};
})();
if (typeof _ret === 'object') return _ret.v;
}
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
/**
* Eject a collection of items from the store, if any items currently in the store match the given criteria.
*
* @param resourceName The name of the resource type of the items eject.
* @param params The criteria by which to match items to eject. See http://www.js-data.io/docs/query-syntax
* @param options Optional configuration.
* @returns The collection of items that were ejected, if any.
*/
module.exports = function ejectAll(resourceName, params, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
params = params || {};
if (!definition) {
throw new _this.errors.NER(resourceName);
} else if (!DSUtils._o(params)) {
throw DSUtils._oErr('params');
}
var resource = _this.store[resourceName];
var queryHash = DSUtils.toJson(params);
// get items that match the criteria
var items = definition.filter(params);
if (DSUtils.isEmpty(params)) {
// remove all completed queries if ejecting all items
resource.completedQueries = {};
} else {
// remove matching completed query, if any
delete resource.completedQueries[queryHash];
}
// prepare to remove matching items
DSUtils.forEach(items, function (item) {
if (item && item[definition.idAttribute]) {
definition.eject(item[definition.idAttribute], options);
}
});
// collection has been modified
definition.handleChange(items);
return items;
};
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
/**
* Return the subset of items currently in the store that match the given criteria.
*
* The actual filtering is delegated to DS#defaults.defaultFilter, which can be overridden by developers.
*
* @param resourceName The name of the resource type of the items to filter.
* @param params The criteria by which to filter items. See http://www.js-data.io/docs/query-syntax
* @param options Optional configuration.
* @returns Matching items.
*/
module.exports = function filter(resourceName, params, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
if (!definition) {
throw new _this.errors.NER(resourceName);
} else if (params && !DSUtils._o(params)) {
throw DSUtils._oErr('params');
}
// Protect against null
params = params || {};
options = DSUtils._(definition, options);
// delegate filtering to DS#defaults.defaultFilter, which can be overridden by developers.
return definition.defaultFilter.call(_this, _this.store[resourceName].collection, resourceName, params, options);
};
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
var _utils = __webpack_require__(2);
var _errors = __webpack_require__(3);
/**
* This is a beast of a file, but it's where a significant portion of the magic happens.
*
* DS#inject makes up the core of how data gets into the store.
*/
/**
* This factory function produces an observer handler function tailor-made for the current item being injected.
*
* The observer handler is what allows computed properties and change tracking to function.
*
* @param definition Resource definition produced by DS#defineResource
* @param resource Resource data as internally stored by the data store
* @returns {Function} Observer handler function
* @private
*/
function makeObserverHandler(definition, resource) {
var DS = this;
// using "var" avoids a JSHint error
var name = definition.name;
/**
* This will be called by observe-js when a new change record is available for the observed object
*
* @param added Change record for added properties
* @param removed Change record for removed properties
* @param changed Change record for changed properties
* @param oldValueFn Function that can be used to get the previous value of a changed property
* @param firstTime Whether this is the first time this function is being called for the given item. Will only be true once.
*/
return function _react(added, removed, changed, oldValueFn, firstTime) {
var target = this;
var item = undefined;
// Get the previous primary key of the observed item, in-case some knucklehead changed it
var innerId = oldValueFn && oldValueFn(definition.idAttribute) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute];
// Ignore changes to relation links
_utils['default'].forEach(definition.relationFields, function (field) {
delete added[field];
delete removed[field];
delete changed[field];
});
// Detect whether there are actually any changes
if (!_utils['default'].isEmpty(added) || !_utils['default'].isEmpty(removed) || !_utils['default'].isEmpty(changed) || firstTime) {
item = DS.get(name, innerId);
// update item and collection "modified" timestamps
resource.modified[innerId] = _utils['default'].updateTimestamp(resource.modified[innerId]);
if (item && definition.instanceEvents) {
setTimeout(function () {
item.emit('DS.change', definition, item);
}, 0);
}
definition.handleChange(item);
// Save a change record for the item
if (definition.keepChangeHistory) {
var changeRecord = {
resourceName: name,
target: item,
added: added,
removed: removed,
changed: changed,
timestamp: resource.modified[innerId]
};
resource.changeHistories[innerId].push(changeRecord);
resource.changeHistory.push(changeRecord);
}
}
// Recompute computed properties if any computed properties depend on changed properties
if (definition.computed) {
item = item || DS.get(name, innerId);
_utils['default'].forOwn(definition.computed, function (fn, field) {
var compute = false;
// check if required fields changed
_utils['default'].forEach(fn.deps, function (dep) {
if (dep in added || dep in removed || dep in changed || !(field in item)) {
compute = true;
}
});
compute = compute || !fn.deps.length;
if (compute) {
_utils['default'].compute.call(item, fn, field);
}
});
}
if (definition.idAttribute in changed) {
definition.errorFn('Doh! You just changed the primary key of an object! Your data for the "' + name + '" resource is now in an undefined (probably broken) state.');
}
};
}
/**
* A recursive function for injecting data into the store.
*
* @param definition Resource definition produced by DS#defineResource
* @param resource Resource data as internally stored by the data store
* @param attrs The data to be injected. Will be an object or an array of objects.
* @param options Optional configuration.
* @returns The injected data
* @private
*/
function _inject(definition, resource, attrs, options) {
var _this = this;
var injected = undefined;
if (_utils['default']._a(attrs)) {
// have an array of objects, go ahead and inject each one individually and return the resulting array
injected = [];
for (var i = 0; i < attrs.length; i++) {
injected.push(_inject.call(_this, definition, resource, attrs[i], options));
}
} else {
// create the observer handler for the data to be injected
var _react = makeObserverHandler.call(_this, definition, resource);
// check if "idAttribute" is a computed property
var c = definition.computed;
var idA = definition.idAttribute;
// compute the primary key if necessary
if (c && c[idA]) {
(function () {
var args = [];
_utils['default'].forEach(c[idA].deps, function (dep) {
args.push(attrs[dep]);
});
attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args);
})();
}
if (!(idA in attrs)) {
// we cannot inject any object into the store that does not have a primary key!
var error = new _errors['default'].R(definition.name + '.inject: "attrs" must contain the property specified by "idAttribute"!');
options.errorFn(error);
throw error;
} else {
try {
(function () {
// when injecting object that contain their nested relations, this code
// will recursively inject them into their proper places in the data store.
// Magic!
_utils['default'].forEach(definition.relationList, function (def) {
var relationName = def.relation;
var relationDef = _this.definitions[relationName];
var toInject = attrs[def.localField];
if (toInject) {
if (!relationDef) {
throw new _errors['default'].R(definition.name + ' relation is defined but the resource is not!');
}
// handle injecting hasMany relations
if (_utils['default']._a(toInject)) {
(function () {
var items = [];
_utils['default'].forEach(toInject, function (toInjectItem) {
if (toInjectItem !== _this.store[relationName].index[toInjectItem[relationDef.idAttribute]]) {
try {
var injectedItem = relationDef.inject(toInjectItem, options.orig());
if (def.foreignKey) {
_utils['default'].set(injectedItem, def.foreignKey, attrs[definition.idAttribute]);
}
items.push(injectedItem);
} catch (err) {
options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!');
}
}
});
})();
} else {
// handle injecting belongsTo and hasOne relations
if (toInject !== _this.store[relationName].index[toInject[relationDef.idAttribute]]) {
try {
var _injected = relationDef.inject(attrs[def.localField], options.orig());
if (def.foreignKey) {
_utils['default'].set(_injected, def.foreignKey, attrs[definition.idAttribute]);
}
} catch (err) {
options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!');
}
}
}
}
});
// primary key of item being injected
var id = attrs[idA];
// item being injected
var item = definition.get(id);
// 0 if the item is new, otherwise the previous last modified timestamp of the item
var initialLastModified = item ? resource.modified[id] : 0;
// item is new
if (!item) {
if (attrs instanceof definition[definition['class']]) {
item = attrs;
} else {
item = new definition[definition['class']]();
}
// remove relation properties from the item, since those relations have been injected by now
_utils['default'].forEach(definition.relationList, function (def) {
delete attrs[def.localField];
});
// copy remaining properties to the injected item
_utils['default'].deepMixIn(item, attrs);
// add item to collection
resource.collection.push(item);
resource.changeHistories[id] = [];
// If we're in the browser, start observation
if (_utils['default'].w) {
resource.observers[id] = new _this.observe.ObjectObserver(item);
resource.observers[id].open(_react, item);
}
// index item
resource.index[id] = item;
// fire observation handler for the first time
_react.call(item, {}, {}, {}, null, true);
// save "previous" attributes of the injected item, for change diffs later
resource.previousAttributes[id] = _utils['default'].copy(item, null, null, null, definition.relationFields);
} else {
// item is being re-injected
// new properties take precedence
if (options.onConflict === 'merge') {
_utils['default'].deepMixIn(item, attrs);
} else if (options.onConflict === 'replace') {
_utils['default'].forOwn(item, function (v, k) {
if (k !== definition.idAttribute) {
if (!attrs.hasOwnProperty(k)) {
delete item[k];
}
}
});
_utils['default'].forOwn(attrs, function (v, k) {
if (k !== definition.idAttribute) {
item[k] = v;
}
});
}
if (definition.resetHistoryOnInject) {
// clear change history for item
resource.previousAttributes[id] = _utils['default'].copy(item, null, null, null, definition.relationFields);
if (resource.changeHistories[id].length) {
_utils['default'].forEach(resource.changeHistories[id], function (changeRecord) {
_utils['default'].remove(resource.changeHistory, changeRecord);
});
resource.changeHistories[id].splice(0, resource.changeHistories[id].length);
}
}
if (_utils['default'].w) {
// force observation callback to be fired if there are any changes to the item and `Object.observe` is not available
resource.observers[id].deliver();
}
}
// update modified timestamp of item
resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? _utils['default'].updateTimestamp(resource.modified[id]) : resource.modified[id];
// reset expiry tracking for item
resource.expiresHeap.remove(item);
var timestamp = new Date().getTime();
resource.expiresHeap.push({
item: item,
timestamp: timestamp,
expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE
});
// final injected item
injected = item;
})();
} catch (err) {
options.errorFn(err, attrs);
}
}
}
return injected;
}
/**
* Inject the given object or array of objects into the data store.
*
* @param resourceName The name of the type of resource of the data to be injected.
* @param attrs Object or array of objects. Objects must contain a primary key.
* @param options Optional configuration.
* @param options.notify Whether to emit the "DS.beforeInject" and "DS.afterInject" events.
* @returns The injected data.
*/
module.exports = function inject(resourceName, attrs, options) {
var _this = this;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var injected = undefined;
if (!definition) {
throw new _errors['default'].NER(resourceName);
} else if (!_utils['default']._o(attrs) && !_utils['default']._a(attrs)) {
throw new _errors['default'].IA(resourceName + '.inject: "attrs" must be an object or an array!');
}
options = _utils['default']._(definition, options);
// lifecycle
options.beforeInject(options, attrs);
if (options.notify) {
definition.emit('DS.beforeInject', definition, attrs);
}
// start the recursive injection of data
injected = _inject.call(_this, definition, resource, attrs, options);
// collection was modified
definition.handleChange(injected);
// lifecycle
options.afterInject(options, injected);
if (options.notify) {
definition.emit('DS.afterInject', definition, injected);
}
return injected;
};
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
/**
* Using an adapter, create a new item.
*
* Generally a primary key will NOT be provided in the properties hash,
* because the adapter's persistence layer should be generating one.
*
* @param resourceName The name of the type of resource of the new item.
* @param attrs Hash of properties with which to create the new item.
* @param options Optional configuration.
* @param options.cacheResponse Whether the newly created item as returned by the adapter should be injected into the data store.
* @param options.upsert If the properties hash contains a primary key, attempt to call DS#update instead.
* @param options.notify Whether to emit the "DS.beforeCreate" and "DS.afterCreate" events.
* @param options.beforeValidate Lifecycle hook.
* @param options.validate Lifecycle hook.
* @param options.afterValidate Lifecycle hook.
* @param options.beforeCreate Lifecycle hook.
* @param options.afterCreate Lifecycle hook.
*/
module.exports = function create(resourceName, attrs, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
var adapter = undefined;
options = options || {};
attrs = attrs || {};
var rejectionError = undefined;
if (!definition) {
rejectionError = new _this.errors.NER(resourceName);
} else if (!DSUtils._o(attrs)) {
rejectionError = DSUtils._oErr('attrs');
} else {
options = DSUtils._(definition, options);
if (options.upsert && DSUtils._sn(attrs[definition.idAttribute])) {
return _this.update(resourceName, attrs[definition.idAttribute], attrs, options);
}
}
return new DSUtils.Promise(function (resolve, reject) {
if (rejectionError) {
reject(rejectionError);
} else {
resolve(attrs);
}
})
// start lifecycle
.then(function (attrs) {
return options.beforeValidate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.validate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.afterValidate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.beforeCreate.call(attrs, options, attrs);
}).then(function (attrs) {
if (options.notify) {
definition.emit('DS.beforeCreate', definition, attrs);
}
adapter = _this.getAdapterName(options);
return _this.adapters[adapter].create(definition, DSUtils.omit(attrs, options.omit), options);
}).then(function (attrs) {
return options.afterCreate.call(attrs, options, attrs);
}).then(function (attrs) {
if (options.notify) {
definition.emit('DS.afterCreate', definition, attrs);
}
if (options.cacheResponse) {
// injected created intem into the store
var created = _this.inject(definition.name, attrs, options.orig());
var id = created[definition.idAttribute];
// mark item's `find` query as completed, so a subsequent `find` call for this item will resolve immediately
var resource = _this.store[resourceName];
resource.completedQueries[id] = new Date().getTime();
resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]);
return created;
} else {
// just return an un-injected instance
return _this.createInstance(resourceName, attrs, options);
}
}).then(function (item) {
return DSUtils.respond(item, { adapter: adapter }, options);
});
};
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
/**
* Using an adapter, destroy an item.
*
* @param resourceName The name of the type of resource of the item to destroy.
* @param id The primary key of the item to destroy.
* @param options Optional configuration.
* @param options.eagerEject Whether to eject the item from the store before the adapter operation completes, re-injecting if the adapter operation fails.
* @param options.notify Whether to emit the "DS.beforeDestroy" and "DS.afterDestroy" events.
* @param options.beforeDestroy Lifecycle hook.
* @param options.afterDestroy Lifecycle hook.
* @returns The primary key of the destroyed item.
*/
module.exports = function destroy(resourceName, id, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
var item = undefined;
var adapter = undefined;
return new DSUtils.Promise(function (resolve, reject) {
id = DSUtils.resolveId(definition, id);
if (!definition) {
reject(new _this.errors.NER(resourceName));
} else if (!DSUtils._sn(id)) {
reject(DSUtils._snErr('id'));
} else {
// check if the item is in the store
item = definition.get(id) || { id: id };
options = DSUtils._(definition, options);
resolve(item);
}
})
// start lifecycle
.then(function (attrs) {
return options.beforeDestroy.call(attrs, options, attrs);
}).then(function (attrs) {
if (options.notify) {
definition.emit('DS.beforeDestroy', definition, attrs);
}
// don't wait for the adapter, remove the item from the store
if (options.eagerEject) {
definition.eject(id);
}
adapter = definition.getAdapter(options);
return adapter.destroy(definition, id, options);
}).then(function () {
return options.afterDestroy.call(item, options, item);
}).then(function (item) {
if (options.notify) {
definition.emit('DS.afterDestroy', definition, item);
}
// make sure the item is removed from the store
definition.eject(id);
return DSUtils.respond(id, { adapter: adapter }, options);
})['catch'](function (err) {
// rollback by re-injecting the item into the store
if (options && options.eagerEject && item) {
definition.inject(item, { notify: false });
}
return DSUtils.Promise.reject(err);
});
};
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
/**
* Using an adapter, destroy an item.
*
* @param resourceName The name of the type of resource of the item to destroy.
* @param params The criteria by which to filter items to destroy. See http://www.js-data.io/docs/query-syntax
* @param options Optional configuration.
* @param options.eagerEject Whether to eject the items from the store before the adapter operation completes, re-injecting if the adapter operation fails.
* @param options.notify Whether to emit the "DS.beforeDestroy" and "DS.afterDestroy" events.
* @param options.beforeDestroy Lifecycle hook.
* @param options.afterDestroy Lifecycle hook.
* @returns The ejected items, if any.
*/
module.exports = function destroyAll(resourceName, params, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
var ejected = undefined,
toEject = undefined,
adapter = undefined;
params = params || {};
return new DSUtils.Promise(function (resolve, reject) {
if (!definition) {
reject(new _this.errors.NER(resourceName));
} else if (!DSUtils._o(params)) {
reject(DSUtils._oErr('attrs'));
} else {
options = DSUtils._(definition, options);
resolve();
}
}).then(function () {
// find items that are to be ejected from the store
toEject = definition.defaultFilter.call(_this, resourceName, params);
return options.beforeDestroy(options, toEject);
}).then(function () {
if (options.notify) {
definition.emit('DS.beforeDestroy', definition, toEject);
}
// don't wait for the adapter, remove the items from the store
if (options.eagerEject) {
ejected = definition.ejectAll(params);
}
adapter = definition.getAdapterName(options);
return _this.adapters[adapter].destroyAll(definition, params, options);
}).then(function () {
return options.afterDestroy(options, toEject);
}).then(function () {
if (options.notify) {
definition.emit('DS.afterDestroy', definition, toEject);
}
// make sure items are removed from the store
return ejected || definition.ejectAll(params);
}).then(function (items) {
return DSUtils.respond(items, { adapter: adapter }, options);
})['catch'](function (err) {
// rollback by re-injecting the items into the store
if (options && options.eagerEject && ejected) {
definition.inject(ejected, { notify: false });
}
return DSUtils.Promise.reject(err);
});
};
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
/* jshint -W082 */
/**
* Using an adapter, retrieve a single item.
*
* @param resourceName The of the type of resource of the item to retrieve.
* @param id The primary key of the item to retrieve.
* @param options Optional configuration.
* @param options.bypassCache Whether to ignore any cached item and force the retrieval through the adapter.
* @param options.cacheResponse Whether to inject the found item into the data store.
* @param options.strictCache Whether to only consider items to be "cached" if they were injected into the store as the result of `find` or `findAll`.
* @param options.strategy The retrieval strategy to use.
* @param options.findStrategy The retrieval strategy to use. Overrides "strategy".
* @param options.fallbackAdapters Array of names of adapters to use if using "fallback" strategy.
* @param options.findFallbackAdapters Array of names of adapters to use if using "fallback" strategy. Overrides "fallbackAdapters".
* @returns The item.
*/
module.exports = function find(resourceName, id, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var adapter = undefined;
return new DSUtils.Promise(function (resolve, reject) {
if (!definition) {
reject(new _this.errors.NER(resourceName));
} else if (!DSUtils._sn(id)) {
reject(DSUtils._snErr('id'));
} else {
options = DSUtils._(definition, options);
if (options.params) {
options.params = DSUtils.copy(options.params);
}
if (options.bypassCache || !options.cacheResponse) {
delete resource.completedQueries[id];
}
if ((!options.findStrictCache || id in resource.completedQueries) && definition.get(id) && !options.bypassCache) {
// resolve immediately with the cached item
resolve(definition.get(id));
} else {
// we're going to delegate to the adapter next
delete resource.completedQueries[id];
resolve();
}
}
}).then(function (item) {
if (!item) {
if (!(id in resource.pendingQueries)) {
var promise = undefined;
var strategy = options.findStrategy || options.strategy;
// try subsequent adapters if the preceeding one fails
if (strategy === 'fallback') {
(function () {
var makeFallbackCall = function makeFallbackCall(index) {
adapter = definition.getAdapterName((options.findFallbackAdapters || options.fallbackAdapters)[index]);
return _this.adapters[adapter].find(definition, id, options)['catch'](function (err) {
index++;
if (index < options.fallbackAdapters.length) {
return makeFallbackCall(index);
} else {
return DSUtils.Promise.reject(err);
}
});
};
promise = makeFallbackCall(0);
})();
} else {
adapter = definition.getAdapterName(options);
// just make a single attempt
promise = _this.adapters[adapter].find(definition, id, options);
}
resource.pendingQueries[id] = promise.then(function (data) {
// Query is no longer pending
delete resource.pendingQueries[id];
if (options.cacheResponse) {
// inject the item into the data store
var injected = definition.inject(data, options.orig());
// mark the item as "cached"
resource.completedQueries[id] = new Date().getTime();
resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]);
return injected;
} else {
// just return an un-injected instance
return definition.createInstance(data, options.orig());
}
});
}
return resource.pendingQueries[id];
} else {
// resolve immediately with the item
return item;
}
}).then(function (item) {
return DSUtils.respond(item, { adapter: adapter }, options);
})['catch'](function (err) {
if (resource) {
delete resource.pendingQueries[id];
}
return DSUtils.Promise.reject(err);
});
};
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
/* jshint -W082 */
function processResults(data, resourceName, queryHash, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var idAttribute = _this.definitions[resourceName].idAttribute;
var date = new Date().getTime();
data = data || [];
// Query is no longer pending
delete resource.pendingQueries[queryHash];
resource.completedQueries[queryHash] = date;
// Merge the new values into the cache
var injected = definition.inject(data, options.orig());
// Make sure each object is added to completedQueries
if (DSUtils._a(injected)) {
DSUtils.forEach(injected, function (item) {
if (item) {
var id = item[idAttribute];
if (id) {
resource.completedQueries[id] = date;
resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]);
}
}
});
} else {
options.errorFn('response is expected to be an array!');
resource.completedQueries[injected[idAttribute]] = date;
}
return injected;
}
/**
* Using an adapter, retrieve a collection of items.
*
* @param resourceName The name of the type of resource of the items to retrieve.
* @param params The criteria by which to filter items to retrieve. See http://www.js-data.io/docs/query-syntax
* @param options Optional configuration.
* @param options.bypassCache Whether to ignore any cached query for these items and force the retrieval through the adapter.
* @param options.cacheResponse Whether to inject the found items into the data store.
* @returns The items.
*/
module.exports = function findAll(resourceName, params, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var queryHash = undefined,
adapter = undefined;
return new DSUtils.Promise(function (resolve, reject) {
params = params || {};
if (!_this.definitions[resourceName]) {
reject(new _this.errors.NER(resourceName));
} else if (!DSUtils._o(params)) {
reject(DSUtils._oErr('params'));
} else {
options = DSUtils._(definition, options);
queryHash = DSUtils.toJson(params);
if (options.params) {
options.params = DSUtils.copy(options.params);
}
// force a new request
if (options.bypassCache || !options.cacheResponse) {
delete resource.completedQueries[queryHash];
delete resource.queryData[queryHash];
}
if (queryHash in resource.completedQueries) {
if (options.useFilter) {
if (options.localKeys) {
resolve(definition.getAll(options.localKeys, options.orig()));
} else {
// resolve immediately by filtering data from the data store
resolve(definition.filter(params, options.orig()));
}
} else {
// resolve immediately by returning the cached array from the previously made query
resolve(resource.queryData[queryHash]);
}
} else {
resolve();
}
}
}).then(function (items) {
if (!(queryHash in resource.completedQueries)) {
if (!(queryHash in resource.pendingQueries)) {
var promise = undefined;
var strategy = options.findAllStrategy || options.strategy;
// try subsequent adapters if the preceeding one fails
if (strategy === 'fallback') {
(function () {
var makeFallbackCall = function makeFallbackCall(index) {
adapter = definition.getAdapterName((options.findAllFallbackAdapters || options.fallbackAdapters)[index]);
return _this.adapters[adapter].findAll(definition, params, options)['catch'](function (err) {
index++;
if (index < options.fallbackAdapters.length) {
return makeFallbackCall(index);
} else {
return DSUtils.Promise.reject(err);
}
});
};
promise = makeFallbackCall(0);
})();
} else {
adapter = definition.getAdapterName(options);
// just make a single attempt
promise = _this.adapters[adapter].findAll(definition, params, options);
}
resource.pendingQueries[queryHash] = promise.then(function (data) {
// Query is no longer pending
delete resource.pendingQueries[queryHash];
if (options.cacheResponse) {
// inject the items into the data store
resource.queryData[queryHash] = processResults.call(_this, data, resourceName, queryHash, options);
resource.queryData[queryHash].$$injected = true;
return resource.queryData[queryHash];
} else {
DSUtils.forEach(data, function (item, i) {
data[i] = definition.createInstance(item, options.orig());
});
return data;
}
});
}
return resource.pendingQueries[queryHash];
} else {
// resolve immediately with the items
return items;
}
}).then(function (items) {
return DSUtils.respond(items, { adapter: adapter }, options);
})['catch'](function (err) {
if (resource) {
delete resource.pendingQueries[queryHash];
}
return DSUtils.Promise.reject(err);
});
};
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Load the specified relations for the given instance.
*
* @param resourceName The name of the type of resource of the instance for which to load relations.
* @param instance The instance or the primary key of the instance.
* @param relations An array of the relations to load.
* @param options Optional configuration.
* @returns The instance, now with its relations loaded.
*/
module.exports = function loadRelations(resourceName, instance, relations, options) {
var _this = this;
var DSUtils = _this.utils;
var DSErrors = _this.errors;
var definition = _this.definitions[resourceName];
return new DSUtils.Promise(function (resolve, reject) {
if (DSUtils._sn(instance)) {
instance = definition.get(instance);
}
if (DSUtils._s(relations)) {
relations = [relations];
}
relations = relations || [];
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils._o(instance)) {
reject(new DSErrors.IA('"instance(id)" must be a string, number or object!'));
} else if (!DSUtils._a(relations)) {
reject(new DSErrors.IA('"relations" must be a string or an array!'));
} else {
(function () {
var _options = DSUtils._(definition, options);
var tasks = [];
DSUtils.forEach(definition.relationList, function (def) {
var relationName = def.relation;
var relationDef = definition.getResource(relationName);
var __options = DSUtils._(relationDef, options);
// relations can be loaded based on resource name or field name
if (!relations.length || DSUtils.contains(relations, relationName) || DSUtils.contains(relations, def.localField)) {
var task = undefined;
var params = {};
if (__options.allowSimpleWhere) {
params[def.foreignKey] = instance[definition.idAttribute];
} else {
params.where = {};
params.where[def.foreignKey] = {
'==': instance[definition.idAttribute]
};
}
if (def.type === 'hasMany') {
var orig = __options.orig();
if (def.localKeys) {
delete params[def.foreignKey];
var keys = DSUtils.get(instance, def.localKeys) || [];
keys = DSUtils._a(keys) ? keys : DSUtils.keys(keys);
params.where = _defineProperty({}, relationDef.idAttribute, {
'in': keys
});
orig.localKeys = keys;
}
task = relationDef.findAll(params, orig);
} else if (def.type === 'hasOne') {
if (def.localKey && DSUtils.get(instance, def.localKey)) {
task = relationDef.find(DSUtils.get(instance, def.localKey), __options.orig());
} else if (def.foreignKey) {
task = relationDef.findAll(params, __options.orig()).then(function (hasOnes) {
return hasOnes.length ? hasOnes[0] : null;
});
}
} else if (DSUtils.get(instance, def.localKey)) {
task = relationDef.find(DSUtils.get(instance, def.localKey), __options.orig());
}
if (task) {
tasks.push(task);
}
}
});
resolve(tasks);
})();
}
}).then(function (tasks) {
return DSUtils.Promise.all(tasks);
}).then(function () {
return instance;
});
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
/**
* Find expired items of the specified resource type and perform the configured action.
*
* @param resourceName The name of the type of resource of the items to reap.
* @param options Optional configuration.
* @returns The reaped items.
*/
module.exports = function reap(resourceName, options) {
var _this = this;
var DSUtils = _this.utils;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
return new DSUtils.Promise(function (resolve, reject) {
if (!definition) {
reject(new _this.errors.NER(resourceName));
} else {
options = DSUtils._(definition, options);
if (!options.hasOwnProperty('notify')) {
options.notify = false;
}
var items = [];
var now = new Date().getTime();
var expiredItem = undefined;
// find the expired items
while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) {
items.push(expiredItem.item);
delete expiredItem.item;
resource.expiresHeap.pop();
}
resolve(items);
}
}).then(function (items) {
// only hit lifecycle if there are items
if (items.length) {
definition.beforeReap(options, items);
if (options.notify) {
definition.emit('DS.beforeReap', definition, items);
}
}
if (options.reapAction === 'inject') {
(function () {
var timestamp = new Date().getTime();
DSUtils.forEach(items, function (item) {
resource.expiresHeap.push({
item: item,
timestamp: timestamp,
expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE
});
});
})();
} else if (options.reapAction === 'eject') {
DSUtils.forEach(items, function (item) {
definition.eject(item[definition.idAttribute]);
});
} else if (options.reapAction === 'refresh') {
var _ret2 = (function () {
var tasks = [];
DSUtils.forEach(items, function (item) {
tasks.push(definition.refresh(item[definition.idAttribute]));
});
return {
v: DSUtils.Promise.all(tasks)
};
})();
if (typeof _ret2 === 'object') return _ret2.v;
}
return items;
}).then(function (items) {
// only hit lifecycle if there are items
if (items.length) {
definition.afterReap(options, items);
if (options.notify) {
definition.emit('DS.afterReap', definition, items);
}
}
return items;
});
};
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
/**
* Save a single item in its present state.
*
* @param resourceName The name of the type of resource of the item.
* @param id The primary key of the item.
* @param options Optional congifuration.
* @returns The item, now saved.
*/
module.exports = function save(resourceName, id, options) {
var _this = this;
var DSUtils = _this.utils;
var DSErrors = _this.errors;
var definition = _this.definitions[resourceName];
var resource = _this.store[resourceName];
var item = undefined,
noChanges = undefined,
adapter = undefined;
return new DSUtils.Promise(function (resolve, reject) {
id = DSUtils.resolveId(definition, id);
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils._sn(id)) {
reject(DSUtils._snErr('id'));
} else if (!definition.get(id)) {
reject(new DSErrors.R('id "' + id + '" not found in cache!'));
} else {
item = definition.get(id);
options = DSUtils._(definition, options);
resolve(item);
}
})
// start lifecycle
.then(function (attrs) {
return options.beforeValidate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.validate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.afterValidate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.beforeUpdate.call(attrs, options, attrs);
}).then(function (attrs) {
if (options.notify) {
definition.emit('DS.beforeUpdate', definition, attrs);
}
// only send changed properties to the adapter
if (options.changesOnly) {
if (DSUtils.w) {
resource.observers[id].deliver();
}
var toKeep = [];
var changes = definition.changes(id);
for (var key in changes.added) {
toKeep.push(key);
}
for (key in changes.changed) {
toKeep.push(key);
}
changes = DSUtils.pick(attrs, toKeep);
// no changes? no save
if (DSUtils.isEmpty(changes)) {
// no changes, return
noChanges = true;
return attrs;
} else {
attrs = changes;
}
}
adapter = definition.getAdapterName(options);
return _this.adapters[adapter].update(definition, id, DSUtils.omit(attrs, options.omit), options);
}).then(function (data) {
return options.afterUpdate.call(data, options, data);
}).then(function (attrs) {
if (options.notify) {
definition.emit('DS.afterUpdate', definition, attrs);
}
if (noChanges) {
// no changes, just return
return attrs;
} else if (options.cacheResponse) {
// inject the reponse into the store, updating the item
var injected = definition.inject(attrs, options.orig());
var _id = injected[definition.idAttribute];
// mark the item as "saved"
resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]);
if (!definition.resetHistoryOnInject) {
resource.previousAttributes[_id] = DSUtils.copy(injected, null, null, null, definition.relationFields);
}
return injected;
} else {
// just return an instance
return definition.createInstance(attrs, options.orig());
}
}).then(function (item) {
return DSUtils.respond(item, { adapter: adapter }, options);
});
};
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
/**
* Update a single item using the supplied properties hash.
*
* @param resourceName The name of the type of resource of the item to update.
* @param id The primary key of the item to update.
* @param attrs The attributes with which to update the item.
* @param options Optional configuration.
* @returns The item, now updated.
*/
module.exports = function update(resourceName, id, attrs, options) {
var _this = this;
var DSUtils = _this.utils;
var DSErrors = _this.errors;
var definition = _this.definitions[resourceName];
var adapter = undefined;
return new DSUtils.Promise(function (resolve, reject) {
id = DSUtils.resolveId(definition, id);
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else if (!DSUtils._sn(id)) {
reject(DSUtils._snErr('id'));
} else {
options = DSUtils._(definition, options);
resolve(attrs);
}
})
// start lifecycle
.then(function (attrs) {
return options.beforeValidate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.validate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.afterValidate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.beforeUpdate.call(attrs, options, attrs);
}).then(function (attrs) {
if (options.notify) {
definition.emit('DS.beforeUpdate', definition, attrs);
}
adapter = definition.getAdapterName(options);
return _this.adapters[adapter].update(definition, id, DSUtils.omit(attrs, options.omit), options);
}).then(function (data) {
return options.afterUpdate.call(data, options, data);
}).then(function (attrs) {
if (options.notify) {
definition.emit('DS.afterUpdate', definition, attrs);
}
if (options.cacheResponse) {
// inject the updated item into the store
var injected = definition.inject(attrs, options.orig());
var resource = _this.store[resourceName];
var _id = injected[definition.idAttribute];
// mark the item as "saved"
resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]);
if (!definition.resetHistoryOnInject) {
resource.previousAttributes[_id] = DSUtils.copy(injected, null, null, null, definition.relationFields);
}
return injected;
} else {
// just return an instance
return definition.createInstance(attrs, options.orig());
}
}).then(function (item) {
return DSUtils.respond(item, { adapter: adapter }, options);
});
};
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
/**
* Update a collection of items using the supplied properties hash.
*
* @param resourceName The name of the type of resource of the items to update.
* @param attrs The attributes with which to update the item.
* @param params The criteria by which to select items to update. See http://www.js-data.io/docs/query-syntax
* @param options Optional configuration.
* @returns The updated items.
*/
module.exports = function updateAll(resourceName, attrs, params, options) {
var _this = this;
var DSUtils = _this.utils;
var DSErrors = _this.errors;
var definition = _this.definitions[resourceName];
var adapter = undefined;
return new DSUtils.Promise(function (resolve, reject) {
if (!definition) {
reject(new DSErrors.NER(resourceName));
} else {
options = DSUtils._(definition, options);
resolve(attrs);
}
})
// start lifecycle
.then(function (attrs) {
return options.beforeValidate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.validate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.afterValidate.call(attrs, options, attrs);
}).then(function (attrs) {
return options.beforeUpdate.call(attrs, options, attrs);
}).then(function (attrs) {
if (options.notify) {
definition.emit('DS.beforeUpdate', definition, attrs);
}
adapter = definition.getAdapterName(options);
return _this.adapters[adapter].updateAll(definition, DSUtils.omit(attrs, options.omit), params, options);
}).then(function (data) {
return options.afterUpdate.call(data, options, data);
}).then(function (data) {
if (options.notify) {
definition.emit('DS.afterUpdate', definition, attrs);
}
var origOptions = options.orig();
if (options.cacheResponse) {
var _ret = (function () {
// inject the updated items into the store
var injected = definition.inject(data, origOptions);
var resource = _this.store[resourceName];
// mark the items as "saved"
DSUtils.forEach(injected, function (i) {
var id = i[definition.idAttribute];
resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]);
if (!definition.resetHistoryOnInject) {
resource.previousAttributes[id] = DSUtils.copy(i, null, null, null, definition.relationFields);
}
});
return {
v: injected
};
})();
if (typeof _ret === 'object') return _ret.v;
} else {
var _ret2 = (function () {
// just return instances
var instances = [];
DSUtils.forEach(data, function (item) {
instances.push(definition.createInstance(item, origOptions));
});
return {
v: instances
};
})();
if (typeof _ret2 === 'object') return _ret2.v;
}
}).then(function (items) {
return DSUtils.respond(items, { adapter: adapter }, options);
});
};
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
/**
* Typecast a value to a String, using an empty string value for null or
* undefined.
*/
function toString(val){
return val == null ? '' : val.toString();
}
module.exports = toString;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
var toString = __webpack_require__(42);
var replaceAccents = __webpack_require__(44);
var removeNonWord = __webpack_require__(45);
var upperCase = __webpack_require__(20);
var lowerCase = __webpack_require__(46);
/**
* Convert string to camelCase text.
*/
function camelCase(str){
str = toString(str);
str = replaceAccents(str);
str = removeNonWord(str)
.replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces
.replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE
.replace(/\s+/g, '') //remove spaces
.replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase
return str;
}
module.exports = camelCase;
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
var toString = __webpack_require__(42);
/**
* Replaces all accented chars with regular ones
*/
function replaceAccents(str){
str = toString(str);
// verifies if the String has accents and replace them
if (str.search(/[\xC0-\xFF]/g) > -1) {
str = str
.replace(/[\xC0-\xC5]/g, "A")
.replace(/[\xC6]/g, "AE")
.replace(/[\xC7]/g, "C")
.replace(/[\xC8-\xCB]/g, "E")
.replace(/[\xCC-\xCF]/g, "I")
.replace(/[\xD0]/g, "D")
.replace(/[\xD1]/g, "N")
.replace(/[\xD2-\xD6\xD8]/g, "O")
.replace(/[\xD9-\xDC]/g, "U")
.replace(/[\xDD]/g, "Y")
.replace(/[\xDE]/g, "P")
.replace(/[\xE0-\xE5]/g, "a")
.replace(/[\xE6]/g, "ae")
.replace(/[\xE7]/g, "c")
.replace(/[\xE8-\xEB]/g, "e")
.replace(/[\xEC-\xEF]/g, "i")
.replace(/[\xF1]/g, "n")
.replace(/[\xF2-\xF6\xF8]/g, "o")
.replace(/[\xF9-\xFC]/g, "u")
.replace(/[\xFE]/g, "p")
.replace(/[\xFD\xFF]/g, "y");
}
return str;
}
module.exports = replaceAccents;
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
var toString = __webpack_require__(42);
// This pattern is generated by the _build/pattern-removeNonWord.js script
var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g;
/**
* Remove non-word chars.
*/
function removeNonWord(str){
str = toString(str);
return str.replace(PATTERN, '');
}
module.exports = removeNonWord;
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
var toString = __webpack_require__(42);
/**
* "Safer" String.toLowerCase()
*/
function lowerCase(str){
str = toString(str);
return str.toLowerCase();
}
module.exports = lowerCase;
/***/ }
/******/ ])
});
|
ajax/libs/can.js/4.0.0-pre.3/can.all.min.js | seogi1004/cdnjs | !function(e,t,n){var i=t.define,a=function(e){var n,i=e.split("."),a=t;for(n=0;n<i.length&&a;n++)a=a[i[n]];return a},r=function(e,n){var i,a,r,o=e.split("."),s=t;for(i=0;i<o.length-1;i++)(r=s[a=o[i]])||(r=s[a]={}),s=r;s[a=o[o.length-1]]=n},o=function(e){if(!e||!e.__esModule)return!1;var t={__esModule:!0,default:!0};for(var n in e)if(!t[n])return!1;return!0},s=function(e){return"require"===e[0]&&"exports"===e[1]&&"module"===e[2]},c=t.define&&t.define.modules||t._define&&t._define.modules||{},l=t.define=function(n,u,d){var p;"function"==typeof u&&(d=u,u=[]);var f,h=[];for(f=0;f<u.length;f++)h.push(e[u[f]]?a(e[u[f]]):c[u[f]]||a(u[f]));s(u)||!u.length&&d.length?(p={exports:{}},h[0]=function(t){return e[t]?a(e[t]):c[t]},h[1]=p.exports,h[2]=p):h[0]||"exports"!==u[0]?h[0]||"module"!==u[0]||(h[0]={id:n}):(p={exports:{}},h[0]=p.exports,"module"===u[1]&&(h[1]=p)),t.define=i;var v=d?d.apply(null,h):void 0;t.define=l,v=p&&p.exports?p.exports:v,c[n]=v;var m=e[n];m&&!a(m)&&(o(v)&&(v=v.default),r(m,v))};t.define.orig=i,t.define.modules=c,t.define.amd=!0,l("@loader",[],function(){var e=function(){};return{get:function(){return{prepareGlobal:e,retrieveGlobal:e}},global:t,__exec:function(e){n(e.source,t)}}})}({jquery:"jQuery","can-util/namespace":"can",kefir:"Kefir","validate.js":"validate",react:"React"},"object"==typeof self&&self.Object==Object?self:window,function(__$source__,__$global__){eval("(function() { "+__$source__+" \n }).call(__$global__);")}),define("can-namespace",function(e,t,n){n.exports={}}),define("can-util/namespace",["require","exports","module","can-namespace"],function(e,t,n){n.exports=e("can-namespace")}),define("can-assign",function(e,t,n){n.exports=function(e,t){for(var n in t)e[n]=t[n];return e}}),define("can-util/js/assign/assign",["require","exports","module","can-assign"],function(e,t,n){"use strict";n.exports=e("can-assign")}),define("can-util/js/is-function/is-function",function(e,t,n){"use strict";var i="undefined"!=typeof document&&"function"==typeof document.getElementsByTagName("body")?function(e){return"[object Function]"===Object.prototype.toString.call(e)}:function(e){return"function"==typeof e};n.exports=i}),define("can-util/js/is-plain-object/is-plain-object",function(e,t,n){"use strict";function i(e){return null!==e&&e==e.window}var a=Object.prototype.hasOwnProperty;n.exports=function(e){if(!e||"object"!=typeof e||e.nodeType||i(e)||e.constructor&&e.constructor.shortName)return!1;try{if(e.constructor&&!a.call(e,"constructor")&&!a.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(e){return!1}var t;for(t in e);return void 0===t||a.call(e,t)}}),define("can-util/js/deep-assign/deep-assign",["require","exports","module","can-util/js/is-function/is-function","can-util/js/is-plain-object/is-plain-object"],function(e,t,n){"use strict";function i(){var e,t,n,o,s,c,l=arguments[0]||{},u=1,d=arguments.length;for("object"==typeof l||a(l)||(l={}),d===u&&(l=this,--u);u<d;u++)if(null!=(e=arguments[u]))for(t in e)n=l[t],l!==(o=e[t])&&(o&&(r(o)||(s=Array.isArray(o)))?(s?(s=!1,c=n&&Array.isArray(n)?n:[]):c=n&&r(n)?n:{},l[t]=i(c,o)):void 0!==o&&(l[t]=o));return l}var a=e("can-util/js/is-function/is-function"),r=e("can-util/js/is-plain-object/is-plain-object");n.exports=i}),define("can-log",function(e,t,n){"use strict";t.warnTimeout=5e3,t.logLevel=0,t.warn=function(e){this.logLevel<2&&(Array.prototype.unshift.call(arguments,"WARN:"),"undefined"!=typeof console&&console.warn?this._logger("warn",Array.prototype.slice.call(arguments)):"undefined"!=typeof console&&console.log?this._logger("log",Array.prototype.slice.call(arguments)):window&&window.opera&&window.opera.postError&&window.opera.postError("CanJS WARNING: "+e))},t.log=function(e){this.logLevel<1&&("undefined"!=typeof console&&console.log?(Array.prototype.unshift.call(arguments,"INFO:"),this._logger("log",Array.prototype.slice.call(arguments))):window&&window.opera&&window.opera.postError&&window.opera.postError("CanJS INFO: "+e))},t.error=function(e){this.logLevel<1&&("undefined"!=typeof console&&console.error?(Array.prototype.unshift.call(arguments,"ERROR:"),this._logger("error",Array.prototype.slice.call(arguments))):window&&window.opera&&window.opera.postError&&window.opera.postError("ERROR: "+e))},t._logger=function(e,t){try{console[e].apply(console,t)}catch(n){console[e](t)}}}),define("can-log/dev/dev",["require","exports","module","can-log"],function(e,t,n){"use strict";var i=e("can-log");n.exports={warnTimeout:5e3,logLevel:0,stringify:function(e){return JSON.stringify(e,function(e,t){return void 0===t?"/* void(undefined) */":t}," ").replace(/"\/\* void\(undefined\) \*\/"/g,"undefined")},warn:function(){i.warn.apply(this,arguments)},log:function(){i.log.apply(this,arguments)},error:function(){i.error.apply(this,arguments)},_logger:i._logger}}),define("can-util/js/dev/dev",["require","exports","module","can-log/dev/dev"],function(e,t,n){"use strict";n.exports=e("can-log/dev/dev")}),define("can-util/js/is-array-like/is-array-like",function(e,t,n){"use strict";n.exports=function(e){var t=typeof e;if("string"===t)return!0;if("number"===t)return!1;var n=e&&"boolean"!==t&&"number"!=typeof e&&"length"in e&&e.length;return"function"!=typeof e&&(0===n||"number"==typeof n&&n>0&&n-1 in e)}}),define("can-symbol",["require","exports","module","can-namespace"],function(e,t,n){!function(e,t,n,i){var a,r=t("can-namespace");if("undefined"!=typeof Symbol&&"function"==typeof Symbol.for)a=Symbol;else{var o=0,s={},c={};(a=function(e){var t="@@symbol"+o+++e,n={};return Object.defineProperties(n,{toString:{value:function(){return t}}}),n}).for=function(e){var t=s[e];return t||(t=s[e]=a(e),c[t]=e),t},a.keyFor=function(e){return c[e]},["hasInstance","isConcatSpreadable","iterator","match","prototype","replace","search","species","split","toPrimitive","toStringTag","unscopables"].forEach(function(e){a[e]=a.for(e)})}["isMapLike","isListLike","isValueLike","isFunctionLike","getOwnKeys","getOwnKeyDescriptor","proto","getOwnEnumerableKeys","hasOwnKey","size","getName","getIdentity","assignDeep","updateDeep","getValue","setValue","getKeyValue","setKeyValue","updateValues","addValue","removeValues","apply","new","onValue","offValue","onKeyValue","offKeyValue","getKeyDependencies","getValueDependencies","keyHasDependencies","valueHasDependencies","onKeys","onKeysAdded","onKeysRemoved"].forEach(function(e){a.for("can."+e)}),i.exports=r.Symbol=a}(0,e,0,n)}),define("can-util/js/is-iterable/is-iterable",["require","exports","module","can-symbol"],function(e,t,n){"use strict";var i=e("can-symbol");n.exports=function(e){return e&&!!e[i.iterator||i.for("iterator")]}}),define("can-util/js/each/each",["require","exports","module","can-util/js/is-array-like/is-array-like","can-util/js/is-iterable/is-iterable","can-symbol"],function(e,t,n){"use strict";var i=e("can-util/js/is-array-like/is-array-like"),a=Object.prototype.hasOwnProperty,r=e("can-util/js/is-iterable/is-iterable"),o=e("can-symbol");n.exports=function(e,t,n){var s,c,l,u=0;if(e)if(i(e))for(c=e.length;u<c&&(l=e[u],!1!==t.call(n||l,l,u,e));u++);else if(r(e))for(var d,p,f=e[o.iterator||o.for("iterator")]();!(d=f.next()).done;)p=d.value,t.call(n||e,Array.isArray(p)?p[1]:p,p[0]);else if("object"==typeof e)for(s in e)if(a.call(e,s)&&!1===t.call(n||e[s],e[s],s,e))break;return e}}),define("can-util/js/make-array/make-array",["require","exports","module","can-util/js/each/each","can-util/js/is-array-like/is-array-like"],function(e,t,n){"use strict";var i=e("can-util/js/each/each"),a=e("can-util/js/is-array-like/is-array-like");n.exports=function(e){var t=[];return a(e)?i(e,function(e,n){t[n]=e}):(0===e||e)&&t.push(e),t}}),define("can-util/js/is-container/is-container",function(e,t,n){"use strict";n.exports=function(e){return/^f|^o/.test(typeof e)}}),define("can-util/js/get/get",["require","exports","module","can-util/js/is-container/is-container"],function(e,t,n){"use strict";var i=e("can-util/js/is-container/is-container");n.exports=function(e,t){var n,a,r=void 0!==t?(t+"").replace(/\[/g,".").replace(/]/g,"").split("."):[],o=r.length;if(!o)return e;for(n=e,a=0;a<o&&i(n);a++)n=n[r[a]];return n}}),define("can-util/js/is-array/is-array",["require","exports","module","can-log/dev/dev"],function(e,t,n){"use strict";var i=e("can-log/dev/dev"),a=!1;n.exports=function(e){return a||(i.warn("js/is-array/is-array is deprecated; use Array.isArray"),a=!0),Array.isArray(e)}}),define("can-util/js/string/string",["require","exports","module","can-util/js/get/get","can-util/js/is-container/is-container","can-log/dev/dev","can-util/js/is-array/is-array"],function(e,t,n){"use strict";var i=e("can-util/js/get/get"),a=e("can-util/js/is-container/is-container"),r=e("can-log/dev/dev"),o=e("can-util/js/is-array/is-array"),s=/\=\=/,c=/([A-Z]+)([A-Z][a-z])/g,l=/([a-z\d])([A-Z])/g,u=/([a-z\d])([A-Z])/g,d=/\{([^\}]+)\}/g,p=/"/g,f=/'/g,h=/-+(.)?/g,v=/[a-z][A-Z]/g,m=function(e){return""+(null===e||void 0===e||isNaN(e)&&""+e=="NaN"?"":e)},g=function(e,t){for(var n=t?t.replace(/\[/g,".").replace(/]/g,"").split("."):[],i=e,a=0;a<n.length-1;a++)i&&(i=i[n[a]]);i&&delete i[n[n.length-1]]},y={esc:function(e){return m(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(p,""").replace(f,"'")},getObject:function(e,t){r.warn("string.getObject is deprecated, please use can-util/js/get/get instead.");for(var n,a=(t=o(t)?t:[t||window]).length,s=0;s<a;s++)if(n=i(t[s],e))return n},capitalize:function(e,t){return e.charAt(0).toUpperCase()+e.slice(1)},camelize:function(e){return m(e).replace(h,function(e,t){return t?t.toUpperCase():""})},hyphenate:function(e){return m(e).replace(v,function(e,t){return e.charAt(0)+"-"+e.charAt(1).toLowerCase()})},underscore:function(e){return e.replace(s,"/").replace(c,"$1_$2").replace(l,"$1_$2").replace(u,"_").toLowerCase()},sub:function(e,t,n){var r=[];return e=e||"",r.push(e.replace(d,function(e,o){var s=i(t,o);return!0===n&&g(t,o),void 0===s||null===s?(r=null,""):a(s)&&r?(r.push(s),""):""+s})),null===r?r:r.length<=1?r[0]:r},replacer:d,undHash:/_|-/};n.exports=y}),define("can-construct",["require","exports","module","can-util/js/assign/assign","can-util/js/deep-assign/deep-assign","can-util/js/dev/dev","can-util/js/make-array/make-array","can-namespace","can-util/js/string/string"],function(e,t,n){"use strict";var i,a=e("can-util/js/assign/assign"),r=e("can-util/js/deep-assign/deep-assign"),o=e("can-util/js/dev/dev"),s=e("can-util/js/make-array/make-array"),c=e("can-namespace"),l=e("can-util/js/string/string"),u={abstract:!0,boolean:!0,break:!0,byte:!0,case:!0,catch:!0,char:!0,class:!0,const:!0,continue:!0,debugger:!0,default:!0,delete:!0,do:!0,double:!0,else:!0,enum:!0,export:!0,extends:!0,false:!0,final:!0,finally:!0,float:!0,for:!0,function:!0,goto:!0,if:!0,implements:!0,import:!0,in:!0,instanceof:!0,int:!0,interface:!0,let:!0,long:!0,native:!0,new:!0,null:!0,package:!0,private:!0,protected:!0,public:!0,return:!0,short:!0,static:!0,super:!0,switch:!0,synchronized:!0,this:!0,throw:!0,throws:!0,transient:!0,true:!0,try:!0,typeof:!0,var:!0,void:!0,volatile:!0,while:!0,with:!0},d=/[^A-Z0-9_]/gi,p=0,f=function(e){return function(t,n){return(t in e?e[t]:e[t]=new Function("__","function "+t+"(){return __.apply(this,arguments)};return "+t))(n)}}({}),h=function(){if(arguments.length)return h.extend.apply(h,arguments)};try{Object.getOwnPropertyDescriptor({}),i=!0}catch(e){i=!1}var v=function(e,t){var n=Object.getOwnPropertyDescriptor(e,t);return n&&(n.get||n.set)?n:null};a(h,{constructorExtends:!0,newInstance:function(){var e,t=this.instance();if(t.setup){if(Object.defineProperty(t,"__inSetup",{configurable:!0,enumerable:!1,value:!0,writable:!0}),(e=t.setup.apply(t,arguments))instanceof h.ReturnValue)return e.value;t.__inSetup=!1}return t.init&&t.init.apply(t,e||arguments),t},_inherit:i?function(e,t,n){n=n||e;var i;for(var a in e)(i=v(e,a))?this._defineProperty(n,t,a,i):h._overwrite(n,t,a,e[a])}:function(e,t,n){n=n||e;for(var i in e)h._overwrite(n,t,i,e[i])},_defineProperty:function(e,t,n,i){Object.defineProperty(e,n,i)},_overwrite:function(e,t,n,i){Object.defineProperty(e,n,{value:i,configurable:!0,enumerable:!0,writable:!0})},setup:function(e){this.defaults=r(!0,{},e.defaults,this.defaults)},instance:function(){p=1;var e=new this;return p=0,e},extend:function(e,t,n){function i(){if(!p)return(!this||this.constructor!==m&&arguments.length&&m.constructorExtends)&&o.warn("can/construct/construct.js: extending a Construct without calling extend"),this&&this.constructor===m||!arguments.length||!m.constructorExtends?m.newInstance.apply(m,arguments):m.extend.apply(m,arguments)}var r=e,c=t,v=n;"string"!=typeof r&&(v=c,c=r,r=null),v||(v=c,c=null),v=v||{};var m,g,y=this,b=this.prototype;g=this.instance(),h._inherit(v,b,g),r||(c&&c.shortName?r=c.shortName:this.shortName&&(r=this.shortName));var w=r?r.replace(d,"_"):"Constructor";u[w]&&(w=l.capitalize(w)),m="function"==typeof f?f(w,i):function(){return i.apply(this,arguments)};for(var k in y)y.hasOwnProperty(k)&&(m[k]=y[k]);h._inherit(c,y,m),a(m,{constructor:m,prototype:g}),void 0!==r&&(m.shortName=r),m.prototype.constructor=m;var x=[y].concat(s(arguments)),j=m.setup.apply(m,x);return m.init&&m.init.apply(m,j||x),m},ReturnValue:function(e){this.value=e}}),h.prototype.setup=function(){},h.prototype.init=function(){},n.exports=c.Construct=h}),define("can-cid",["require","exports","module","can-namespace"],function(e,t,n){var i=e("can-namespace"),a=0,r="can"+new Date,o=function(e,t){var n=e.nodeName?r:"_cid";return e[n]||(a++,e[n]=(t||"")+a),e[n]};if(o.domExpando=r,o.get=function(e){var t=typeof e;return null!==t&&("object"===t||"function"===t)?o(e):t+":"+e},i.cid)throw new Error("You can't have two versions of can-cid, check your dependencies");n.exports=i.cid=o}),define("can-dom-data-state",["require","exports","module","can-namespace","can-cid"],function(e,t,n){"use strict";var i=e("can-namespace"),a=e("can-cid"),r={},o=function(e){for(var t in e)return!1;return!0},s=function(e,t){var n=a(this),i=r[n],o=!1;return r[n]||(o=!0,i=r[n]={}),void 0!==e&&(i[e]=t),o},c=function(){var e=a.get(this),t=!1;return e&&r[e]&&(t=!0,delete r[e]),t},l={_data:r,getCid:function(){return a.get(this)},cid:function(){return a(this)},expando:a.domExpando,get:function(e){var t=a.get(this),n=t&&r[t];return void 0===e?n||s(this):n&&n[e]},set:s,clean:function(e){var t=a.get(this),n=r[t];n&&n[e]&&delete n[e],o(n)&&c.call(this)},delete:c};if(i.domDataState)throw new Error("You can't have two versions of can-dom-data-state, check your dependencies");n.exports=i.domDataState=l}),define("can-reflect/reflections/helpers",["require","exports","module","can-symbol"],function(e,t,n){var i=e("can-symbol");n.exports={makeGetFirstSymbolValue:function(e){var t=e.map(function(e){return i.for(e)}),n=t.length;return function(e){for(var i=-1;++i<n;)if(void 0!==e[t[i]])return e[t[i]]}},hasLength:function(e){var t=typeof e,n=e&&"boolean"!==t&&"number"!=typeof e&&"length"in e&&e.length;return"function"!=typeof e&&(0===n||"number"==typeof n&&n>0&&n-1 in e)}}}),define("can-reflect/reflections/type/type",["require","exports","module","can-symbol","can-reflect/reflections/helpers"],function(e,t,n){function i(e){var t=typeof e;return null==e||"function"!==t&&"object"!==t}function a(e){if(!e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);if(t===Object.prototype||null===t)return!0;var n=p.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&f.call(n)===h}var r,o=e("can-symbol"),s=e("can-reflect/reflections/helpers"),c=Object.getOwnPropertyNames(function(){}.prototype),l=Object.getPrototypeOf(function(){}.prototype),u=s.makeGetFirstSymbolValue(["can.new","can.apply"]),d=s.makeGetFirstSymbolValue(["can.onValue","can.onKeyValue","can.onKeys","can.onKeysAdded"]);if("undefined"!=typeof Symbol&&"function"==typeof Symbol.for)r=function(e){return"symbol"==typeof e};else{r=function(e){return"object"==typeof e&&!Array.isArray(e)&&"@@symbol"===e.toString().substr(0,"@@symbol".length)}}var p=Object.prototype.hasOwnProperty,f=Function.prototype.toString,h=f.call(Object);n.exports={isConstructorLike:function(e){var t=e[o.for("can.new")];if(void 0!==t)return t;if("function"!=typeof e)return!1;var n=e.prototype;if(!n)return!1;if(l!==Object.getPrototypeOf(n))return!0;var i=Object.getOwnPropertyNames(n);if(i.length===c.length){for(var a=0,r=i.length;a<r;a++)if(i[a]!==c[a])return!0;return!1}return!0},isFunctionLike:function(e){var t,n=e[o.for("can.isFunctionLike")];return void 0!==n?n:void 0!==(t=u(e))?!!t:"function"==typeof e},isListLike:function(e){var t;if("string"==typeof e)return!0;if(i(e))return!1;if(void 0!==(t=e[o.for("can.isListLike")]))return t;var n=e[o.iterator];return void 0!==n?!!n:!!Array.isArray(e)||s.hasLength(e)},isMapLike:function(e){if(i(e))return!1;var t=e[o.for("can.isMapLike")];if(void 0!==t)return!!t;var n=e[o.for("can.getKeyValue")];return void 0===n||!!n},isObservableLike:function(e){if(i(e))return!1;var t=d(e);return void 0!==t&&!!t},isPrimitive:i,isBuiltIn:function(e){return!!(i(e)||Array.isArray(e)||a(e)||"[object Object]"!==Object.prototype.toString.call(e)&&-1!==Object.prototype.toString.call(e).indexOf("[object "))},isValueLike:function(e){var t;if(i(e))return!0;if(void 0!==(t=e[o.for("can.isValueLike")]))return t;var n=e[o.for("can.getValue")];return void 0!==n?!!n:void 0},isSymbolLike:r,isMoreListLikeThanMapLike:function(e){if(Array.isArray(e))return!0;var t=e[o.for("can.isMoreListLikeThanMapLike")];if(void 0!==t)return t;var n=this.isListLike(e),i=this.isMapLike(e);return!(!n||i)||!(!n&&i)&&void 0},isIteratorLike:function(e){return e&&"object"==typeof e&&"function"==typeof e.next&&0===e.next.length},isPromise:function(e){return e instanceof Promise||"[object Promise]"===Object.prototype.toString.call(e)},isPlainObject:a}}),define("can-reflect/reflections/call/call",["require","exports","module","can-symbol","can-reflect/reflections/type/type"],function(e,t,n){var i=e("can-symbol"),a=e("can-reflect/reflections/type/type");n.exports={call:function(e,t){var n=[].slice.call(arguments,2),a=e[i.for("can.apply")];return a?a.call(e,t,n):e.apply(t,n)},apply:function(e,t,n){var a=e[i.for("can.apply")];return a?a.call(e,t,n):e.apply(t,n)},new:function(e){var t=[].slice.call(arguments,1),n=e[i.for("can.new")];if(n)return n.apply(e,t);var r=Object.create(e.prototype),o=e.apply(r,t);return a.isPrimitive(o)?r:o}}}),define("can-reflect/reflections/get-set/get-set",["require","exports","module","can-symbol","can-reflect/reflections/type/type"],function(e,t,n){var i=e("can-symbol"),a=e("can-reflect/reflections/type/type"),r=i.for("can.setKeyValue"),o=i.for("can.getKeyValue"),s=i.for("can.getValue"),c=i.for("can.setValue"),l={setKeyValue:function(e,t,n){if(a.isSymbolLike(t))"symbol"==typeof t?e[t]=n:Object.defineProperty(e,t,{enumerable:!1,configurable:!0,value:n,writable:!0});else{var i=e[r];if(void 0!==i)return i.call(e,t,n);e[t]=n}},getKeyValue:function(e,t){var n=e[o];return n?n.call(e,t):e[t]},deleteKeyValue:function(e,t){var n=e[i.for("can.deleteKeyValue")];if(n)return n.call(e,t);delete e[t]},getValue:function(e){if(a.isPrimitive(e))return e;var t=e[s];return t?t.call(e):e},setValue:function(e,t){var n=e&&e[c];if(n)return n.call(e,t);throw new Error("can-reflect.setValue - Can not set value.")},splice:function(e,t,n,a){var r;if("number"!=typeof n){var o=e[i.for("can.updateValues")];if(o)return o.call(e,t,n,a);r=n.length}else r=n;var s=e[i.for("can.splice")];return s?s.call(e,t,r,a):[].splice.apply(e,[t,r].concat(a))},addValues:function(e,t,n){var a=e[i.for("can.addValues")];return a?a.call(e,t,n):Array.isArray(e)&&void 0===n?e.push.apply(e,t):l.splice(e,n,[],t)},removeValues:function(e,t,n){var a=e[i.for("can.removeValues")];if(a)return a.call(e,t,n);{if(!Array.isArray(e)||void 0!==n)return l.splice(e,n,t,[]);t.forEach(function(t){var n=e.indexOf(t);n>=0&&e.splice(n,1)})}}};l.get=l.getKeyValue,l.set=l.setKeyValue,l.delete=l.deleteKeyValue,n.exports=l}),define("can-reflect/reflections/observe/observe",["require","exports","module","can-symbol"],function(e,t,n){function i(e,t){return function(n,i,a,o){var s=n[r.for(e)];return void 0!==s?s.call(n,i,a,o):this[t].apply(this,arguments)}}function a(e,t){return function(n){var i=n[r.for(e)];if(void 0!==i){var a=o.call(arguments,1);return i.apply(n,a)}throw new Error(t)}}var r=e("can-symbol"),o=[].slice;n.exports={onKeyValue:i("can.onKeyValue","onEvent"),offKeyValue:i("can.offKeyValue","offEvent"),onKeys:a("can.onKeys","can-reflect: can not observe an onKeys event"),onKeysAdded:a("can.onKeysAdded","can-reflect: can not observe an onKeysAdded event"),onKeysRemoved:a("can.onKeysRemoved","can-reflect: can not unobserve an onKeysRemoved event"),getKeyDependencies:a("can.getKeyDependencies","can-reflect: can not determine dependencies"),keyHasDependencies:a("can.keyHasDependencies","can-reflect: can not determine if this has key dependencies"),onValue:a("can.onValue","can-reflect: can not observe value change"),offValue:a("can.offValue","can-reflect: can not unobserve value change"),getValueDependencies:a("can.getValueDependencies","can-reflect: can not determine dependencies"),valueHasDependencies:a("can.valueHasDependencies","can-reflect: can not determine if value has dependencies"),onEvent:function(e,t,n,i){if(e){var a=e[r.for("can.onEvent")];if(void 0!==a)return a.call(e,t,n,i);e.addEventListener&&e.addEventListener(t,n,i)}},offEvent:function(e,t,n,i){if(e){var a=e[r.for("can.offEvent")];if(void 0!==a)return a.call(e,t,n,i);e.removeEventListener&&e.removeEventListener(t,n,i)}},setPriority:function(e,t){if(e){var n=e[r.for("can.setPriority")];if(void 0!==n)return n.call(e,t),!0}return!1},getPriority:function(e){if(e){var t=e[r.for("can.getPriority")];if(void 0!==t)return t.call(e)}}}}),define("can-reflect/reflections/shape/shape",["require","exports","module","can-symbol","can-reflect/reflections/get-set/get-set","can-reflect/reflections/type/type","can-reflect/reflections/helpers"],function(e,t,n){function i(e){return!!d.isPrimitive(e)||!w(e)&&(d.isBuiltIn(e)&&!d.isPlainObject(e))}function a(e,t){return function(n,a){if(i(n))return n;var r;a&&!b&&(b={unwrap:new a,serialize:new a},r=!0);var o;if(d.isValueLike(n))o=this[e](u.getValue(n));else{var s=d.isIteratorLike(n)||d.isMoreListLikeThanMapLike(n);if(o=s?[]:{},b){if(b[e].has(n))return b[e].get(n);b[e].set(n,o)}for(var c=0,l=t.length;c<l;c++){var p=n[t[c]];if(p){var f=p.call(n,o);return r&&(b=null),f}}"function"==typeof obj?(b&&b[e].set(n,n),o=n):s?this.eachIndex(n,function(t,n){o[n]=this[e](t)},this):this.eachKey(n,function(t,n){o[n]=this[e](t)},this)}return r&&(b=null),o}}function r(e,t){var n=e[e.length-1];if(n&&n.deleteCount===n.insert.length&&t.index-n.index===n.deleteCount)return n.insert.push.apply(n.insert,t.insert),void(n.deleteCount+=t.deleteCount);e.push(t)}function o(e,t,n){var i=this.toArray(t),a=[],o=-1;this.eachIndex(e,function(e,t){if(o=t,t>=i.length)return n||r(a,{index:t,deleteCount:i.length-t+1,insert:[]}),!1;var s=i[t];d.isPrimitive(e)||d.isPrimitive(s)||!1===k(e)?r(a,{index:t,deleteCount:1,insert:[s]}):this.updateDeep(e,s)},this),i.length>o&&r(a,{index:o+1,deleteCount:0,insert:i.slice(o+1)});for(var s=0,c=a.length;s<c;s++){var l=a[s];u.splice(e,l.index,l.deleteCount,l.insert)}return e}var s,c,l=e("can-symbol"),u=e("can-reflect/reflections/get-set/get-set"),d=e("can-reflect/reflections/type/type"),p=e("can-reflect/reflections/helpers"),f=function(e){return function(){var t=[this];return t.push.apply(t,arguments),e.apply(null,t)}},h=l.for("can.getKeyValue"),v=f(u.getKeyValue),m=l.for("can.setKeyValue"),g=f(u.setKeyValue),y=l.for("can.size"),b=null,w=p.makeGetFirstSymbolValue(["can.updateDeep","can.assignDeep","can.setKeyValue"]),k=function(e){return d.isPlainObject(e)||Array.isArray(e)||!!w(e)};try{Object.keys(1),c=Object.keys}catch(e){c=function(e){return d.isPrimitive(e)?[]:Object.keys(e)}}var x;x="undefined"!=typeof Map?function(e){var t=new Map;return s.eachIndex(e,function(e){t.set(e,!0)}),t}:function(e){var t={};return e.forEach(function(e){t[e]=!0}),{get:function(e){return t[e]},set:function(e,n){t[e]=n},keys:function(){return e}}};var j=function(e){var t=e[l.for("can.hasOwnKey")];if(t)return t.bind(e);var n=x(s.getOwnEnumerableKeys(e));return function(e){return n.get(e)}};(s={each:function(e,t,n){return d.isIteratorLike(e)||d.isMoreListLikeThanMapLike(e)?this.eachIndex(e,t,n):this.eachKey(e,t,n)},eachIndex:function(e,t,n){if(Array.isArray(e))return this.eachListLike(e,t,n);var i,a=e[l.iterator];if(d.isIteratorLike(e)?i=e:a&&(i=a.call(e)),i)for(var r,o=0;!(r=i.next()).done&&!1!==t.call(n||e,r.value,o++,e););else this.eachListLike(e,t,n);return e},eachListLike:function(e,t,n){var i=-1,a=e.length;if(void 0===a){var r=e[y];if(!r)throw new Error("can-reflect: unable to iterate.");a=r.call(e)}for(;++i<a;){var o=e[i];if(!1===t.call(n||o,o,i,e))break}return e},toArray:function(e){var t=[];return this.each(e,function(e){t.push(e)}),t},eachKey:function(e,t,n){if(e){var i=this.getOwnEnumerableKeys(e),a=e[h]||v;return this.eachIndex(i,function(i){var r=a.call(e,i);return t.call(n||e,r,i,e)})}return e},hasOwnKey:function(e,t){var n=e[l.for("can.hasOwnKey")];if(n)return n.call(e,t);var i=e[l.for("can.getOwnKeys")];if(i){var a=!1;return this.eachIndex(i.call(e),function(e){if(e===t)return a=!0,!1}),a}return e.hasOwnProperty(t)},getOwnEnumerableKeys:function(e){var t=e[l.for("can.getOwnEnumerableKeys")];if(t)return t.call(e);if(e[l.for("can.getOwnKeys")]&&e[l.for("can.getOwnKeyDescriptor")]){var n=[];return this.eachIndex(this.getOwnKeys(e),function(t){this.getOwnKeyDescriptor(e,t).enumerable&&n.push(t)},this),n}return c(e)},getOwnKeys:function(e){var t=e[l.for("can.getOwnKeys")];return t?t.call(e):Object.getOwnPropertyNames(e)},getOwnKeyDescriptor:function(e,t){var n=e[l.for("can.getOwnKeyDescriptor")];return n?n.call(e,t):Object.getOwnPropertyDescriptor(e,t)},unwrap:a("unwrap",[l.for("can.unwrap")]),serialize:a("serialize",[l.for("can.serialize"),l.for("can.unwrap")]),assignMap:function(e,t){var n=j(e),i=e[h]||v,a=e[m]||g;return this.eachKey(t,function(t,r){n(r)&&i.call(e,r)===t||a.call(e,r,t)}),e},assignList:function(e,t){var n=this.toArray(t);return u.splice(e,0,n,n),e},assign:function(e,t){return d.isIteratorLike(t)||d.isMoreListLikeThanMapLike(t)?this.assignList(e,t):this.assignMap(e,t),e},assignDeepMap:function(e,t){var n=j(e),i=e[h]||v,a=e[m]||g;return this.eachKey(t,function(t,r){if(n(r)){var o=i.call(e,r);t===o||(d.isPrimitive(o)||d.isPrimitive(t)||!1===k(o)?a.call(e,r,t):this.assignDeep(o,t))}else u.setKeyValue(e,r,t)},this),e},assignDeepList:function(e,t){return o.call(this,e,t,!0)},assignDeep:function(e,t){var n=e[l.for("can.assignDeep")];return n?n.call(e,t):d.isMoreListLikeThanMapLike(t)?this.assignDeepList(e,t):this.assignDeepMap(e,t),e},updateMap:function(e,t){var n=x(this.getOwnEnumerableKeys(t)),i=t[h]||v,a=e[m]||g;return this.eachKey(e,function(r,o){if(n.get(o)){n.set(o,!1);var s=i.call(t,o);s!==r&&a.call(e,o,s)}else u.deleteKeyValue(e,o)},this),this.eachIndex(n.keys(),function(r){n.get(r)&&a.call(e,r,i.call(t,r))}),e},updateList:function(e,t){var n=this.toArray(t);return u.splice(e,0,e,n),e},update:function(e,t){return d.isIteratorLike(t)||d.isMoreListLikeThanMapLike(t)?this.updateList(e,t):this.updateMap(e,t),e},updateDeepMap:function(e,t){var n=x(this.getOwnEnumerableKeys(t)),i=t[h]||v,a=e[m]||g;return this.eachKey(e,function(r,o){if(n.get(o)){n.set(o,!1);var s=i.call(t,o);d.isPrimitive(r)||d.isPrimitive(s)||!1===k(r)?a.call(e,o,s):this.updateDeep(r,s)}else u.deleteKeyValue(e,o)},this),this.eachIndex(n.keys(),function(r){n.get(r)&&a.call(e,r,i.call(t,r))}),e},updateDeepList:function(e,t){return o.call(this,e,t)},updateDeep:function(e,t){var n=e[l.for("can.updateDeep")];return n?n.call(e,t):d.isMoreListLikeThanMapLike(t)?this.updateDeepList(e,t):this.updateDeepMap(e,t),e},in:function(){},getAllEnumerableKeys:function(){},getAllKeys:function(){},assignSymbols:function(e,t){return this.eachKey(t,function(t,n){var i=d.isSymbolLike(l[n])?l[n]:l.for(n);u.setKeyValue(e,i,t)}),e},isSerializable:i,size:function(e){var t=e[y],n=0;if(t)return t.call(e);if(p.hasLength(e))return e.length;if(d.isListLike(e))return this.each(e,function(){n++}),n;if(e){for(var i in e)e.hasOwnProperty(i)&&n++;return n}}}).keys=s.getOwnEnumerableKeys,n.exports=s}),define("can-reflect/reflections/get-name/get-name",["require","exports","module","can-symbol","can-reflect/reflections/type/type"],function(e,t,n){function i(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e)return e.name;if(e.constructor&&e!==e.constructor){var n=i(e.constructor);if(n){if(r.isValueLike(e))return n+"<>";if(r.isMoreListLikeThanMapLike(e))return n+"[]";if(r.isMapLike(e))return n+"{}"}}}var a=e("can-symbol"),r=e("can-reflect/reflections/type/type"),o=a.for("can.getName");n.exports={setName:function(e,t){if("function"!=typeof t){var n=t;t=function(){return n}}Object.defineProperty(e,o,{value:t})},getName:i}}),define("can-reflect/types/map",["require","exports","module","can-reflect/reflections/shape/shape","can-symbol"],function(e,t,n){var i=e("can-reflect/reflections/shape/shape"),a=e("can-symbol");"undefined"!=typeof Map&&(i.assignSymbols(Map.prototype,{"can.getOwnEnumerableKeys":Map.prototype.keys,"can.setKeyValue":Map.prototype.set,"can.getKeyValue":Map.prototype.get,"can.deleteKeyValue":Map.prototype.delete,"can.hasOwnKey":Map.prototype.has}),"function"!=typeof Map.prototype.keys&&(Map.prototype.keys=Map.prototype[a.for("can.getOwnEnumerableKeys")]=function(){var e=[],t=0;return this.forEach(function(t,n){e.push(n)}),{next:function(){return{value:e[t],done:t++===e.length}}}})),"undefined"!=typeof WeakMap&&i.assignSymbols(WeakMap.prototype,{"can.getOwnEnumerableKeys":function(){throw new Error("can-reflect: WeakMaps do not have enumerable keys.")},"can.setKeyValue":WeakMap.prototype.set,"can.getKeyValue":WeakMap.prototype.get,"can.deleteKeyValue":WeakMap.prototype.delete,"can.hasOwnKey":WeakMap.prototype.has})}),define("can-reflect/types/set",["require","exports","module","can-reflect/reflections/shape/shape","can-symbol"],function(e,t,n){var i=e("can-reflect/reflections/shape/shape"),a=e("can-symbol");"undefined"!=typeof Set&&(i.assignSymbols(Set.prototype,{"can.isMoreListLikeThanMapLike":!0,"can.updateValues":function(e,t,n){t!==n&&i.each(t,function(e){this.delete(e)},this),i.each(n,function(e){this.add(e)},this)},"can.size":function(){return this.size}}),"function"!=typeof Set.prototype[a.iterator]&&(Set.prototype[a.iterator]=function(){var e=[],t=0;return this.forEach(function(t){e.push(t)}),{next:function(){return{value:e[t],done:t++===e.length}}}})),"undefined"!=typeof WeakSet&&i.assignSymbols(WeakSet.prototype,{"can.isListLike":!0,"can.isMoreListLikeThanMapLike":!0,"can.updateValues":function(e,t,n){t!==n&&i.each(t,function(e){this.delete(e)},this),i.each(n,function(e){this.add(e)},this)},"can.size":function(){throw new Error("can-reflect: WeakSets do not have enumerable keys.")}})}),define("can-reflect",["require","exports","module","can-reflect/reflections/call/call","can-reflect/reflections/get-set/get-set","can-reflect/reflections/observe/observe","can-reflect/reflections/shape/shape","can-reflect/reflections/type/type","can-reflect/reflections/get-name/get-name","can-namespace","can-reflect/types/map","can-reflect/types/set"],function(e,t,n){var i=e("can-reflect/reflections/call/call"),a=e("can-reflect/reflections/get-set/get-set"),r=e("can-reflect/reflections/observe/observe"),o=e("can-reflect/reflections/shape/shape"),s=e("can-reflect/reflections/type/type"),c=e("can-reflect/reflections/get-name/get-name"),l=e("can-namespace"),u={};[i,a,r,o,s,c].forEach(function(e){for(var t in e)if(u[t]=e[t],"function"==typeof e[t]){var n=Object.getOwnPropertyDescriptor(e[t],"name");(!n||n.writable&&n.configurable)&&Object.defineProperty(e[t],"name",{value:"canReflect."+t})}}),e("can-reflect/types/map"),e("can-reflect/types/set"),n.exports=l.Reflect=u}),define("can-globals/can-globals-proto",["require","exports","module","can-reflect"],function(e,t,n){!function(e,t,n,i){"use strict";function a(e,t){var n=this.eventHandlers[e];if(n)for(var i=n.slice(),a=0;a<i.length;a++)i[a](t)}function r(){this.eventHandlers={},this.properties={}}var o=t("can-reflect");r.prototype.define=function(e,t,n){return void 0===n&&(n=!0),this.properties[e]||(this.properties[e]={default:t,value:t,enableCache:n}),this},r.prototype.getKeyValue=function(e){var t=this.properties[e];if(t)return"function"==typeof t.value?t.cachedValue?t.cachedValue:t.enableCache?(t.cachedValue=t.value(),t.cachedValue):t.value():t.value},r.prototype.makeExport=function(e){return function(t){return 0===arguments.length?this.getKeyValue(e):void 0!==t&&null!==t?("function"==typeof t?this.setKeyValue(e,function(){return t}):this.setKeyValue(e,t),t):void this.deleteKeyValue(e)}.bind(this)},r.prototype.offKeyValue=function(e,t){if(this.properties[e]){var n=this.eventHandlers[e];if(n){var i=n.indexOf(t);n.splice(i,1)}}return this},r.prototype.onKeyValue=function(e,t){return this.properties[e]&&(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(t)),this},r.prototype.deleteKeyValue=function(e){var t=this.properties[e];return void 0!==t&&(t.value=t.default,t.cachedValue=void 0,a.call(this,e,t.value)),this},r.prototype.setKeyValue=function(e,t){if(!this.properties[e])return this.define(e,t);var n=this.properties[e];return n.value=t,n.cachedValue=void 0,a.call(this,e,t),this},r.prototype.reset=function(){for(var e in this.properties)this.properties.hasOwnProperty(e)&&(this.properties[e].cachedValue=void 0,a.call(this,e,this.getKeyValue(e)));return this},o.assignSymbols(r.prototype,{"can.getKeyValue":r.prototype.getKeyValue,"can.setKeyValue":r.prototype.setKeyValue,"can.deleteKeyValue":r.prototype.deleteKeyValue,"can.onKeyValue":r.prototype.onKeyValue,"can.offKeyValue":r.prototype.offKeyValue}),i.exports=r}(0,e,0,n)}),define("can-globals/can-globals-instance",["require","exports","module","can-namespace","can-globals/can-globals-proto"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-namespace"),r=new(t("can-globals/can-globals-proto"));if(a.globals)throw new Error("You can't have two versions of can-globals, check your dependencies");i.exports=a.globals=r}(0,e,0,n)}),define("can-globals/global/global",["require","exports","module","can-globals/can-globals-instance"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-globals/can-globals-instance");a.define("global",function(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:"object"==typeof process&&"[object process]"==={}.toString.call(process)?e:window}),i.exports=a.makeExport("global")}(function(){return this}(),e,0,n)}),define("can-globals/document/document",["require","exports","module","can-globals/global/global","can-globals/can-globals-instance"],function(e,t,n){!function(e,t,n,i){"use strict";t("can-globals/global/global");var a=t("can-globals/can-globals-instance");a.define("document",function(){return a.getKeyValue("global").document}),i.exports=a.makeExport("document")}(0,e,0,n)}),define("can-globals/mutation-observer/mutation-observer",["require","exports","module","can-globals/global/global","can-globals/can-globals-instance"],function(e,t,n){!function(e,t,n,i){"use strict";t("can-globals/global/global");var a=t("can-globals/can-globals-instance");a.define("MutationObserver",function(){var e=a.getKeyValue("global");return e.MutationObserver||e.WebKitMutationObserver||e.MozMutationObserver}),i.exports=a.makeExport("MutationObserver")}(0,e,0,n)}),define("can-cid/helpers",function(e,t,n){n.exports={each:function(e,t,n){for(var i in e)t.call(n,e[i],i);return e}}}),define("can-cid/set/set",["require","exports","module","can-cid","can-cid/helpers"],function(e,t,n){"use strict";var i,a=e("can-cid").get,r=e("can-cid/helpers");"undefined"!=typeof Set?i=Set:((i=function(){this.values={}}).prototype.add=function(e){this.values[a(e)]=e},i.prototype.delete=function(e){var t=a(e)in this.values;return t&&delete this.values[a(e)],t},i.prototype.forEach=function(e,t){r.each(this.values,e,t)},i.prototype.has=function(e){return a(e)in this.values},i.prototype.clear=function(){return this.values={}},Object.defineProperty(i.prototype,"size",{get:function(){var e=0;return r.each(this.values,function(){e++}),e}})),n.exports=i}),define("can-util/dom/mutation-observer/document/document",["require","exports","module","can-globals/document/document","can-dom-data-state","can-globals/mutation-observer/mutation-observer","can-util/js/each/each","can-cid/set/set","can-util/js/make-array/make-array","can-util/js/string/string"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-globals/document/document"),r=t("can-dom-data-state"),o=t("can-globals/mutation-observer/mutation-observer"),s=t("can-util/js/each/each"),c=t("can-cid/set/set"),l=t("can-util/js/make-array/make-array"),u=t("can-util/js/string/string"),d=function(e,t,n){if(n.has(e))return!0;n.add(e),"removedNodes"===t.name&&a().documentElement.contains(e)||(t.handlers.forEach(function(t){t(e)}),t.afterHandlers.forEach(function(t){t(e)}))},p={add:function(e){var t=o();if(t){var n=a().documentElement,i=r.get.call(n,"globalObserverData");if(!i){var s=new t(function(e){i.handlers.forEach(function(t){t(e)})});s.observe(n,{childList:!0,subtree:!0}),i={observer:s,handlers:[]},r.set.call(n,"globalObserverData",i)}i.handlers.push(e)}},remove:function(e){var t=a().documentElement,n=r.get.call(t,"globalObserverData");if(n){var i=n.handlers.indexOf(e);i>=0&&n.handlers.splice(i,1),0===n.handlers.length&&(n.observer.disconnect(),r.clean.call(t,"globalObserverData"))}}},f=function(e){var t=e.toLowerCase()+"Nodes",n=function(){var e=a().documentElement,n=r.get.call(e,t+"MutationData");return n||(n={name:t,handlers:[],afterHandlers:[],hander:null},o()&&r.set.call(e,t+"MutationData",n)),n},i=function(){var e=n();return 0!==e.handlers.length&&0!==e.afterHandlers.length||(e.handler=function(n){var i=new c;n.forEach(function(n){s(n[t],function(t){var n=t.getElementsByTagName&&l(t.getElementsByTagName("*")),a=d(t,e,i);if(n&&!a)for(var r,o=0;void 0!==(r=n[o]);o++)d(r,e,i)})})},this.add(e.handler)),e},f=function(){var e=a().documentElement,i=n();0===i.handlers.length&&0===i.afterHandlers.length&&(this.remove(i.handler),r.clean.call(e,t+"MutationData"))},h=function(e,t){p["on"+e]=function(e){i.call(this)[t].push(e)},p["off"+e]=function(e){var i=n(),a=i[t].indexOf(e);a>=0&&i[t].splice(a,1),f.call(this)}};!function(e){h(e,"handlers"),h("After"+e,"afterHandlers")}(u.capitalize(t))};f("added"),f("removed"),i.exports=p}(0,e,0,n)}),define("can-util/dom/data/data",["require","exports","module","can-dom-data-state","can-util/dom/mutation-observer/document/document"],function(e,t,n){"use strict";var i=e("can-dom-data-state"),a=e("can-util/dom/mutation-observer/document/document"),r=function(){return i.delete.call(this)},o=0,s=function(e){0===(o-=r.call(e)?1:0)&&a.offAfterRemovedNodes(s)};n.exports={getCid:i.getCid,cid:i.cid,expando:i.expando,clean:i.clean,get:i.get,set:function(e,t){0===o&&a.onAfterRemovedNodes(s),o+=i.set.call(this,e,t)?1:0},delete:r}}),define("can-util/dom/class-name/class-name",function(e,t,n){"use strict";var i=function(e){return this.classList?this.classList.contains(e):!!this.className.match(new RegExp("(\\s|^)"+e+"(\\s|$)"))};n.exports={has:i,add:function(e){this.classList?this.classList.add(e):i.call(this,e)||(this.className+=" "+e)},remove:function(e){if(this.classList)this.classList.remove(e);else if(i.call(this,e)){var t=new RegExp("(\\s|^)"+e+"(\\s|$)");this.className=this.className.replace(t," ")}}}}),define("can-globals/is-browser-window/is-browser-window",["require","exports","module","can-globals/can-globals-instance"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-globals/can-globals-instance");a.define("isBrowserWindow",function(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"==typeof SimpleDOM}),i.exports=a.makeExport("isBrowserWindow")}(0,e,0,n)}),define("can-util/dom/events/events",["require","exports","module","can-globals/document/document","can-globals/is-browser-window/is-browser-window","can-util/js/is-plain-object/is-plain-object","can-log/dev/dev"],function(e,t,n){!function(e,t,n,i){"use strict";function a(e,t){var n=s(t)?"inserted"===t.type||"removed"===t.type:"inserted"===t||"removed"===t,i=!!e.disabled;return n&&i}var r=t("can-globals/document/document"),o=t("can-globals/is-browser-window/is-browser-window"),s=t("can-util/js/is-plain-object/is-plain-object"),c=!1,l=t("can-log/dev/dev");i.exports={addEventListener:function(){this.addEventListener.apply(this,arguments)},removeEventListener:function(){this.removeEventListener.apply(this,arguments)},canAddEventListener:function(){return this.nodeName&&(1===this.nodeType||9===this.nodeType)||this===window},dispatch:function(e,t,n){var i,o=c&&a(this,e),s=(this.ownerDocument||r()).createEvent("HTMLEvents"),u="string"==typeof e;if(s.initEvent(u?e:e.type,void 0===n||n,!1),!u)for(var d in e)void 0===s[d]&&(s[d]=e[d]);return!0===this.disabled&&"fix_synthetic_events_on_disabled_test"!==s.type&&l.warn("can-util/dom/events::dispatch: Dispatching a synthetic event on a disabled is problematic in FireFox and Internet Explorer. We recommend avoiding this if at all possible. see https://github.com/canjs/can-util/issues/294"),s.args=t,o&&(this.disabled=!1),i=this.dispatchEvent(s),o&&(this.disabled=!0),i}},function(){if(o()){var e="fix_synthetic_events_on_disabled_test",t=document.createElement("input");t.disabled=!0;var n=setTimeout(function(){c=!0},50),a=function a(){clearTimeout(n),i.exports.removeEventListener.call(t,e,a)};i.exports.addEventListener.call(t,e,a);try{i.exports.dispatch.call(t,e,[],!1)}catch(e){a(),c=!0}}}()}(0,e,0,n)}),define("can-queues/queue-state",function(e,t,n){n.exports={lastTask:null}}),define("can-queues/queue",["require","exports","module","can-queues/queue-state","can-util/js/dev/dev"],function(e,t,n){function i(){}var a=e("can-queues/queue-state"),r=e("can-util/js/dev/dev"),o=function(e,t){this.callbacks=Object.assign({onFirstTask:i,onComplete:function(){a.lastTask=null}},t||{}),this.name=e,this.index=0,this.tasks=[],this._log=!1};o.noop=i,o.prototype.enqueue=function(e,t,n,i){var a=this.tasks.push({fn:e,context:t,args:n,meta:i||{}});this._logEnqueue(this.tasks[a-1]),1===a&&this.callbacks.onFirstTask(this)},o.prototype._logEnqueue=function(e){if(e.meta.stack=this,e.meta.parentTask=a.lastTask,!0===this._log||"enqueue"===this._log){var t=e.meta.log?e.meta.log.concat(e):[e.fn.name,e];r.log.apply(r,[this.name+" enqueuing:"].concat(t))}},o.prototype._logFlush=function(e){if(!0===this._log||"flush"===this._log){var t=e.meta.log?e.meta.log.concat(e):[e.fn.name,e];r.log.apply(r,[this.name+" running :"].concat(t))}a.lastTask=e},o.prototype.flush=function(){for(;this.index<this.tasks.length;){var e=this.tasks[this.index++];this._logFlush(e),e.fn.apply(e.context,e.args)}this.index=0,this.tasks=[],this.callbacks.onComplete(this)},o.prototype.log=function(){this._log=!arguments.length||arguments[0]},n.exports=o}),define("can-queues/priority-queue",["require","exports","module","can-queues/queue"],function(e,t,n){var i=e("can-queues/queue"),a=function(){i.apply(this,arguments),this.taskMap=new Map,this.curPriorityIndex=1/0,this.curPriorityMax=0,this.taskContainersByPriority=[],this.isFlushing=!1,this.tasksRemaining=0};(a.prototype=Object.create(i.prototype)).enqueue=function(e,t,n,i){if(!this.taskMap.has(e)){this.tasksRemaining++;var a=0===this.taskContainersByPriority.length,r={fn:e,context:t,args:n,meta:i||{}};this.getTaskContainerAndUpdateRange(r).tasks.push(r),this.taskMap.set(e,r),this._logEnqueue(r),a&&this.callbacks.onFirstTask(this)}},a.prototype.isEnqueued=function(e){return this.taskMap.has(e)},a.prototype.flush=function(){if(!this.isFlushing)for(this.isFlushing=!0;;){if(!(this.curPriorityIndex<=this.curPriorityMax))return this.taskMap=new Map,this.curPriorityIndex=1/0,this.curPriorityMax=0,this.taskContainersByPriority=[],this.isFlushing=!1,void this.callbacks.onComplete(this);var e=this.taskContainersByPriority[this.curPriorityIndex];if(e&&e.tasks.length>e.index){var t=e.tasks[e.index++];this._logFlush(t),this.tasksRemaining--,this.taskMap.delete(t.fn),t.fn.apply(t.context,t.args)}else this.curPriorityIndex++}},a.prototype.flushQueuedTask=function(e){var t=this.taskMap.get(e);if(t){var n=t.meta.priority||0,i=this.taskContainersByPriority[n],a=i.tasks.indexOf(t,i.index);a>=0&&(i.tasks.splice(a,1),this._logFlush(t),this.tasksRemaining--,this.taskMap.delete(t.fn),t.fn.apply(t.context,t.args))}},a.prototype.getTaskContainerAndUpdateRange=function(e){var t=e.meta.priority||0;return t<this.curPriorityIndex&&(this.curPriorityIndex=t),t>this.curPriorityMax&&(this.curPriorityMax=t),this.taskContainersByPriority[t]||(this.taskContainersByPriority[t]={tasks:[],index:0})},a.prototype.tasksRemainingCount=function(){return this.tasksRemaining},n.exports=a}),define("can-queues/completion-queue",["require","exports","module","can-queues/queue"],function(e,t,n){var i=e("can-queues/queue"),a=function(){i.apply(this,arguments),this.flushCount=0};(a.prototype=Object.create(i.prototype)).flush=function(){if(this.flushCount>0);else{for(this.flushCount++;this.index<this.tasks.length;){var e=this.tasks[this.index++];this._logFlush(e),e.fn.apply(e.context,e.args)}this.index=0,this.tasks=[],this.flushCount--,this.callbacks.onComplete(this)}},n.exports=a}),define("can-queues",["require","exports","module","can-util/js/dev/dev","can-queues/queue","can-queues/priority-queue","can-queues/queue-state","can-queues/completion-queue","can-namespace"],function(e,t,n){var i,a,r,o,s,c=e("can-util/js/dev/dev"),l=e("can-queues/queue"),u=e("can-queues/priority-queue"),d=e("can-queues/queue-state"),p=e("can-queues/completion-queue"),f=e("can-namespace"),h=0,v=!1,m=!1,g=0,y=function(){return{}};a=new l("NOTIFY",{onComplete:function(){r.flush()},onFirstTask:function(){h?v=!0:a.flush()}}),r=new u("DERIVE",{onComplete:function(){o.flush()},onFirstTask:function(){v=!0}}),o=new p("DOM_UI",{onComplete:function(){s.flush()},onFirstTask:function(){v=!0}}),s=new l("MUTATE",{onComplete:function(){d.lastTask=null,m=!1},onFirstTask:function(){v=!0}});var b={Queue:l,PriorityQueue:u,notifyQueue:a,deriveQueue:r,domUIQueue:o,mutateQueue:s,batch:{start:function(){1===++h&&(i={number:++g})},stop:function(){0===--h&&v&&(v=!1,m=!0,a.flush())},isCollecting:function(){return h>0},number:function(){return g},data:function(){return i}},enqueueByQueue:function(e,t,n,i,a){e&&(i=i||y,b.batch.start(),["notify","derive","domUI","mutate"].forEach(function(r){var o=b[r+"Queue"],s=e[r];void 0!==s&&s.forEach(function(e){var r=i&&i(e,t,n);r.reasonLog=a,o.enqueue(e,t,n,r)})}),b.batch.stop())},stack:function(){for(var e=d.lastTask,t=[];e;)t.unshift(e),e=e.meta.parentTask;return t},logStack:function(){this.stack().forEach(function(e){var t=e.meta&&e.meta.log?e.meta.log:[e.fn.name,e];c.log.apply(c,[e.meta.stack.name+" ran task:"].concat(t))})},taskCount:function(){return a.tasks.length+r.tasks.length+o.tasks.length+s.tasks.length},flush:function(){a.flush()},log:function(){a.log.apply(a,arguments),r.log.apply(r,arguments),o.log.apply(o,arguments),s.log.apply(s,arguments)}};if(f.queues)throw new Error("You can't have two versions of can-queues, check your dependencies");n.exports=f.queues=b}),define("can-key-tree",["require","exports","module","can-reflect"],function(e,t,n){function i(e){return e===Object.prototype||"[object Object]"!==Object.prototype.toString.call(e)&&-1!==Object.prototype.toString.call(e).indexOf("[object ")}function a(e,t,n,i){if(e)if(i===n){if(!s.isMoreListLikeThanMapLike(e))throw new Error("can-key-tree: Map types are not supported yet.");s.addValues(t,s.toArray(e))}else s.each(e,function(e){a(e,t,n+1,i)})}function r(e,t,n){if(n===t){if(!s.isMoreListLikeThanMapLike(e))throw new Error("can-key-tree: Map types are not supported yet.");s.removeValues(e,s.toArray(e))}else s.each(e,function(i,a){r(i,t+1,n),s.deleteKeyValue(e,a)})}function o(e,t){if(0===t)return s.size(e);if(0===s.size(e))return 0;var n=0;return s.each(e,function(e){n+=o(e,t-1)}),n}var s=e("can-reflect"),c=function(e,t){this.callbacks=t||{},this.treeStructure=e;var n=e[0];s.isConstructorLike(n)?this.root=new n:this.root=n};c.prototype.add=function(e){if(e.length>this.treeStructure.length)throw new Error("can-key-tree: Can not add path deeper than tree.");for(var t=this.root,n=0===s.size(this.root),a=0;a<e.length-1;a++){var r=e[a],o=s.getKeyValue(t,r);if(!o){var c=this.treeStructure[a+1];o=i(c.prototype)?new c:new c(r),s.setKeyValue(t,r,o)}t=o}if(!s.isMoreListLikeThanMapLike(t))throw new Error("can-key-tree: Map types are not supported yet.");s.addValues(t,[e[e.length-1]]),n&&this.callbacks.onFirst&&this.callbacks.onFirst.call(this)},c.prototype.get=function(e){var t=this.getNode(e);if(this.treeStructure.length===e.length)return t;var n=new(0,this.treeStructure[this.treeStructure.length-1]);return a(t,n,e.length,this.treeStructure.length-1),n},c.prototype.getNode=function(e){for(var t=this.root,n=0;n<e.length;n++){var i=e[n],a=s.getKeyValue(t,i);if(!a)return;t=a}return t},c.prototype.delete=function(e){for(var t=this.root,n=[this.root],i=0;i<e.length-1;i++){var a=e[i],o=s.getKeyValue(t,a);if(void 0===o)return!1;n.push(o),t=o}var c=e[e.length-1];if(e.length===this.treeStructure.length){if(!s.isMoreListLikeThanMapLike(t))throw new Error("can-key-tree: Map types are not supported yet.");s.removeValues(t,[c])}else if(e.length){var l=s.getKeyValue(t,c);if(void 0===l)return!1;r(l,e.length,this.treeStructure.length-1),s.deleteKeyValue(t,c)}else r(t,0,this.treeStructure.length-1);for(i=n.length-2;i>=0&&0===s.size(t);i--)t=n[i],s.deleteKeyValue(t,e[i]);return this.callbacks.onEmpty&&0===s.size(this.root)&&this.callbacks.onEmpty.call(this),!0},c.prototype.size=function(){return o(this.root,this.treeStructure.length-1)},n.exports=c}),define("can-observation-recorder",["require","exports","module","can-namespace"],function(e,t,n){var i=e("can-namespace"),a=[],r={stack:a,makeDependenciesRecorder:function(){return{traps:null,keyDependencies:new Map,valueDependencies:new Set,ignore:0}},start:function(){a.push({traps:null,keyDependencies:new Map,valueDependencies:new Set,ignore:0})},stop:function(){return a.pop()},add:function(e,t){var n=a[a.length-1];if(n&&0===n.ignore)if(n.traps)n.traps.push([e,t]);else if(void 0===t)n.valueDependencies.add(e);else{var i=n.keyDependencies.get(e);i||(i=new Set,n.keyDependencies.set(e,i)),i.add(t)}},addMany:function(e){var t=a[a.length-1];if(t)if(t.traps)t.traps.push.apply(t.traps,e);else for(var n=0,i=e.length;n<i;n++)this.add(e[n][0],e[n][1])},ignore:function(e){return function(){if(a.length){var t=a[a.length-1];t.ignore++;var n=e.apply(this,arguments);return t.ignore--,n}return e.apply(this,arguments)}},trap:function(){if(a.length){var e=a[a.length-1],t=e.traps,n=e.traps=[];return function(){return e.traps=t,n}}return function(){return[]}},trapsCount:function(){return a.length?a[a.length-1].traps.length:0},isRecording:function(){var e=a.length,t=e&&a[e-1];return t&&0===t.ignore&&t}};if(i.observationRecorder)throw new Error("You can't have two versions of can-observation-recorder, check your dependencies");n.exports=i.observationRecorder=r}),define("can-observation/recorder-dependency-helpers",["require","exports","module","can-reflect"],function(e,t,n){function i(e){l.offKeyValue(this.observable,e,this.onDependencyChange,"notify")}function a(e,t){e.forEach(i,{onDependencyChange:this.onDependencyChange,observable:t})}function r(e){this.oldEventSet&&this.oldEventSet.delete(e)||l.onKeyValue(this.observable,e,this.onDependencyChange,"notify")}function o(e,t){e.forEach(r,{onDependencyChange:this.onDependencyChange,observable:t,oldEventSet:this.oldDependencies.keyDependencies.get(t)})}function s(e){this.oldDependencies.valueDependencies.delete(e)||l.onValue(e,this.onDependencyChange,"notify")}function c(e){l.offValue(e,this.onDependencyChange,"notify")}var l=e("can-reflect");n.exports={updateObservations:function(e){e.newDependencies.keyDependencies.forEach(o,e),e.oldDependencies.keyDependencies.forEach(a,e),e.newDependencies.valueDependencies.forEach(s,e),e.oldDependencies.valueDependencies.forEach(c,e)},stopObserving:function(e,t){e.keyDependencies.forEach(a,{onDependencyChange:t}),e.valueDependencies.forEach(c,{onDependencyChange:t})}}}),define("can-observation",["require","exports","module","can-util/js/assign/assign","can-namespace","can-reflect","can-queues","can-key-tree","can-observation-recorder","can-observation/recorder-dependency-helpers","can-symbol","can-log/dev/dev"],function(e,t,n){!function(e,t,n,i){function a(e,t,n){this.func=e,this.context=t,this.options=n||{priority:0,isObservable:!0},this.newDependencies=u.makeDependenciesRecorder(),this.oldDependencies=null,this.handlers=new l([Object,Array],{onFirst:this.start.bind(this),onEmpty:this.stop.bind(this)}),this.bound=!1;var i=this;this.onDependencyChange=function(e){i.dependencyChange(this,e)},this.update=this.update.bind(this),Object.defineProperty(this.onDependencyChange,"name",{value:s.getName(this)+".onDependencyChange"}),Object.defineProperty(this.update,"name",{value:s.getName(this)+".update"})}var r=t("can-util/js/assign/assign"),o=t("can-namespace"),s=t("can-reflect"),c=t("can-queues"),l=t("can-key-tree"),u=t("can-observation-recorder"),d=t("can-observation/recorder-dependency-helpers"),p=t("can-symbol"),f=t("can-log/dev/dev");r(a.prototype,{get:function(){return this.options.isObservable&&a.isRecording()&&(u.add(this),this.bound||a.temporarilyBind(this)),!0===this.bound?(c.deriveQueue.tasksRemainingCount()>0&&a.updateChildrenAndSelf(this),this.value):this.func.call(this.context)},dependencyChange:function(e,t){!0===this.bound&&c.deriveQueue.enqueue(this.update,this,[],{priority:this.options.priority,log:[s.getName(this.update)]},[s.getName(e),"changed"])},update:function(){if(!0===this.bound){var e=this.value;if(this.oldValue=null,this.start(),e!==this.value)return"function"==typeof this._log&&this._log(e,this.value),c.enqueueByQueue(this.handlers.getNode([]),this,[this.value,e],null,[s.getName(this),"changed to",this.value,"from",e]),!0}},start:function(){this.bound=!0,this.oldDependencies=this.newDependencies,u.start(),this.value=this.func.call(this.context),this.newDependencies=u.stop(),d.updateObservations(this)},stop:function(){this.bound=!1,d.stopObserving(this.newDependencies,this.onDependencyChange),this.newDependencies=u.makeDependenciesRecorder()},hasDependencies:function(){var e=this.newDependencies;return this.bound?e.valueDependencies.size+e.keyDependencies.size>0:void 0},log:function(){var e=function(e){return"string"==typeof e?JSON.stringify(e):e};this._log=function(t,n){f.log(s.getName(this),"\n is ",e(n),"\n was ",e(t))}}}),s.assignSymbols(a.prototype,{"can.onValue":function(e,t){this.handlers.add([t||"mutate",e])},"can.offValue":function(e,t){this.handlers.delete([t||"mutate",e])},"can.getValue":a.prototype.get,"can.isValueLike":!0,"can.isMapLike":!1,"can.isListLike":!1,"can.valueHasDependencies":a.prototype.hasDependencies,"can.getValueDependencies":function(){if(!0===this.bound)return this.newDependencies},"can.getPriority":function(){return this.options.priority},"can.setPriority":function(e){this.options.priority=e},"can.getName":function(){return s.getName(this.constructor)+"<"+s.getName(this.func)+">"}});var h=p.for("can.getValueDependencies");a.updateChildrenAndSelf=function(e){if(e.update&&!0===c.deriveQueue.isEnqueued(e.update))return c.deriveQueue.flushQueuedTask(e.update),!0;if(e[h]){var t=!1;return(e[h]().valueDependencies||[]).forEach(function(e){a.updateChildrenAndSelf(e)&&(t=!0)}),t}return!1},a.add=u.add,a.addAll=u.addMany,a.ignore=u.ignore,a.trap=u.trap,a.trapsCount=u.trapsCount,a.isRecording=u.isRecording;var v,m=function(){},g=function(){for(var e=0,t=v.length;e<t;e++)s.offValue(v[e],m);v=null};if(a.temporarilyBind=function(e){var t=e.computeInstance||e;s.onValue(t,m),v||(v=[],setTimeout(g,10)),v.push(t)},o.Observation)throw new Error("You can't have two versions of can-observation, check your dependencies");i.exports=o.Observation=a}(0,e,0,n)}),define("can-util/js/is-promise-like/is-promise-like",function(e,t,n){"use strict";n.exports=function(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}}),define("can-reflect-promise",["require","exports","module","can-reflect","can-symbol","can-observation-recorder","can-queues","can-key-tree","can-util/js/dev/dev"],function(e,t,n){function i(e,t,n){var i=e[f],a=i[t];i[t]=n,l.enqueueByQueue(i.handlers.getNode([t]),e,[n,a],function(){return{}},["Promise",e,"resolved with value",n,"and changed virtual property: "+t])}function a(e){var t=e[f];t||(Object.defineProperty(e,f,{enumerable:!1,configurable:!1,writable:!1,value:Object.create(h)}),(t=e[f]).handlers=new u([Object,Object,Array])),e.then(function(t){l.batch.start(),i(e,"isPending",!1),i(e,"isResolved",!0),i(e,"value",t),i(e,"state","resolved"),l.batch.stop()},function(t){l.batch.start(),i(e,"isPending",!1),i(e,"isRejected",!0),i(e,"reason",t),i(e,"state","rejected"),l.batch.stop(),d.error("Failed promise:",t)})}function r(e){var t,n="getPrototypeOf"in Object?Object.getPrototypeOf(e):e.__proto__;e[p]&&e[f]||(null!==n&&n!==Object.prototype||"function"==typeof(n=e).promise&&(t=n.promise,n.promise=function(){var e=t.call(n);return r(e),e}),o.assignSymbols(n,{"can.getKeyValue":function(e){switch(this[f]||a(this),c.add(this,e),e){case"state":case"isPending":case"isResolved":case"isRejected":case"value":case"reason":return this[f][e];default:return this[e]}},"can.getValue":function(){return this[p]("value")},"can.isValueLike":!1,"can.onKeyValue":function(e,t,n){this[f]||a(this),this[f].handlers.add([e,n||"mutate",t])},"can.offKeyValue":function(e,t,n){this[f]||a(this),this[f].handlers.delete([e,n||"mutate",t])}}))}var o=e("can-reflect"),s=e("can-symbol"),c=e("can-observation-recorder"),l=e("can-queues"),u=e("can-key-tree"),d=e("can-util/js/dev/dev"),p=s.for("can.getKeyValue"),f=s.for("can.meta"),h={isPending:!0,state:"pending",isResolved:!1,isRejected:!1,value:void 0,reason:void 0};n.exports=r}),define("can-stache-key",["require","exports","module","can-observation","can-util/js/dev/dev","can-util/js/each/each","can-symbol","can-reflect","can-util/js/is-promise-like/is-promise-like","can-reflect-promise"],function(e,t,n){var i,a=e("can-observation"),r=e("can-util/js/dev/dev"),o=e("can-util/js/each/each"),s=e("can-symbol"),c=e("can-reflect"),l=e("can-util/js/is-promise-like/is-promise-like"),u=e("can-reflect-promise"),d=s.for("can.getValue"),p=s.for("can.setValue"),f=s.for("can.isValueLike"),h=a.ignore(c.getKeyValue.bind(c)),v=Function.prototype.bind;v=function(e){var t=Function.prototype.bind.call(this,e);return Object.defineProperty(t,"name",{value:c.getName(e)+"."+c.getName(this)}),t};var m=function(e,t){var n=t[e-1];return n&&n.at},g=function(e,t,n,a,r,o){var s;do{s=!1;for(var c=0,l=i.valueReaders.length;c<l;c++)i.valueReaders[c].test(e,t,n,a)&&(e=i.valueReaders[c].read(e,t,n,a,r,o))}while(s);return e},y={index:!0,key:!0,event:!0,element:!0,viewModel:!0},b=function(e,t,n,i,r){e.foundObservable&&!t.foundObservable&&a.trapsCount()&&(a.addAll(n()),e.foundObservable(i,r),t.foundObservable=!0)};o((i={read:function(e,t,n){var r,o={foundObservable:!1};(n=n||{}).foundObservable&&(r=a.trap());var s,c=g(e,0,t,n,o),l=t.length,u=0;for(b(n,o,r,e,0);u<l;){s=c;for(var d=0,p=i.propertyReaders.length;d<p;d++){var f=i.propertyReaders[d];if(f.test(c)){c=f.read(c,t[u],u,n,o);break}}if(b(n,o,r,s,u),c,u+=1,c=g(c,u,t,n,o,s),b(n,o,r,s,u-1),typeof c,u<t.length&&(null===c||void 0===c))return n.earlyExit&&n.earlyExit(s,u-1,c),{value:void 0,parent:s}}return void 0===c&&n.earlyExit&&n.earlyExit(s,u-1),{value:c,parent:s}},get:function(e,t,n){return i.read(e,i.reads(t),n||{}).value},valueReadersMap:{},valueReaders:[{name:"function",test:function(e){return e&&c.isFunctionLike(e)&&!c.isConstructorLike(e)},read:function(e,t,n,i,a,r){return m(t,n)?t===n.length?v.call(e,r):e:i.callMethodsOnObservables&&c.isObservableLike(r)&&c.isMapLike(r)?e.apply(r,i.args||[]):i.isArgument&&t===n.length?!1!==i.proxyMethods?v.call(e,r):e:e.apply(r,i.args||[])}},{name:"isValueLike",test:function(e,t,n,i){return e&&e[d]&&!1!==e[f]&&(i.foundAt||!m(t,n))},read:function(e,t,n,i){return!1===i.readCompute&&t===n.length?e:c.getValue(e)},write:function(e,t){e[p]?e[p](t):e.set?e.set(t):e(t)}}],propertyReadersMap:{},propertyReaders:[{name:"map",test:function(e){return(l(e)||"object"==typeof e&&e&&"function"==typeof e.then)&&u(e),c.isObservableLike(e)&&c.isMapLike(e)},read:function(e,t){var n=c.getKeyValue(e,t.key);return void 0!==n?n:e[t.key]},write:c.setKeyValue},{name:"object",test:function(){return!0},read:function(e,t,n,i){if(null!=e)return"object"!=typeof e?e[t.key]:t.key in e?e[t.key]:t.at&&y[t.key]&&"@"+t.key in e?(i.foundAt=!0,r.warn("Use %"+t.key+" in place of @"+t.key+"."),e["@"+t.key]):void 0},write:function(e,t,n){var i=e[t];c.isMapLike(i)&&n&&"object"==typeof n?(r.warn('can-stache-key: Merging data into "'+t+'" because its parent is non-observable'),c.update(i,n)):c.isValueLike(i)&&c.isObservableLike(i)?c.setValue(i,n):e[t]=n}}],reads:function(e){var t=""+e,n=[],i=0,a=!1;"@"===t.charAt(0)&&(i=1,a=!0);for(var r="",o=i;o<t.length;o++){var s=t.charAt(o);"."===s||"@"===s?"\\"!==t.charAt(o-1)?(n.push({key:r,at:a}),a="@"===s,r=""):r=r.substr(0,r.length-1)+".":r+=s}return n.push({key:r,at:a}),n},write:function(e,t,n,a){var r,o="string"==typeof t?i.reads(t):t;a=a||{},o.length>1?(r=o.pop(),e=i.read(e,o,a).value,o.push(r)):r=o[0];var s=h(e,r.key);i.valueReadersMap.isValueLike.test(s,o.length-1,o,a)?i.valueReadersMap.isValueLike.write(s,n,a):(i.valueReadersMap.isValueLike.test(e,o.length-1,o,a)&&(e=e[d]()),i.propertyReadersMap.map.test(e)?i.propertyReadersMap.map.write(e,r.key,n,a):i.propertyReadersMap.object.test(e)&&(i.propertyReadersMap.object.write(e,r.key,n,a),a.observation&&a.observation.update()))}}).propertyReaders,function(e){i.propertyReadersMap[e.name]=e}),o(i.valueReaders,function(e){i.valueReadersMap[e.name]=e}),i.set=i.write,n.exports=i}),define("can-util/dom/dispatch/dispatch",["require","exports","module","can-util/dom/events/events"],function(e,t,n){"use strict";var i=e("can-util/dom/events/events");n.exports=function(){return i.dispatch.apply(this,arguments)}}),define("can-util/dom/matches/matches",function(e,t,n){"use strict";var i=function(e){return e.matches||e.webkitMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector};n.exports=function(){var e=i(this);return!!e&&e.apply(this,arguments)}}),define("can-util/js/is-empty-object/is-empty-object",function(e,t,n){"use strict";n.exports=function(e){for(var t in e)return!1;return!0}}),define("can-util/dom/events/delegate/delegate",["require","exports","module","can-util/dom/events/events","can-util/dom/data/data","can-util/dom/matches/matches","can-util/js/each/each","can-util/js/is-empty-object/is-empty-object"],function(e,t,n){"use strict";var i=e("can-util/dom/events/events"),a=e("can-util/dom/data/data"),r=e("can-util/dom/matches/matches"),o=e("can-util/js/each/each"),s=e("can-util/js/is-empty-object/is-empty-object"),c="delegateEvents",l=function(e){return"focus"===e||"blur"===e},u=function(e){var t=a.get.call(this,c)[e.type],n=[];if(t){var i=[];o(t,function(e){i.push(e)});var s=e.target;do{i.forEach(function(e){r.call(s,e[0].selector)&&n.push({target:s,delegates:e})}),s=s.parentNode}while(s&&s!==e.currentTarget)}var l=e.stopPropagation;e.stopPropagation=function(){l.apply(this,arguments),this.cancelBubble=!0};for(var u=0;u<n.length;u++)for(var d=n[u],p=d.delegates,f=0,h=p.length;f<h;f++){if(!1===p[f].handler.call(d.target,e))return!1;if(e.cancelBubble)return}};i.addDelegateListener=function(e,t,n){var r,o=a.get.call(this,c);o||a.set.call(this,c,o={}),(r=o[e])||(r=o[e]={},i.addEventListener.call(this,e,u,l(e))),r[t]||(r[t]=[]),r[t].push({handler:n,selector:t})},i.removeDelegateListener=function(e,t,n){var r=a.get.call(this,c);if(r&&r[e]&&r[e][t]){for(var o=r[e],d=o[t],p=0;p<d.length;)d[p].handler===n?d.splice(p,1):p++;0===d.length&&(delete o[t],s(o)&&(i.removeEventListener.call(this,e,u,l(e)),delete r[e],s(r)&&a.clean.call(this,c)))}}}),define("can-control",["require","exports","module","can-construct","can-namespace","can-util/js/string/string","can-util/js/assign/assign","can-util/js/is-function/is-function","can-util/js/each/each","can-util/js/dev/dev","can-util/js/get/get","can-util/dom/data/data","can-util/dom/class-name/class-name","can-util/dom/events/events","can-stache-key","can-reflect","can-observation","can-symbol","can-util/dom/dispatch/dispatch","can-util/dom/events/delegate/delegate"],function(e,t,n){var i,a=e("can-construct"),r=e("can-namespace"),o=e("can-util/js/string/string"),s=e("can-util/js/assign/assign"),c=e("can-util/js/is-function/is-function"),l=e("can-util/js/each/each"),u=e("can-util/js/dev/dev"),d=e("can-util/js/get/get"),p=e("can-util/dom/data/data"),f=e("can-util/dom/class-name/class-name"),h=e("can-util/dom/events/events"),v=e("can-stache-key"),m=e("can-reflect"),g=e("can-observation"),y=e("can-symbol");e("can-util/dom/dispatch/dispatch"),e("can-util/dom/events/delegate/delegate");var b,w=y.for("can.onKeyValue"),k=y.for("can.offKeyValue"),x=y.for("can.onEvent"),j=y.for("can.offEvent"),L=y.for("can.onValue"),E=y.for("can.offValue"),V={on:function(e,t,n){if(h.canAddEventListener.call(this))h["string"==typeof t?"addDelegateListener":"addEventListener"].call(this,e,t,n);else if(this[w])m.onKeyValue(this,e,t,n);else if(this[x])this[x](e,t,n);else if("addEventListener"in this)this.addEventListener(e,t,n);else{if(e||!this[L])throw new Error("can-control: Unable to bind "+e);m.onValue(this,t)}},off:function(e,t,n){if(h.canAddEventListener.call(this))h["string"==typeof t?"removeDelegateListener":"removeEventListener"].call(this,e,t,n);else if(this[k])m.offKeyValue(this,e,t,n);else if(this[j])this[j](e,t,n);else if("removeEventListener"in this)this.removeEventListener(e,t,n);else{if(e||!this[E])throw new Error("can-control: Unable to unbind "+e);m.offValue(this,t)}}},O=function(e,t,n,i){return V.on.call(e,t,n,i),function(){V.off.call(e,t,n,i)}},C=[].slice,_=/\{([^\}]+)\}/g,D=function(e,t,n,i){return V.on.call(e,n,t,i),function(){V.off.call(e,n,t,i)}},S=function(e,t,n,i){return i?D(e,i.trim(),t,n):O(e,t,n)},T=a.extend("Control",{setup:function(){if(a.setup.apply(this,arguments),T){var e,t=this;t.actions={};for(e in t.prototype)t._isAction(e)&&(t.actions[e]=t._action(e))}},_shifter:function(e,t){function n(){var n=a.wrapElement(this);return e.called=t,i.apply(e,[n].concat(C.call(arguments,0)))}var i="string"==typeof t?e[t]:t;c(i)||(i=e[i]);var a=this;return Object.defineProperty(n,"name",{value:m.getName(this)+"["+t+"]"}),n},_isAction:function(e){var t=this.prototype[e],n=typeof t;return"constructor"!==e&&("function"===n||"string"===n&&c(this.prototype[t]))&&!!(T.isSpecial(e)||i[e]||/[^\w]/.test(e))},_action:function(e,t,n){var i,a;if(_.lastIndex=0,t||!_.test(e)){var r=function(){var n,i=e.replace(_,function(e,i){var r,o;return this._isDelegate(t,i)?(n=this._getDelegate(t,i),""):(i=this._removeDelegateFromKey(i),o=this._lookup(t)[0],void 0===(r=v.read(o,v.reads(i),{readCompute:!1}).value)&&"undefined"!=typeof window&&(r=d(window,i)),o&&(m.isObservableLike(o)&&m.isMapLike(o)||r)?"string"==typeof r?r:(n=r,""):(a=!0,null))}.bind(this)),r=(i=i.trim()).split(/\s+/g),o=r.pop();return{processor:this.processors[o]||b,parts:[i,r.join(" "),o],delegate:n||void 0}};if(Object.defineProperty(r,"name",{value:m.getName(n||this.prototype)+"["+e+"].actionData"}),i=new g(r,this),n){var o=function(t){n._bindings.control[e](n.element),n._bindings.control[e]=t.processor(t.delegate||n.element,t.parts[2],t.parts[1],e,n)};Object.defineProperty(o,"name",{value:m.getName(n)+"["+e+"].handler"}),m.onValue(i,o,"mutate"),a&&u.log("can-control: No property found for handling "+e),n._bindings.readyComputes[e]={compute:i,handler:o}}return i.get()}},_lookup:function(e){return[e,window]},_removeDelegateFromKey:function(e){return e},_isDelegate:function(e,t){return"element"===t},_getDelegate:function(e,t){},processors:{},defaults:{},convertElement:function(e){return e="string"==typeof e?document.querySelector(e):e,this.wrapElement(e)},wrapElement:function(e){return e},unwrapElement:function(e){return e},isSpecial:function(e){return"inserted"===e||"removed"===e}},{setup:function(e,t){var n,i=this.constructor,a=i.pluginName||i.shortName;if(!e)throw new Error("Creating an instance of a named control without passing an element");if(this.element=i.convertElement(e),a&&"Control"!==a&&f.add.call(this.element,a),(n=p.get.call(this.element,"controls"))||(n=[],p.set.call(this.element,"controls",n)),n.push(this),m.isObservableLike(t)&&m.isMapLike(t)){for(var r in i.defaults)t.hasOwnProperty(r)||v.set(t,r,i.defaults[r]);this.options=t}else this.options=s(s({},i.defaults),t);return this.on(),[this.element,this.options]},on:function(e,t,n,i){if(!e){this.off();var a,r,o=this.constructor,s=this._bindings,c=o.actions,l=this.constructor.unwrapElement(this.element),u=T._shifter(this,"destroy");for(a in c)c.hasOwnProperty(a)&&(r=c[a]||o._action(a,this.options,this))&&(s.control[a]=r.processor(r.delegate||l,r.parts[2],r.parts[1],a,this));return h.addEventListener.call(l,"removed",u),s.user.push(function(e){h.removeEventListener.call(e,"removed",u)}),s.user.length}return"string"==typeof e&&(i=n,n=t,t=e,e=this.element),void 0===i&&(i=n,n=t,t=null),"string"==typeof i&&(i=T._shifter(this,i)),this._bindings.user.push(S(e,n,i,t)),this._bindings.user.length},off:function(){var e=this.constructor.unwrapElement(this.element),t=this._bindings;t&&(l(t.user||[],function(t){t(e)}),l(t.control||{},function(t){t(e)}),l(t.readyComputes||{},function(e){m.offValue(e.compute,e.handler,"mutate")})),this._bindings={user:[],control:{},readyComputes:{}}},destroy:function(){if(null!==this.element){var e,t=this.constructor,n=t.pluginName||t.shortName&&o.underscore(t.shortName);this.off(),n&&"can_control"!==n&&f.remove.call(this.element,n),(e=p.get.call(this.element,"controls"))&&e.splice(e.indexOf(this),1),this.element=null}else u.warn("can-control: Control already destroyed")}});i=T.processors,b=function(e,t,n,i,a){return S(e,t,T._shifter(a,i),n)},l(["beforeremove","change","click","contextmenu","dblclick","keydown","keyup","keypress","mousedown","mousemove","mouseout","mouseover","mouseup","reset","resize","scroll","select","submit","focusin","focusout","mouseenter","mouseleave","touchstart","touchmove","touchcancel","touchend","touchleave","inserted","removed","dragstart","dragenter","dragover","dragleave","drag","drop","dragend"],function(e){i[e]=b}),n.exports=r.Control=T}),define("can-component/control/control",["require","exports","module","can-control","can-util/js/each/each","can-reflect"],function(e,t,n){var i=e("can-control"),a=e("can-util/js/each/each"),r=e("can-reflect"),o=/\{([^\}]+)\}/g,s=i.extend({_lookup:function(e){return[e.scope,e,window]},_removeDelegateFromKey:function(e){return e.replace(/^(scope|^viewModel)\./,"")},_isDelegate:function(e,t){return"scope"===t||"viewModel"===t},_getDelegate:function(e,t){return e[t]},_action:function(e,t,n){var a;return o.lastIndex=0,a=o.test(e),!n&&a?void 0:i._action.apply(this,arguments)}},{setup:function(e,t){return this.scope=t.scope,this.viewModel=t.viewModel,i.prototype.setup.call(this,e,t)},off:function(){this._bindings&&a(this._bindings.readyComputes||{},function(e){r.offValue(e.compute,e.handler)}),i.prototype.off.apply(this,arguments),this._bindings.readyComputes={}},destroy:function(){i.prototype.destroy.apply(this,arguments),"function"==typeof this.options.destroy&&this.options.destroy.apply(this,arguments)}});n.exports=s}),define("can-event-queue",["require","exports","module","can-util/js/dev/dev","can-util/js/assign/assign","can-queues","can-reflect","can-symbol","can-key-tree","can-util/dom/events/events"],function(e,t,n){function i(e){var t=p(e),n=t.handlers;return n||(n=t.handlers=new u([Object,Object,Object,Array],{onFirst:function(){e._eventSetup&&e._eventSetup()},onEmpty:function(){e._eventTeardown&&e._eventTeardown()}})),n}function a(e,t,n){Object.defineProperty(e,t,{enumerable:!1,value:n})}var r=e("can-util/js/dev/dev"),o=e("can-util/js/assign/assign"),s=e("can-queues"),c=e("can-reflect"),l=e("can-symbol"),u=e("can-key-tree"),d=e("can-util/dom/events/events"),p=function(e){var t=l.for("can.meta"),n=e[t];return n||(n={},c.setKeyValue(e,t,n)),n},f={dispatch:function(e,t){if(arguments.length>2&&(r.warn("Arguments to dispatch should be an array, not multiple arguments."),t=Array.prototype.slice.call(arguments,1)),t&&!Array.isArray(t)&&(r.warn("Arguments to dispatch should be an array."),t=[t]),!this.__inSetup){"string"==typeof e&&(e={type:e}),e.reasonLog||(e.reasonLog=[c.getName(this),"dispatched",'"'+e+'"',"with"].concat(t)),e.makeMeta||(e.makeMeta=function(e){return{log:[c.getName(e)]}});var n=p(this);"function"==typeof n._log&&n._log.call(this,e,t);var a=i(this).getNode([e.type]);if(a){if(s.batch.start(),a.onKeyValue&&s.enqueueByQueue(a.onKeyValue,this,t,e.makeMeta,e.reasonLog),a.event){e.batchNum=s.batch.number();var o=[e].concat(t);s.enqueueByQueue(a.event,this,o,e.makeMeta,e.reasonLog)}s.batch.stop()}}},addEventListener:function(e,t,n){i(this).add([e,"event",n||"mutate",t])},removeEventListener:function(e,t,n){i(this).delete([e,"event",n||"mutate",t])}},h=l.for("can.onKeyValue"),v=l.for("can.offKeyValue"),m=l.for("can.onEvent"),g=l.for("can.offEvent"),y=l.for("can.onValue"),b=l.for("can.offValue");f.on=function(e,t,n){if(d.canAddEventListener.call(this))d["string"==typeof t?"addDelegateListener":"addEventListener"].call(this,e,t,n);else if("addEventListener"in this)this.addEventListener(e,t,n);else if(this[h])c.onKeyValue(this,e,t,n);else if(this[m])this[m](e,t,n);else{if(e||!this[y])throw new Error("can-control: Unable to bind "+e);c.onValue(this,t)}},f.off=function(e,t,n){if(d.canAddEventListener.call(this))d["string"==typeof t?"removeDelegateListener":"removeEventListener"].call(this,e,t,n);else if("removeEventListener"in this)this.removeEventListener(e,t,n);else if(this[v])c.offKeyValue(this,e,t,n);else if(this[g])this[g](e,t,n);else{if(e||!this[b])throw new Error("can-control: Unable to unbind "+e);c.offValue(this,t)}};var w={"can.onKeyValue":function(e,t,n){i(this).add([e,"onKeyValue",n||"mutate",t])},"can.offKeyValue":function(e,t,n){i(this).delete([e,"onKeyValue",n||"mutate",t])}},k=function(e){return o(e,f),c.assignSymbols(e,w),e};o(k,f),a(k,"start",function(){console.warn("use can-queues.batch.start()"),s.batch.start()}),a(k,"stop",function(){console.warn("use can-queues.batch.stop()"),s.batch.stop()}),a(k,"flush",function(){console.warn("use can-queues.flush()"),s.flush()}),a(k,"afterPreviousEvents",function(e){console.warn("don't use afterPreviousEvents"),s.mutateQueue.enqueue(function(){s.mutateQueue.enqueue(e)}),s.flush()}),a(k,"after",function(e){console.warn("don't use after"),s.mutateQueue.enqueue(e),s.flush()}),n.exports=k}),define("can-simple-map",["require","exports","module","can-construct","can-event-queue","can-queues","can-util/js/each/each","can-observation-recorder","can-reflect","can-log/dev/dev","can-symbol"],function(e,t,n){var i=e("can-construct"),a=e("can-event-queue"),r=e("can-queues"),o=e("can-util/js/each/each"),s=e("can-observation-recorder"),c=e("can-reflect"),l=e("can-log/dev/dev"),u=e("can-symbol"),d=function(e){var t=u.for("can.meta"),n=e[t];return n||(n={},c.setKeyValue(e,t,n)),n},p=i.extend("SimpleMap",{setup:function(e){this._data={},this.attr(e)},attr:function(e,t){var n=this;if(0===arguments.length){s.add(this,"__keys");var i={};return o(this._data,function(e,t){s.add(this,t),i[t]=e},this),i}if(arguments.length>1){var a=this._data.hasOwnProperty(e),l=this._data[e];this._data[e]=t,r.batch.start(),a||this.dispatch("__keys",[]),"function"==typeof this._log&&this._log(e,t,l),this.dispatch({type:e,reasonLog:[c.getName(this)+"'s",e,"changed to",t,"from",l]},[t,l]),r.batch.stop()}else{if("object"!=typeof e)return"constructor"!==e?(s.add(this,e),this._data[e]):this.constructor;r.batch.start(),c.eachKey(e,function(e,t){n.attr(t,e)}),r.batch.stop()}},serialize:function(){return c.serialize(this,Map)},get:function(){return this.attr.apply(this,arguments)},set:function(){return this.attr.apply(this,arguments)},log:function(e){var t=function(e){return"string"==typeof e?JSON.stringify(e):e},n=d(this);n.allowedLogKeysSet=n.allowedLogKeysSet||new Set,e&&n.allowedLogKeysSet.add(e),this._log=function(i,a,r,o){e&&!n.allowedLogKeysSet.has(i)||l.log(c.getName(this),"\n key ",t(i),"\n is ",t(a),"\n was ",t(r))}}});a(p.prototype),c.assignSymbols(p.prototype,{"can.isMapLike":!0,"can.isListLike":!1,"can.isValueLike":!1,"can.getKeyValue":p.prototype.get,"can.setKeyValue":p.prototype.set,"can.deleteKeyValue":function(e){return this.attr(e,void 0)},"can.getOwnEnumerableKeys":function(){return s.add(this,"__keys"),Object.keys(this._data)},"can.assignDeep":function(e){r.batch.start(),c.assignMap(this,e),r.batch.stop()},"can.updateDeep":function(e){r.batch.start(),c.updateMap(this,e),r.batch.stop()},"can.keyHasDependencies":function(e){return!1},"can.getKeyDependencies":function(e){},"can.getName":function(){return c.getName(this.constructor)+"{}"}}),n.exports=p}),define("can-view-scope/reference-map",["require","exports","module","can-simple-map"],function(e,t,n){var i=e("can-simple-map").extend({});n.exports=i}),define("can-util/js/single-reference/single-reference",["require","exports","module","can-cid"],function(e,t,n){!function(e,t,n,i){function a(e,t){return(t?o(e)+":"+t:o(e))||e}var r,o=t("can-cid");r={set:function(e,t,n,i){e[a(t,i)]=n},getAndDelete:function(e,t,n){var i=a(t,n),r=e[i];return delete e[i],r}},i.exports=r}(0,e,0,n)}),define("can-view-scope/make-compute-like",["require","exports","module","can-util/js/single-reference/single-reference","can-reflect"],function(e,t,n){var i=e("can-util/js/single-reference/single-reference"),a=e("can-reflect"),r=function(e){return arguments.length?a.setValue(this,e):a.getValue(this)};n.exports=function(e){var t=r.bind(e);return t.on=t.bind=t.addEventListener=function(n,a){var r=function(e,n){a.call(t,{type:"change"},e,n)};i.set(a,this,r),e.on(r)},t.off=t.unbind=t.removeEventListener=function(t,n){e.off(i.getAndDelete(n,this))},a.assignSymbols(t,{"can.getValue":function(){return a.getValue(e)},"can.setValue":function(t){return a.setValue(e,t)},"can.onValue":function(t,n){return a.onValue(e,t,n)},"can.offValue":function(t,n){return a.offValue(e,t,n)},"can.valueHasDependencies":function(){return a.valueHasDependencies(e)},"can.getPriority":function(){return a.getPriority(e)},"can.setPriority":function(t){a.setPriority(e,t)},"can.isValueLike":!0,"can.isFunctionLike":!1}),t.isComputed=!0,t}}),define("can-view-scope/compute_data",["require","exports","module","can-observation","can-stache-key","can-util/js/assign/assign","can-reflect","can-symbol","can-key-tree","can-queues","can-observation-recorder","can-cid/set/set","can-view-scope/make-compute-like"],function(e,t,n){"use strict";var i=e("can-observation"),a=e("can-stache-key"),r=e("can-util/js/assign/assign"),o=e("can-reflect"),s=e("can-symbol"),c=e("can-key-tree"),l=e("can-queues"),u=e("can-observation-recorder"),d=e("can-cid/set/set"),p=e("can-view-scope/make-compute-like"),f=u.ignore(o.getValue.bind(o)),h=u.ignore(function(e){if(e.reads&&1===e.reads.length){var t=e.root;return t&&t[s.for("can.getValue")]&&(t=o.getValue(t)),t&&o.isObservableLike(t)&&o.isMapLike(t)&&"function"!=typeof t[e.reads[0].key]&&t}}),v=function(e){return e&&"number"==typeof e.batchNum&&"string"==typeof e.type},m=function(e,t,n){this.startingScope=e,this.key=t,this.options=r({observation:this.observation},n);var a;this.read=this.read.bind(this),this.dispatch=this.dispatch.bind(this),Object.defineProperty(this.read,"name",{value:"{{"+this.key+"}}::ScopeKeyData.read"}),Object.defineProperty(this.dispatch,"name",{value:o.getName(this)+".dispatch"}),this.handlers=new c([Object,Array],{onFirst:this.setup.bind(this),onEmpty:this.teardown.bind(this)}),a=this.observation=new i(this.read,this),this.fastPath=void 0,this.root=void 0,this.initialValue=void 0,this.reads=void 0,this.setRoot=void 0;var s=new d;s.add(a),this.dependencies={valueDependencies:s}};m.prototype={constructor:m,dispatch:function(e){var t=this.value;this.value=e,l.enqueueByQueue(this.handlers.getNode([]),this,[e,t],null,[o.getName(this),"changed to",e,"from",t])},setup:function(){this.bound=!0,o.onValue(this.observation,this.dispatch,"notify");var e=h(this);e&&this.toFastPath(e),this.value=f(this.observation)},teardown:function(){this.bound=!1,o.offValue(this.observation,this.dispatch,"notify"),this.toSlowPath()},set:function(e){var t=this.root||this.setRoot;t?a.write(t,this.reads,e,this.options):this.startingScope.set(this.key,e,this.options)},get:function(){return u.isRecording()&&(u.add(this),this.bound||i.temporarilyBind(this)),!0===this.bound?this.value:this.observation.get()},on:function(e,t){this.handlers.add([t||"mutate",e])},off:function(e,t){this.handlers.delete([t||"mutate",e])},toFastPath:function(e){var t=this,n=this.observation;this.fastPath=!0,n.dependencyChange=function(n,a){if(v(a))throw"no event objects!";return n===e&&"function"!=typeof a?this.newVal=a:t.toSlowPath(),i.prototype.dependencyChange.apply(this,arguments)},n.start=function(){this.value=this.newVal}},toSlowPath:function(){this.observation.dependencyChange=i.prototype.dependencyChange,this.observation.start=i.prototype.start,this.fastPath=!1},read:function(){if(this.root)return a.read(this.root,this.reads,this.options).value;var e=this.startingScope.read(this.key,this.options);return this.scope=e.scope,this.reads=e.reads,this.root=e.rootObserve,this.setRoot=e.setRoot,this.initialValue=e.value},hasDependencies:function(){return o.valueHasDependencies(this.observation)}},o.assignSymbols(m.prototype,{"can.getValue":m.prototype.get,"can.setValue":m.prototype.set,"can.onValue":m.prototype.on,"can.offValue":m.prototype.off,"can.valueHasDependencies":m.prototype.hasDependencies,"can.getValueDependencies":function(){return this.dependencies},"can.getPriority":function(){return o.getPriority(this.observation)},"can.setPriority":function(e){o.setPriority(this.observation,e)},"can.getName":function(){return o.getName(this.constructor)+"{{"+this.key+"}}"}}),Object.defineProperty(m.prototype,"compute",{get:function(){var e=p(this);return Object.defineProperty(this,"compute",{value:e,writable:!1,configurable:!1}),e},configurable:!0}),n.exports=function(e,t,n){return new m(e,t,n||{args:[]})}}),define("can-util/js/log/log",["require","exports","module","can-log"],function(e,t,n){"use strict";n.exports=e("can-log")}),define("can-view-scope",["require","exports","module","can-stache-key","can-observation","can-view-scope/reference-map","can-view-scope/compute_data","can-util/js/assign/assign","can-util/js/each/each","can-namespace","can-util/js/dev/dev","can-reflect","can-util/js/log/log"],function(e,t,n){function i(e,t,n){this._context=e,this._parent=t,this._meta=n||{},this.__cache={}}function a(e,t,n){e.helpers||e.partials||e.tags||(e={helpers:e}),i.call(this,e,t,n)}var r=e("can-stache-key"),o=e("can-observation"),s=e("can-view-scope/reference-map"),c=e("can-view-scope/compute_data"),l=e("can-util/js/assign/assign"),u=e("can-util/js/each/each"),d=e("can-namespace"),p=e("can-util/js/dev/dev"),f=e("can-reflect"),h=e("can-util/js/log/log");l(i,{read:r.read,Refs:s,refsScope:function(){return new i(new this.Refs)},keyInfo:function(e){var t={};return t.isDotSlash="./"===e.substr(0,2),t.isThisDot="this."===e.substr(0,5),t.isThisAt="this@"===e.substr(0,5),t.isInCurrentContext=t.isDotSlash||t.isThisDot||t.isThisAt,t.isInParentContext="../"===e.substr(0,3),t.isCurrentContext="."===e||"this"===e,t.isParentContext=".."===e,t.isContextBased=t.isInCurrentContext||t.isInParentContext||t.isCurrentContext||t.isParentContext,t}}),l(i.prototype,{add:function(e,t){return e!==this._context?new this.constructor(e,this,t):this},read:function(e,t){if("%root"===e)return{value:this.getRoot()};if("%scope"===e)return{value:this};var n=i.keyInfo(e);if(n.isContextBased&&this._meta.notContext)return this._parent.read(e,t);var a;if(n.isInCurrentContext)a=!0,e=n.isDotSlash?e.substr(2):e.substr(5);else{if(n.isInParentContext||n.isParentContext){for(var o=this._parent;o._meta.notContext;)o=o._parent;return n.isParentContext?r.read(o._context,[],t):o.read(e.substr(3)||".",t)}if(n.isCurrentContext)return r.read(this._context,[],t)}var s=r.reads(e);return"*"===s[0].key.charAt(0)?this.getRefs()._read(s,t,!0):this._read(s,t,a)},_read:function(e,t,n){for(var i,a,s,c,u,d=this,p=[],f=-1,h=l({foundObservable:function(t,n){a=t,s=e.slice(n)},earlyExit:function(t,n){(n>f||n===f&&"object"==typeof t&&e[n].key in t)&&(u=a,c=s,f=n)}},t),v=o.isRecording();d;){if(null!==(i=d._context)&&("object"==typeof i||"function"==typeof i)){var m=o.trap(),g=r.read(i,e,h),y=m();if(void 0!==g.value)return!y.length&&v?(a=g.parent,s=e.slice(e.length-1)):o.addAll(y),{scope:d,rootObserve:a,value:g.value,reads:s};p.push.apply(p,y)}d=n?null:d._parent}return o.addAll(p),{setRoot:u,reads:c,value:void 0}},get:function(e,t){return t=l({isArgument:!0},t),this.read(e,t).value},peek:o.ignore(function(e,t){return this.get(e,t)}),peak:o.ignore(function(e,t){return p.warn("peak is deprecated, please use peek instead"),this.peek(e,t)}),getScope:function(e){for(var t=this;t;){if(e(t))return t;t=t._parent}},getContext:function(e){var t=this.getScope(e);return t&&t._context},getRefs:function(){var e,t=this.getScope(function(t){return e=t,t._context instanceof i.Refs});return t||(e._parent=i.refsScope(),t=e._parent),t},getRoot:function(){for(var e=this,t=this;e._parent;)t=e,e=e._parent;return e._context instanceof i.Refs&&(e=t),e._context},set:function(e,t,n){n=n||{};var a=i.keyInfo(e);if(a.isCurrentContext)return f.setValue(this._context,t);if(a.isInParentContext||a.isParentContext){for(var o=this._parent;o._meta.notContext;)o=o._parent;return a.isParentContext?f.setValue(o._context,t):o.set(e.substr(3)||".",t,n)}var s,c,l=e.lastIndexOf("."),u=e.lastIndexOf("/");if(u>l?(s=e.substring(0,u),c=e.substring(u+1,e.length)):-1!==l?(s=e.substring(0,l),c=e.substring(l+1,e.length)):(s=".",c=e),"*"===e.charAt(0))r.write(this.getRefs()._context,e,t,n);else{var d=this.read(s,n).value;if(void 0===d)return void p.error("Attempting to set a value at "+e+" where "+s+" is undefined.");r.write(d,c,t,n)}},attr:o.ignore(function(e,t,n){return h.warn("can-view-scope::attr is deprecated, please use peek, get or set"),n=l({isArgument:!0},n),2===arguments.length?this.set(e,t,n):this.get(e,n)}),computeData:function(e,t){return c(this,e,t)},compute:function(e,t){return this.computeData(e,t).compute},cloneFromRef:function(){for(var e,t,n=[],a=this;a;){if((e=a._context)instanceof i.Refs){t=a._parent;break}n.unshift(e),a=a._parent}return t?(u(n,function(e){t=t.add(e)}),t):this}}),(a.prototype=new i).constructor=a,i.Options=a,d.view=d.view||{},n.exports=d.view.Scope=i}),define("can-simple-observable/log",["require","exports","module","can-log/dev/dev","can-reflect"],function(e,t,n){function i(e){return"string"==typeof e?JSON.stringify(e):e}var a=e("can-log/dev/dev"),r=e("can-reflect");n.exports=function(){this._log=function(e,t){a.log(r.getName(this),"\n is ",i(t),"\n was ",i(e))}}}),define("can-simple-observable",["require","exports","module","can-reflect","can-observation-recorder","can-namespace","can-key-tree","can-queues","can-simple-observable/log"],function(e,t,n){function i(e){this.handlers=new s([Object,Array]),this.value=e}var a=e("can-reflect"),r=e("can-observation-recorder"),o=e("can-namespace"),s=e("can-key-tree"),c=e("can-queues");i.prototype={constructor:i,get:function(){return r.add(this),this.value},set:function(e){var t=this.value;this.value=e,c.enqueueByQueue(this.handlers.getNode([]),this,[e,t],null,[a.getName(this),"changed to",e,"from",t]),"function"==typeof this._log&&this._log(t,e)},on:function(e,t){this.handlers.add([t||"mutate",e])},off:function(e,t){this.handlers.delete([t||"mutate",e])},log:e("can-simple-observable/log")},a.assignSymbols(i.prototype,{"can.getValue":i.prototype.get,"can.setValue":i.prototype.set,"can.onValue":i.prototype.on,"can.offValue":i.prototype.off,"can.isMapLike":!1,"can.valueHasDependencies":function(){return!0},"can.getName":function(){var e=this.value;return e="object"!=typeof e||null===e?JSON.stringify(e):"",a.getName(this.constructor)+"<"+e+">"}}),n.exports=o.SimpleObservable=i}),define("can-simple-observable/settable/settable",["require","exports","module","can-reflect","can-observation-recorder","can-simple-observable","can-observation","can-key-tree","can-queues","can-simple-observable/log"],function(e,t,n){function i(e,t,n){function i(){return e.call(t,this.lastSetValue.get())}this.handlers=new c([Object,Array],{onFirst:this.setup.bind(this),onEmpty:this.teardown.bind(this)}),this.lastSetValue=new o(n),this.handler=this.handler.bind(this),a.assignSymbols(this,{"can.getName":function(){return a.getName(this.constructor)+"<"+a.getName(e)+">"}}),Object.defineProperty(this.handler,"name",{value:a.getName(this)+".handler"}),Object.defineProperty(i,"name",{value:a.getName(e)+"::"+a.getName(this.constructor)}),this.observation=new s(i,this)}var a=e("can-reflect"),r=e("can-observation-recorder"),o=e("can-simple-observable"),s=e("can-observation"),c=e("can-key-tree"),l=e("can-queues"),u=e("can-simple-observable/log"),d=r.ignore(a.getValue.bind(a));(i.prototype={handler:function(e){var t=this.value;this.value=e,"function"==typeof this._log&&this._log(t,e),l.enqueueByQueue(this.handlers.getNode([]),this,[e,t],function(){return{}})},setup:function(){this.bound=!0,a.onValue(this.observation,this.handler,"notify"),this.value=d(this.observation)},teardown:function(){this.bound=!1,a.offValue(this.observation,this.handler,"notify")},set:function(e){e!==this.lastSetValue.get()&&this.lastSetValue.set(e)},get:function(){return r.isRecording()&&(r.add(this),this.bound||s.temporarilyBind(this)),!0===this.bound?this.value:this.observation.get()},on:function(e,t){this.handlers.add([t||"mutate",e])},off:function(e,t){this.handlers.delete([t||"mutate",e])},hasDependencies:function(){return a.valueHasDependencies(this.observation)},getValueDependencies:function(){return a.getValueDependencies(this.observation)},log:u}).constructor=i,a.assignSymbols(i.prototype,{"can.getValue":i.prototype.get,"can.setValue":i.prototype.set,"can.onValue":i.prototype.on,"can.offValue":i.prototype.off,"can.isMapLike":!1,"can.getPriority":function(){return a.getPriority(this.observation)},"can.setPriority":function(e){a.setPriority(this.observation,e)},"can.valueHasDependencies":i.prototype.hasDependencies,"can.getValueDependencies":i.prototype.getValueDependencies}),n.exports=i}),define("can-stache/src/key-observable",["require","exports","module","can-simple-observable/settable/settable","can-stache-key"],function(e,t,n){function i(e,t){t=""+t,this.key=t,this.root=e,a.call(this,function(){return r.get(this,t)},e)}var a=e("can-simple-observable/settable/settable"),r=e("can-stache-key");(i.prototype=Object.create(a.prototype)).set=function(e){r.set(this.root,this.key,e)},n.exports=i}),define("can-stache/src/utils",["require","exports","module","can-view-scope","can-observation","can-stache-key","can-reflect","can-stache/src/key-observable","can-util/js/is-array-like/is-array-like"],function(e,t,n){var i=e("can-view-scope"),a=e("can-observation"),r=e("can-stache-key"),o=e("can-reflect"),s=e("can-stache/src/key-observable"),c=e("can-util/js/is-array-like/is-array-like"),l=i.Options,u=function(){};n.exports={isArrayLike:c,emptyHandler:function(){},jsonParse:function(e){return"'"===e[0]?e.substr(1,e.length-2):"undefined"===e?void 0:JSON.parse(e)},mixins:{last:function(){return this.stack[this.stack.length-1]},add:function(e){this.last().add(e)},subSectionDepth:function(){return this.stack.length-1}},convertToScopes:function(e,t,n,i,a,r,o){e.fn=a?this.makeRendererConvertScopes(a,t,n,i,o):u,e.inverse=r?this.makeRendererConvertScopes(r,t,n,i,o):u,e.isSection=!(!a&&!r)},makeRendererConvertScopes:function(e,t,n,r,o){var s=function(n,i,a){return e(n||t,i,a)},c=function(e,a,o){return void 0===e||e instanceof i||(e=t?t.add(e):i.refsScope().add(e||{})),void 0===a||a instanceof l||(a=n.add(a)),s(e,a||n,o||r)};return o?c:a.ignore(c)},getItemsStringContent:function(e,t,n,i){for(var a="",c=r.get(e,"length"),l=o.isObservableLike(e),u=0;u<c;u++){var d=l?new s(e,u):e[u];a+=n.fn(d,i)}return a},getItemsFragContent:function(e,t,n,i){for(var a=[],c=r.get(e,"length"),l=o.isObservableLike(e),u=0;u<c;u++){var d={"%index":u},p=l?new s(e,u):e[u];i&&(d[i]=p),a.push(t.fn(n.add(d,{notContext:!0}).add(p)))}return a},Options:l}}),define("can-attribute-encoder",["require","exports","module","can-namespace","can-log/dev/dev"],function(e,t,n){function i(e,t){for(var n=0;n<e.length;n++)t(e[n],n)}function a(e,t,n){return t+"-"+n.toLowerCase()}function r(e,t){return 0===e.indexOf(t)}function o(e,t){return e.length-e.indexOf(t)===t.length}var s=e("can-namespace"),c=e("can-log/dev/dev"),l=function(e){var t={};return i(e.split(","),function(e){t[e]=!0}),t}("allowReorder,attributeName,attributeType,autoReverse,baseFrequency,baseProfile,calcMode,clipPathUnits,contentScriptType,contentStyleType,diffuseConstant,edgeMode,externalResourcesRequired,filterRes,filterUnits,glyphRef,gradientTransform,gradientUnits,kernelMatrix,kernelUnitLength,keyPoints,keySplines,keyTimes,lengthAdjust,limitingConeAngle,markerHeight,markerUnits,markerWidth,maskContentUnits,maskUnits,patternContentUnits,patternTransform,patternUnits,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,repeatCount,repeatDur,requiredExtensions,requiredFeatures,specularConstant,specularExponent,spreadMethod,startOffset,stdDeviation,stitchTiles,surfaceScale,systemLanguage,tableValues,textLength,viewBox,viewTarget,xChannelSelector,yChannelSelector"),u={leftParens:/\(/g,rightParens:/\)/g,leftBrace:/\{/g,rightBrace:/\}/g,camelCase:/([a-z])([A-Z])/g,forwardSlash:/\//g,space:/\s/g,uppercase:/[A-Z]/g,uppercaseDelimiterThenChar:/:u:([a-z])/g,caret:/\^/g,dollar:/\$/g,at:/@/g},d={prependUppercase:":u:",replaceSpace:":s:",replaceForwardSlash:":f:",replaceLeftParens:":lp:",replaceRightParens:":rp:",replaceLeftBrace:":lb:",replaceRightBrace:":rb:",replaceCaret:":c:",replaceDollar:":d:",replaceAt:":at:"},p={};if(p.encode=function(e){var t=e;return!l[t]&&t.match(u.camelCase)&&(r(t,"on:")||o(t,":to")||o(t,":from")||o(t,":bind")?t=t.replace(u.uppercase,function(e){return d.prependUppercase+e.toLowerCase()}):(t=t.replace(u.camelCase,a),c.warn("can-attribute-encoder: Found attribute with name: "+e+". Converting to: "+t+"."))),t=t.replace(u.space,d.replaceSpace).replace(u.forwardSlash,d.replaceForwardSlash).replace(u.leftParens,d.replaceLeftParens).replace(u.rightParens,d.replaceRightParens).replace(u.leftBrace,d.replaceLeftBrace).replace(u.rightBrace,d.replaceRightBrace).replace(u.caret,d.replaceCaret).replace(u.dollar,d.replaceDollar).replace(u.at,d.replaceAt)},p.decode=function(e){var t=e;return t=t.replace(d.replaceLeftParens,"(").replace(d.replaceRightParens,")").replace(d.replaceLeftBrace,"{").replace(d.replaceRightBrace,"}").replace(d.replaceForwardSlash,"/").replace(d.replaceSpace," ").replace(d.replaceCaret,"^").replace(d.replaceDollar,"$").replace(d.replaceAt,"@"),!l[t]&&t.match(u.uppercaseDelimiterThenChar)&&(r(t,"on:")||o(t,":to")||o(t,":from")||o(t,":bind"))&&(t=t.replace(u.uppercaseDelimiterThenChar,function(e,t){return t.toUpperCase()})),t},s.encoder)throw new Error("You can't have two versions of can-attribute-encoder, check your dependencies");n.exports=s.encoder=p}),define("can-view-parser",["require","exports","module","can-namespace","can-log/dev/dev","can-attribute-encoder"],function(e,t,n){function i(e,t){for(var n=0;n<e.length;n++)t(e[n],n)}function a(e){var t={};return i(e.split(","),function(e){t[e]=!0}),t}function r(e,t){for(var n=0,i=e.length;n<i;n++){var a=e[n];t[a.tokenType].apply(t,a.args)}return e}function o(e){return e.split("\n").length-1}var s=e("can-namespace"),c=e("can-log/dev/dev"),l=e("can-attribute-encoder"),u=new RegExp("^<\\/([-:_A-Za-z0-9]+)[^>]*>"),d=new RegExp("\\{\\{(![\\s\\S]*?!|[\\s\\S]*?)\\}\\}\\}?","g"),p=/\s/,f=new RegExp("[A-Za-z0-9]"),h=a("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed"),v=a("altGlyph,altGlyphDef,altGlyphItem,animateColor,animateMotion,animateTransform,clipPath,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,foreignObject,glyphRef,linearGradient,radialGradient,textPath"),m=a("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr"),g=a("script"),y="start,end,close,attrStart,attrEnd,attrValue,chars,comment,special,done".split(","),b={"{":"}","(":")"},w=function(){},k=function(e,t,n){function a(e,n){var i;if(n)for(n=v[n]?n:n.toLowerCase(),i=V.length-1;i>=0&&V[i]!==n;i--);else i=0;if(void 0===e?V.length>0&&(t.filename?c.warn(t.filename+": expected closing tag </"+V[i]+">"):c.warn("expected closing tag </"+V[i]+">")):(i<0||i!==V.length-1)&&(V.length>0?t.filename?c.warn(t.filename+":"+b+": unexpected closing tag "+e+" expected </"+V[V.length-1]+">"):c.warn(b+": unexpected closing tag "+e+" expected </"+V[V.length-1]+">"):t.filename?c.warn(t.filename+":"+b+": unexpected closing tag "+e):c.warn(b+": unexpected closing tag "+e)),i>=0){for(var a=V.length-1;a>=i;a--)t.close&&t.close(V[a],b);V.length=i}}if("object"==typeof e)return r(e,t);var s=[];t=t||{},n&&i(y,function(e){var n=t[e]||w;t[e]=function(){if(!1!==n.apply(this,arguments)){var t=arguments.length;void 0===arguments[t-1]&&(t=arguments.length-1),t=arguments.length,s.push({tokenType:e,args:[].slice.call(arguments,0,t)})}}});var l,p,f,b,x=t.magicMatch||d,j=t.magicStart||"{{",E=function(){C&&(t.chars&&t.chars(C,b),b+=o(C)),C=""},V=[],O=e,C="";for(b=1,V.last=function(){return this[this.length-1]};e;){if(p=!0,V.last()&&g[V.last()])e=e.replace(new RegExp("([\\s\\S]*?)</"+V.last()+"[^>]*>"),function(e,n){return n=n.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g,"$1$2"),t.chars&&t.chars(n,b),b+=o(n),""}),a("",V.last());else{if(0===e.indexOf("\x3c!--"))(l=e.indexOf("--\x3e"))>=0&&(E(),t.comment&&t.comment(e.substring(4,l),b),b+=o(e.substring(0,l+3)),e=e.substring(l+3),p=!1);else if(0===e.indexOf("</"))(f=e.match(u))&&(E(),f[0].replace(u,a),b+=o(e.substring(0,f[0].length)),e=e.substring(f[0].length),p=!1);else if(0===e.indexOf("<")){var _=k.searchStartTag(e);_&&(E(),function(e,n,i,r){n=v[n]?n:n.toLowerCase(),m[n]&&V.last()===n&&a("",n),r=h[n]||!!r,t.start(n,r,b),r||V.push(n),k.parseAttrs(i,t,b),b+=o(e),t.end(n,r,b)}.apply(null,_.match),e=_.html,p=!1)}else 0===e.indexOf(j)&&(f=e.match(x))&&(E(),f[0].replace(x,function(e,n){t.special&&t.special(n,b)}),b+=o(e.substring(0,f[0].length)),e=e.substring(f[0].length));if(p){0===(l=L(e,j))&&e===O&&(C+=e.charAt(0),e=e.substr(1),l=L(e,j));var D=l<0?e:e.substring(0,l);e=l<0?"":e.substring(l),D&&(C+=D)}}if(e===O)throw new Error("Parse Error: "+e);O=e}return E(),a(),t.done(b),s},x=function(e,t,n,i,a){var r=i.substring("number"==typeof e.nameStart?e.nameStart:t,t),o=l.encode(r);e.attrStart=o,n.attrStart(e.attrStart,a),e.inName=!1},j=function(e,t,n,i,a){if(void 0!==e.valueStart&&e.valueStart<t){var r,o,s=i.substring(e.valueStart,t);o=(r=(r=i.substring(e.valueStart-1,t+1)).trim()).charAt(r.length-1),e.inQuote!==o&&(n.filename?c.warn(n.filename+":"+a+": End quote is missing for "+s):c.warn(a+": End quote is missing for "+s)),n.attrValue(s,a)}n.attrEnd(e.attrStart,a),e.attrStart=void 0,e.valueStart=void 0,e.inValue=!1,e.inName=!1,e.lookingForEq=!1,e.inQuote=!1,e.lookingForName=!0},L=function(e,t){for(var n=t.length,i=0,a=e.length;i<a;i++)if("<"===e[i]||e.substr(i,n)===t)return i;return-1};k.parseAttrs=function(e,t,n){if(e){for(var i,a=t.magicMatch||d,r=t.magicStart||"{{",o=0,s={inName:!1,nameStart:void 0,inValue:!1,valueStart:void 0,inQuote:!1,attrStart:void 0,lookingForName:!0,lookingForValue:!1,lookingForEq:!1};o<e.length;){i=o;var c=e.charAt(o);if(o++,r===e.substr(i,r.length)){s.inValue&&i>s.valueStart?t.attrValue(e.substring(s.valueStart,i),n):s.inName&&s.nameStart<i?(x(s,i,t,e,n),j(s,i,t,e,n)):s.lookingForValue?s.inValue=!0:s.lookingForEq&&s.attrStart&&j(s,i,t,e,n),a.lastIndex=i;var l=a.exec(e);l&&(t.special(l[1],n),o=i+l[0].length,s.inValue&&(s.valueStart=i+l[0].length))}else if(s.inValue)s.inQuote?c===s.inQuote&&j(s,i,t,e,n):p.test(c)&&j(s,i,t,e,n);else if("="===c&&(s.lookingForEq||s.lookingForName||s.inName))s.attrStart||x(s,i,t,e,n),s.lookingForValue=!0,s.lookingForEq=!1,s.lookingForName=!1;else if(s.inName){var u,f=e[s.nameStart];b[f]===c?(u=b["{"===f?"(":"{"],e[i+1]===u?(x(s,i+2,t,e,n),o++):x(s,i+1,t,e,n),s.lookingForEq=!0):p.test(c)&&"{"!==f&&"("!==f&&(x(s,i,t,e,n),s.lookingForEq=!0)}else s.lookingForName?p.test(c)||(s.attrStart&&j(s,i,t,e,n),s.nameStart=i,s.inName=!0):s.lookingForValue&&(p.test(c)?o===e.length&&j(s,i,t,e,n):(s.lookingForValue=!1,s.inValue=!0,"'"===c||'"'===c?(s.inQuote=c,s.valueStart=i+1):s.valueStart=i))}s.inName?(x(s,i+1,t,e,n),j(s,i+1,t,e,n)):(s.lookingForEq||s.lookingForValue||s.inValue)&&j(s,i+1,t,e,n),a.lastIndex=0}},k.searchStartTag=function(e){var t=e.indexOf(">");if(-1===t||!f.test(e[1]))return null;var n,i,a,r="",o="",s=e.substring(0,t+1),c="/"===s[s.length-2],l=s.search(p);return c?(o="/",i=s.substring(1,s.length-2).trim()):i=s.substring(1,s.length-1).trim(),-1===l?n=i:(l--,n=i.substring(0,l),r=i.substring(l)),a=[s,n,r,o],{match:a,html:e.substring(s.length)}},n.exports=s.HTMLParser=k}),define("can-util/js/set-immediate/set-immediate",["require","exports","module","can-globals/global/global"],function(e,t,n){!function(e,t,n,i){"use strict";var e=t("can-globals/global/global")();i.exports=e.setImmediate||function(e){return setTimeout(e,0)}}(function(){return this}(),e,0,n)}),define("can-util/dom/child-nodes/child-nodes",function(e,t,n){"use strict";n.exports=function(e){var t=e.childNodes;if("length"in t)return t;for(var n=e.firstChild,i=[];n;)i.push(n),n=n.nextSibling;return i}}),define("can-util/dom/contains/contains",function(e,t,n){"use strict";n.exports=function(e){return this.contains(e)}}),define("can-util/dom/mutate/mutate",["require","exports","module","can-util/js/make-array/make-array","can-util/js/set-immediate/set-immediate","can-cid","can-globals/mutation-observer/mutation-observer","can-util/dom/child-nodes/child-nodes","can-util/dom/contains/contains","can-util/dom/dispatch/dispatch","can-globals/document/document","can-util/dom/data/data"],function(e,t,n){!function(e,t,n,i){"use strict";var a,r=t("can-util/js/make-array/make-array"),o=t("can-util/js/set-immediate/set-immediate"),s=t("can-cid"),c=t("can-globals/mutation-observer/mutation-observer"),l=t("can-util/dom/child-nodes/child-nodes"),u=t("can-util/dom/contains/contains"),d=t("can-util/dom/dispatch/dispatch"),p=t("can-globals/document/document"),f=t("can-util/dom/data/data"),h={inserted:function(e,t){return u.call(e,t)},removed:function(e,t){return!u.call(e,t)}},v=function(e,t,n,i,a){if(e.length)for(var o,c,l,u=0;void 0!==(l=e[u]);u++)if(c=s(l),l.getElementsByTagName&&n(t,l)&&!a[c]){a[c]=!0,o=r(l.getElementsByTagName("*")),d.call(l,i,[],!1),"removed"===i&&f.delete.call(l);for(var p,h=0;void 0!==(p=o[h]);h++)a[c=s(p)]||(d.call(p,i,[],!1),"removed"===i&&f.delete.call(p),a[c]=!0)}},m=function(){var e=a;a=null;var t=e[0][1][0],n=p()||t.ownerDocument||t,i=n.contains?n:n.documentElement,r={inserted:{},removed:{}};e.forEach(function(e){v(e[1],i,h[e[0]],e[0],r[e[0]])})},g=function(e,t){if(!c()&&e.length){var n=e[0],i=p()||n.ownerDocument||n,r=i.contains?i:i.documentElement;h.inserted(r,n)&&(a||(a=[],o(m)),a.push([t,e]))}};i.exports={appendChild:function(e){if(c())this.appendChild(e);else{var t;t=11===e.nodeType?r(l(e)):[e],this.appendChild(e),g(t,"inserted")}},insertBefore:function(e,t,n){if(c())this.insertBefore(e,t);else{var i;i=11===e.nodeType?r(l(e)):[e],this.insertBefore(e,t),g(i,"inserted")}},removeChild:function(e){c()?this.removeChild(e):(g([e],"removed"),this.removeChild(e))},replaceChild:function(e,t){if(c())this.replaceChild(e,t);else{var n;n=11===e.nodeType?r(l(e)):[e],g([t],"removed"),this.replaceChild(e,t),g(n,"inserted")}},inserted:function(e){g(e,"inserted")},removed:function(e){g(e,"removed")}}}(0,e,0,n)}),define("can-cid/map/map",["require","exports","module","can-cid","can-cid/helpers"],function(e,t,n){"use strict";var i,a=e("can-cid").get,r=e("can-cid/helpers");"undefined"!=typeof Map?i=Map:((i=function(){this.values={}}).prototype.set=function(e,t){this.values[a(e)]={key:e,value:t}},i.prototype.delete=function(e){var t=a(e)in this.values;return t&&delete this.values[a(e)],t},i.prototype.forEach=function(e,t){r.each(this.values,function(n){return e.call(t||this,n.value,n.key,this)},this)},i.prototype.has=function(e){return a(e)in this.values},i.prototype.get=function(e){var t=this.values[a(e)];return t&&t.value},i.prototype.clear=function(){return this.values={}},Object.defineProperty(i.prototype,"size",{get:function(){var e=0;return r.each(this.values,function(){e++}),e}})),n.exports=i}),define("can-util/js/cid-map/cid-map",["require","exports","module","can-cid/map/map"],function(e,t,n){!function(e,t,n,i){"use strict";i.exports=t("can-cid/map/map")}(0,e,0,n)}),define("can-view-nodelist",["require","exports","module","can-util/js/make-array/make-array","can-util/js/each/each","can-namespace","can-util/dom/mutate/mutate","can-util/js/cid-map/cid-map"],function(e,t,n){var i=e("can-util/js/make-array/make-array"),a=e("can-util/js/each/each"),r=e("can-namespace"),o=e("can-util/dom/mutate/mutate"),s=e("can-util/js/cid-map/cid-map"),c=new s,l=[].splice,u=[].push,d=function(e){for(var t=0,n=0,i=e.length;n<i;n++){var a=e[n];a.nodeType?t++:t+=d(a)}return t},p=function(e){for(var t=new s,n=0,i=e.length;n<i;n++){var a=h.first(e[n]);t.set(a,e[n])}return t},f=function(e,t){t.forEach(function(t){e.newDeepChildren.push(t)})},h={update:function(e,t){var n=h.unregisterChildren(e);t=i(t);var a=e.length;return l.apply(e,[0,a].concat(t)),e.replacements?(h.nestReplacements(e),e.deepChildren=e.newDeepChildren,e.newDeepChildren=[]):h.nestList(e),n},nestReplacements:function(e){for(var t=0,n=p(e.replacements),i=e.replacements.length;t<e.length&&i;){var a=e[t],r=n.get(a);r&&(n.delete(a),e.splice(t,d(r),r),i--),t++}i&&f(e,n),e.replacements=[]},nestList:function(e){for(var t=0;t<e.length;){var n=e[t],i=c.get(n);i?i!==e&&e.splice(t,d(i),i):c.set(n,e),t++}},last:function(e){var t=e[e.length-1];return t.nodeType?t:h.last(t)},first:function(e){var t=e[0];return t.nodeType?t:h.first(t)},flatten:function(e){for(var t=[],n=0;n<e.length;n++){var i=e[n];i.nodeType?t.push(i):t.push.apply(t,h.flatten(i))}return t},register:function(e,t,n,i){return e.unregistered=t,e.parentList=n,e.nesting=n&&void 0!==n.nesting?n.nesting+1:0,n?(e.deepChildren=[],e.newDeepChildren=[],e.replacements=[],!0!==n&&(i?n.replacements.push(e):n.newDeepChildren.push(e))):h.nestList(e),e},unregisterChildren:function(e){var t=[];return a(e,function(n){n.nodeType?(e.replacements||c.delete(n),t.push(n)):u.apply(t,h.unregister(n,!0))}),a(e.deepChildren,function(e){h.unregister(e,!0)}),t},unregister:function(e,t){var n=h.unregisterChildren(e,!0);if(e.unregistered){var i=e.unregistered;if(e.replacements=e.unregistered=null,!t){var a=e.parentList&&e.parentList.deepChildren;if(a){var r=a.indexOf(e);-1!==r&&a.splice(r,1)}}i()}return n},after:function(e,t){var n=e[e.length-1];n.nextSibling?o.insertBefore.call(n.parentNode,t,n.nextSibling):o.appendChild.call(n.parentNode,t)},replace:function(e,t){var n,i=e[0].parentNode;"SELECT"===i.nodeName.toUpperCase()&&i.selectedIndex>=0&&(n=i.value),1===e.length?o.replaceChild.call(i,t,e[0]):(h.after(e,t),h.remove(e)),void 0!==n&&(i.value=n)},remove:function(e){var t=e[0]&&e[0].parentNode;a(e,function(e){o.removeChild.call(t,e)})},nodeMap:c};n.exports=r.nodeLists=h}),define("can-util/dom/fragment/fragment",["require","exports","module","can-globals/document/document","can-util/dom/child-nodes/child-nodes"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-globals/document/document"),r=t("can-util/dom/child-nodes/child-nodes"),o=/^\s*<(\w+)[^>]*>/,s={}.toString,c=function(e,t,n){void 0===t&&(t=o.test(e)&&RegExp.$1),e&&"[object Function]"===s.call(e.replace)&&(e=e.replace(/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,"<$1></$2>"));var i=n.createElement("div"),a=n.createElement("div");"tbody"===t||"tfoot"===t||"thead"===t||"colgroup"===t?(a.innerHTML="<table>"+e+"</table>",i=3===a.firstChild.nodeType?a.lastChild:a.firstChild):"col"===t?(a.innerHTML="<table><colgroup>"+e+"</colgroup></table>",i=3===a.firstChild.nodeType?a.lastChild:a.firstChild.firstChild):"tr"===t?(a.innerHTML="<table><tbody>"+e+"</tbody></table>",i=3===a.firstChild.nodeType?a.lastChild:a.firstChild.firstChild):"td"===t||"th"===t?(a.innerHTML="<table><tbody><tr>"+e+"</tr></tbody></table>",i=3===a.firstChild.nodeType?a.lastChild:a.firstChild.firstChild.firstChild):"option"===t?(a.innerHTML="<select>"+e+"</select>",i=3===a.firstChild.nodeType?a.lastChild:a.firstChild):i.innerHTML=""+e;var c={},l=r(i);c.length=l.length;for(var u=0;u<l.length;u++)c[u]=l[u];return[].slice.call(c)};i.exports=function(e,t){if(e&&11===e.nodeType)return e;t?t.length&&(t=t[0]):t=a();for(var n=c(e,void 0,t),i=(t||document).createDocumentFragment(),r=0,o=n.length;r<o;r++)i.appendChild(n[r]);return i}}(0,e,0,n)}),define("can-util/dom/frag/frag",["require","exports","module","can-globals/document/document","can-util/dom/fragment/fragment","can-util/js/each/each","can-util/dom/child-nodes/child-nodes"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-globals/document/document"),r=t("can-util/dom/fragment/fragment"),o=t("can-util/js/each/each"),s=t("can-util/dom/child-nodes/child-nodes"),c=function(e,t){var n,i=t||a();return e&&"string"!=typeof e?11===e.nodeType?e:"number"==typeof e.nodeType?((n=i.createDocumentFragment()).appendChild(e),n):"number"==typeof e.length?(n=i.createDocumentFragment(),o(e,function(e){n.appendChild(c(e))}),s(n).length||n.appendChild(i.createTextNode("")),n):(n=r(""+e,i),s(n).length||n.appendChild(i.createTextNode("")),n):((n=r(null==e?"":""+e,i)).childNodes.length||n.appendChild(i.createTextNode("")),n)};i.exports=c}(0,e,0,n)}),define("can-util/dom/is-of-global-document/is-of-global-document",["require","exports","module","can-globals/document/document"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-globals/document/document");i.exports=function(e){return(e.ownerDocument||e)===a()}}(0,e,0,n)}),define("can-util/dom/events/make-mutation-event/make-mutation-event",["require","exports","module","can-util/dom/events/events","can-util/dom/data/data","can-globals/mutation-observer/mutation-observer","can-util/dom/dispatch/dispatch","can-util/dom/mutation-observer/document/document","can-globals/document/document","can-cid/map/map","can-util/js/string/string","can-util/dom/is-of-global-document/is-of-global-document"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-util/dom/events/events"),r=t("can-util/dom/data/data"),o=t("can-globals/mutation-observer/mutation-observer"),s=t("can-util/dom/dispatch/dispatch"),c=t("can-util/dom/mutation-observer/document/document"),l=t("can-globals/document/document"),u=t("can-cid/map/map"),d=t("can-util/js/string/string");t("can-util/dom/is-of-global-document/is-of-global-document"),i.exports=function(e,t){var n=a.addEventListener,i=a.removeEventListener;a.addEventListener=function(i){if(i===e&&o()){var a=l().documentElement,p=r.get.call(a,e+"Data");if(p||(p={handler:function(t){p.nodeIdsRespondingToInsert.has(t)&&(s.call(t,e,[],!1),p.nodeIdsRespondingToInsert.delete(t))},nodeIdsRespondingToInsert:new u},c["on"+d.capitalize(t)](p.handler),r.set.call(a,e+"Data",p)),11!==this.nodeType){var f=p.nodeIdsRespondingToInsert.get(this)||0;p.nodeIdsRespondingToInsert.set(this,f+1)}}return n.apply(this,arguments)},a.removeEventListener=function(n){if(n===e&&o()){var a=l().documentElement,s=r.get.call(a,e+"Data");if(s){var u=s.nodeIdsRespondingToInsert.get(this)-1;u?s.nodeIdsRespondingToInsert.set(this,u):s.nodeIdsRespondingToInsert.delete(this),s.nodeIdsRespondingToInsert.size||(c["off"+d.capitalize(t)](s.handler),r.clean.call(a,e+"Data"))}}return i.apply(this,arguments)}}}(0,e,0,n)}),define("can-util/dom/events/removed/removed",["require","exports","module","can-util/dom/events/make-mutation-event/make-mutation-event"],function(e,t,n){"use strict";e("can-util/dom/events/make-mutation-event/make-mutation-event")("removed","removedNodes")}),define("can-view-live/lib/core",["require","exports","module","can-view-parser","can-util/dom/events/events","can-view-nodelist","can-util/dom/frag/frag","can-util/dom/child-nodes/child-nodes","can-reflect","can-util/dom/events/removed/removed","can-symbol"],function(e,t,n){var i=e("can-view-parser"),a=e("can-util/dom/events/events"),r=e("can-view-nodelist"),o=e("can-util/dom/frag/frag"),s=e("can-util/dom/child-nodes/child-nodes"),c=e("can-reflect");e("can-util/dom/events/removed/removed");var l=new WeakMap,u={setup:function(e,t,n){var i,r=!1,o=function(){return r||(r=!0,n(i),a.removeEventListener.call(e,"removed",o)),!0};return i={teardownCheck:function(e){return!e&&o()}},a.addEventListener.call(e,"removed",o),t(i),i},listen:function(e,t,n){return u.setup(e,function(){c.onValue(t,n,"notify"),u.addElementDependency(e,t)},function(i){c.offValue(t,n,"notify"),u.deleteElementDependency(e,t),i.nodeList&&r.unregister(i.nodeList)})},getAttributeParts:function(e){var t,n={};return i.parseAttrs(e,{attrStart:function(e){n[e]="",t=e},attrValue:function(e){n[t]+=e},attrEnd:function(){}}),n},isNode:function(e){return e&&e.nodeType},addTextNodeIfNoChildren:function(e){e.firstChild||e.appendChild(e.ownerDocument.createTextNode(""))},replace:function(e,t,n){var i=e.slice(0),a=o(t);return r.register(e,n),r.update(e,s(a)),r.replace(i,a),e},getParentNode:function(e,t){return t&&11===e.parentNode.nodeType?t:e.parentNode},makeString:function(e){return null==e?"":""+e},addElementDependency:function(e,t){var n=l.get(e);n?n.add(t):l.set(e,new Set([t]))},deleteElementDependency:function(e,t){var n=l.get(e);n&&(n.delete(t),n.size||l.delete(e))}},d=e("can-symbol").for("can.getValueDependencies");Element.prototype[d]=function(){var e=this;if(l.has(e))return{valueDependencies:l.get(e)}},n.exports=u}),define("can-types",["require","exports","module","can-namespace","can-reflect","can-symbol","can-log/dev/dev"],function(e,t,n){var i=e("can-namespace"),a=e("can-reflect"),r=e("can-symbol"),o=e("can-log/dev/dev"),s={isMapLike:function(e){return o.warn("can-types.isMapLike(obj) is deprecated, please use `canReflect.isObservableLike(obj) && canReflect.isMapLike(obj)` instead."),a.isObservableLike(e)&&a.isMapLike(e)},isListLike:function(e){return o.warn("can-types.isListLike(obj) is deprecated, please use `canReflect.isObservableLike(obj) && canReflect.isListLike(obj)` instead."),a.isObservableLike(e)&&a.isListLike(e)},isPromise:function(e){return o.warn("can-types.isPromise is deprecated, please use canReflect.isPromise instead."),a.isPromise(e)},isConstructor:function(e){return o.warn("can-types.isConstructor is deprecated, please use canReflect.isConstructorLike instead."),a.isConstructorLike(e)},isCallableForValue:function(e){return o.warn("can-types.isCallableForValue(obj) is deprecated, please use `canReflect.isFunctionLike(obj) && !canReflect.isConstructorLike(obj)` instead."),e&&a.isFunctionLike(e)&&!a.isConstructorLike(e)},isCompute:function(e){return o.warn("can-types.isCompute is deprecated."),e&&e.isComputed},get iterator(){return o.warn('can-types.iterator is deprecated, use `canSymbol.iterator || canSymbol.for("iterator")` instead.'),r.iterator||r.for("iterator")},DefaultMap:null,DefaultList:null,queueTask:function(e){var t=e[2]||[];e[0].apply(e[1],t)},wrapElement:function(e){return e},unwrapElement:function(e){return e}};if(i.types)throw new Error("You can't have two versions of can-types, check your dependencies");n.exports=i.types=s}),define("can-util/js/diff/diff",function(e,t,n){"use strict";function i(e,t,n,i,r){for(var o=n.length-1,s=i.length-1;o>e&&s>t;){if(!r(n[o],i[s]))return[{index:t,deleteCount:o-e+1,insert:a.call(i,t,s+1)}];o--,s--}return[{index:t,deleteCount:o-e+1,insert:a.call(i,t,s+1)}]}var a=[].slice,r=function(e,t){return e===t};n.exports=function(e,t,n){n=n||r;for(var o=0,s=0,c=e.length,l=t.length,u=[];o<c&&s<l;){var d=e[o],p=t[s];if(n(d,p))o++,s++;else if(s+1<l&&n(d,t[s+1]))u.push({index:s,deleteCount:0,insert:[t[s]]}),o++,s+=2;else{if(!(o+1<c&&n(e[o+1],p)))return u.push.apply(u,i(o,s,e,t,n)),u;u.push({index:s,deleteCount:1,insert:[]}),o+=2,s++}}return s===l&&o===c?u:(u.push({index:s,deleteCount:c-o,insert:a.call(t,s)}),u)}}),define("can-util/dom/events/attributes/attributes",["require","exports","module","can-util/dom/events/events","can-util/dom/is-of-global-document/is-of-global-document","can-util/dom/data/data","can-globals/mutation-observer/mutation-observer","can-assign","can-util/dom/dispatch/dispatch"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-util/dom/events/events"),r=t("can-util/dom/is-of-global-document/is-of-global-document"),o=t("can-util/dom/data/data"),s=t("can-globals/mutation-observer/mutation-observer"),c=t("can-assign"),l=t("can-util/dom/dispatch/dispatch"),u=a.addEventListener,d=a.removeEventListener;a.addEventListener=function(e){if("attributes"===e){var t=s();if(r(this)&&t){if(!o.get.call(this,"canAttributesObserver")){var n=this,i=new t(function(e){e.forEach(function(e){var t=c({},e);l.call(n,t,[],!1)})});i.observe(this,{attributes:!0,attributeOldValue:!0}),o.set.call(this,"canAttributesObserver",i)}}else o.set.call(this,"canHasAttributesBindings",!0)}return u.apply(this,arguments)},a.removeEventListener=function(e){if("attributes"===e){var t,n=s();r(this)&&n?(t=o.get.call(this,"canAttributesObserver"))&&t.disconnect&&(t.disconnect(),o.clean.call(this,"canAttributesObserver")):o.clean.call(this,"canHasAttributesBindings")}return d.apply(this,arguments)}}(0,e)}),define("can-util/dom/events/inserted/inserted",["require","exports","module","can-util/dom/events/make-mutation-event/make-mutation-event"],function(e,t,n){"use strict";e("can-util/dom/events/make-mutation-event/make-mutation-event")("inserted","addedNodes")}),define("can-util/dom/attr/attr",["require","exports","module","can-util/js/set-immediate/set-immediate","can-globals/document/document","can-globals/global/global","can-util/dom/is-of-global-document/is-of-global-document","can-util/dom/data/data","can-util/dom/contains/contains","can-util/dom/events/events","can-util/dom/dispatch/dispatch","can-globals/mutation-observer/mutation-observer","can-util/js/each/each","can-types","can-util/js/diff/diff","can-util/dom/events/attributes/attributes","can-util/dom/events/inserted/inserted"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-util/js/set-immediate/set-immediate"),r=t("can-globals/document/document"),e=t("can-globals/global/global")(),o=t("can-util/dom/is-of-global-document/is-of-global-document"),s=t("can-util/dom/data/data"),c=t("can-util/dom/contains/contains"),l=t("can-util/dom/events/events"),u=t("can-util/dom/dispatch/dispatch"),d=t("can-globals/mutation-observer/mutation-observer"),p=t("can-util/js/each/each"),f=t("can-types"),h=t("can-util/js/diff/diff");t("can-util/dom/events/attributes/attributes"),t("can-util/dom/events/inserted/inserted");var v={xlink:"http://www.w3.org/1999/xlink"},m={INPUT:!0,TEXTAREA:!0,SELECT:!0},g=function(e){return null==e?"":""+e},y=function(e){return"http://www.w3.org/2000/svg"===e.namespaceURI},b=function(){return!0},w=function(e){return e&&e.test||b},k=function(e,t){return t=t||{},t.get=function(){return this[e]},t.set=function(t){return this[e]!==t&&(this[e]=t),t},t},x=function(e){return{isBoolean:!0,set:function(t){e in this?this[e]=!1!==t:this.setAttribute(e,"")},remove:function(){this[e]=!1}}},j=function(e,t){if(!s.get.call(e,"attrMO")){var n=function(){t.call(e)},i=d();if(i){var a=new i(n);a.observe(e,{childList:!0,subtree:!0}),s.set.call(e,"attrMO",a)}else s.set.call(e,"attrMO",!0),s.set.call(e,"canBindingCallback",{onMutation:n})}},L=function(e,t){for(var n=e.firstChild;n;){if("OPTION"===n.nodeName&&t===n.value)return n;if("OPTGROUP"===n.nodeName){var i=L(n,t);if(i)return i}n=n.nextSibling}},E=function(e,t){var n;null!=t&&(n=L(e,t)),n?n.selected=!0:e.selectedIndex=-1},V=function(e,t){for(var n=e.firstChild;n;)"OPTION"===n.nodeName&&t(n),"OPTGROUP"===n.nodeName&&V(n,t),n=n.nextSibling},O=function(e){var t=[];return V(e,function(e){e.selected&&t.push(e.value)}),t},C=function(e,t){V(e,function(e){e.selected=-1!==t.indexOf(e.value)})},_=function(e,t){var n=s.get.call(e,"attrSetChildOptions");return n?Function.prototype:(n=function(){E(e,e.value)},s.set.call(e,"attrSetChildOptions",n),t.call(e,"change",n),function(t){s.clean.call(e,"attrSetChildOptions"),t.call(e,"change",n)})},D={special:{checked:{get:function(){return this.checked},set:function(e){var t=!!e||""===e||0===arguments.length;return this.checked=t,t&&"radio"===this.type&&(this.defaultChecked=!0),e},remove:function(){this.checked=!1},test:function(){return"INPUT"===this.nodeName}},class:{get:function(){return y(this)?this.getAttribute("class"):this.className},set:function(e){return e=e||"",y(this)?this.setAttribute("class",""+e):this.className=e,e}},disabled:x("disabled"),focused:{get:function(){return this===document.activeElement},set:function(e){function t(){e?a.focus():a.blur()}var n=D.get(this,"focused"),i=this.ownerDocument.documentElement,a=this;if(n!==e)if(c.call(i,a))f.queueTask([t,this,[]]);else{var r=function(){l.removeEventListener.call(a,"inserted",r),t()};l.addEventListener.call(a,"inserted",r)}return!!e},addEventListener:function(e,t,n){return n.call(this,"focus",t),n.call(this,"blur",t),function(e){e.call(this,"focus",t),e.call(this,"blur",t)}},test:function(){return"INPUT"===this.nodeName}},for:k("htmlFor"),innertext:k("innerText"),innerhtml:k("innerHTML"),innerHTML:k("innerHTML",{addEventListener:function(e,t,n){var i=[],a=this;return p(["change","blur"],function(e){var n=function(){t.apply(this,arguments)};l.addEventListener.call(a,e,n),i.push([e,n])}),function(e){p(i,function(t){e.call(a,t[0],t[1])})}}}),required:x("required"),readonly:x("readOnly"),selected:{get:function(){return this.selected},set:function(e){return e=!!e,s.set.call(this,"lastSetValue",e),this.selected=e},addEventListener:function(e,t,n){var i=this,a=this.parentNode,r=i.selected,o=function(t){var n=i.selected;n!==(r=s.get.call(i,"lastSetValue")||r)&&(r=n,u.call(i,e))},c=_(a,n);return l.addEventListener.call(a,"change",o),n.call(i,e,t),function(n){c(n),l.removeEventListener.call(a,"change",o),n.call(i,e,t)}},test:function(){return"OPTION"===this.nodeName&&this.parentNode&&"SELECT"===this.parentNode.nodeName}},src:{set:function(e){return null==e||""===e?(this.removeAttribute("src"),null):(this.setAttribute("src",e),e)}},style:{set:function(){var t=e.document&&r().createElement("div");return t&&t.style&&"cssText"in t.style?function(e){return this.style.cssText=e||""}:function(e){return this.setAttribute("style",e)}}()},textcontent:k("textContent"),value:{get:function(){var e=this.value;return"SELECT"===this.nodeName&&"selectedIndex"in this&&-1===this.selectedIndex&&(e=void 0),e},set:function(e){var t=this.nodeName.toLowerCase();if("input"===t&&(e=g(e)),this.value===e&&"option"!==t||(this.value=e),D.defaultValue[t]&&(this.defaultValue=e),"select"===t){s.set.call(this,"attrValueLastVal",e),E(this,null===e?e:this.value);var n=this.ownerDocument.documentElement;if(!c.call(n,this)){var i=this,a=function(){l.removeEventListener.call(i,"inserted",a),E(i,null===e?e:i.value)};l.addEventListener.call(this,"inserted",a)}j(this,function(){var e=s.get.call(this,"attrValueLastVal");D.set(this,"value",e),u.call(this,"change")})}return e},test:function(){return m[this.nodeName]}},values:{get:function(){return O(this)},set:function(e){return e=e||[],C(this,e),s.set.call(this,"stickyValues",D.get(this,"values")),j(this,function(){var e=s.get.call(this,"stickyValues");D.set(this,"values",e);var t=s.get.call(this,"stickyValues");h(e.slice().sort(),t.slice().sort()).length&&u.call(this,"values")}),e},addEventListener:function(e,t,n){var i=function(){u.call(this,"values")};return l.addEventListener.call(this,"change",i),n.call(this,e,t),function(n){l.removeEventListener.call(this,"change",i),n.call(this,e,t)}}}},defaultValue:{input:!0,textarea:!0},setAttrOrProp:function(e,t,n){t=t.toLowerCase();var i=D.special[t];i&&i.isBoolean&&!n?this.remove(e,t):this.set(e,t,n)},set:function(e,t,n){var i=o(e)&&d();t=t.toLowerCase();var a;i||(a=D.get(e,t));var r,s=D.special[t],c=s&&s.set,l=w(s);"function"==typeof c&&l.call(e)?r=2===arguments.length?c.call(e):c.call(e,n):D.setAttribute(e,t,n),i||r===a||D.trigger(e,t,a)},setSelectValue:function(e,t){D.set(e,"value",t)},setAttribute:function(){var e=r();if(e&&document.createAttribute)try{e.createAttribute("{}")}catch(e){var t={},n=document.createElement("div");return function(e,i,a){var r,o,s,c=i.charAt(0);"{"!==c&&"("!==c&&"*"!==c||!e.setAttributeNode?1!==(s=i.split(":")).length&&v[s[0]]?e.setAttributeNS(v[s[0]],i,a):e.setAttribute(i,a):((r=t[i])||(n.innerHTML="<div "+i+'=""></div>',r=t[i]=n.childNodes[0].attributes[0]),(o=r.cloneNode()).value=a,e.setAttributeNode(o))}}return function(e,t,n){e.setAttribute(t,n)}}(),trigger:function(e,t,n){if(s.get.call(e,"canHasAttributesBindings"))return t=t.toLowerCase(),a(function(){u.call(e,{type:"attributes",attributeName:t,target:e,oldValue:n,bubbles:!1},[])})},get:function(e,t){t=t.toLowerCase();var n=D.special[t],i=n&&n.get,a=w(n);return"function"==typeof i&&a.call(e)?i.call(e):e.getAttribute(t)},remove:function(e,t){t=t.toLowerCase();var n;d()||(n=D.get(e,t));var i=D.special[t],a=i&&i.set,r=i&&i.remove,o=w(i);"function"==typeof r&&o.call(e)?r.call(e):"function"==typeof a&&o.call(e)?a.call(e,void 0):e.removeAttribute(t),d()||null==n||D.trigger(e,t,n)},has:function(){var e=r()&&document.createElement("div");return e&&e.hasAttribute?function(e,t){return e.hasAttribute(t)}:function(e,t){return null!==e.getAttribute(t)}}()},S=l.addEventListener;l.addEventListener=function(e,t){var n=D.special[e];if(n&&n.addEventListener){var i=n.addEventListener.call(this,e,t,S),a=s.get.call(this,"attrTeardowns");return a||s.set.call(this,"attrTeardowns",a={}),a[e]||(a[e]=[]),void a[e].push({teardown:i,handler:t})}return S.apply(this,arguments)};var T=l.removeEventListener;l.removeEventListener=function(e,t){var n=D.special[e];{if(!n||!n.addEventListener)return T.apply(this,arguments);var i=s.get.call(this,"attrTeardowns");if(i&&i[e]){for(var a=i[e],r=0,o=a.length;r<o;r++)if(a[r].handler===t){a[r].teardown.call(this,T),a.splice(r,1);break}0===a.length&&delete i[e]}}},i.exports=D}(function(){return this}(),e,0,n)}),define("can-view-live/lib/attr",["require","exports","module","can-util/dom/attr/attr","can-view-live/lib/core","can-reflect"],function(e,t,n){var i=e("can-util/dom/attr/attr"),a=e("can-view-live/lib/core"),r=e("can-reflect");a.attr=function(e,t,n){function o(n){i.set(e,t,n)}Object.defineProperty(o,"name",{value:"live.attr update::"+r.getName(n)}),a.listen(e,n,o),o(r.getValue(n))}}),define("can-util/js/global/global",["require","exports","module","can-globals/global/global"],function(e,t,n){!function(e,t,n,i){"use strict";i.exports=t("can-globals/global/global")}(0,e,0,n)}),define("can-view-callbacks",["require","exports","module","can-observation-recorder","can-util/js/dev/dev","can-util/js/global/global","can-util/dom/mutate/mutate","can-namespace"],function(e,t,n){!function(e,t,n,i){var a=t("can-observation-recorder"),r=t("can-util/js/dev/dev"),o=t("can-util/js/global/global"),s=t("can-util/dom/mutate/mutate"),c=t("can-namespace"),l={},u={},d=[],p=/[-\:]/,f=function(){},h={},v={_tags:h,_attributes:u,_regExpAttributes:d,defaultCallback:f,tag:function(e,t){if(!t){var n;return null===t?delete h[e.toLowerCase()]:n=h[e.toLowerCase()],!n&&p.test(e)&&(n=f),n}void 0!==h[e.toLowerCase()]&&r.warn("Custom tag: "+e.toLowerCase()+" is already defined"),p.test(e)||"content"===e||r.warn("Custom tag: "+e.toLowerCase()+" hyphen missed"),o().html5&&(o().html5.elements+=" "+e,o().html5.shivDocument()),h[e.toLowerCase()]=t},attr:function(e,t){if(!t){var n=u[e];if(!n)for(var i=0,a=d.length;i<a;i++){var o=d[i];if(o.match.test(e))return o.handler}return l[e]=!0,n}"string"==typeof e?(u[e]=t,l[e]&&r.warn("can-view-callbacks: "+e+" custom attribute behavior requested before it was defined. Make sure "+e+" is defined before it is needed.")):(d.push({match:e,handler:t}),Object.keys(l).forEach(function(t){e.test(t)&&r.warn("can-view-callbacks: "+t+" custom attribute behavior requested before it was defined. Make sure "+e+" is defined before it is needed.")}))},tagHandler:function(e,t,n){var i,o=n.options.get("tags."+t,{proxyMethods:!1})||h[t],c=n.scope;if(i=o?a.ignore(o)(e,n):c,o||r.warn("can-view-callbacks: No custom element found for "+t),i&&n.subtemplate){c!==i&&(c=c.add(i));var l=n.subtemplate(c,n.options),u="string"==typeof l?can.view.frag(l):l;s.appendChild.call(e,u)}}};if(c.view=c.view||{},c.view.callbacks)throw new Error("You can't have two versions of can-view-callbacks, check your dependencies");i.exports=c.view.callbacks=v}(0,e,0,n)}),define("can-view-live/lib/attrs",["require","exports","module","can-view-live/lib/core","can-view-callbacks","can-util/dom/attr/attr","can-util/dom/events/events","can-reflect"],function(e,t,n){var i=e("can-view-live/lib/core"),a=e("can-view-callbacks"),r=e("can-util/dom/attr/attr"),o=e("can-util/dom/events/events"),s=e("can-reflect");i.attrs=function(e,t,n,c){function l(t){var o,s=i.getAttributeParts(t);for(o in s){var l=s[o];if(l!==u[o]){r.set(e,o,l);var d=a.attr(o);d&&d(e,{attributeName:o,scope:n,options:c})}delete u[o]}for(o in u)r.remove(e,o);u=s}if(s.isObservableLike(t)){var u={};Object.defineProperty(l,"name",{value:"live.attrs update::"+s.getName(t)}),i.addElementDependency(e,t),s.onValue(t,l);var d=function(){s.offValue(t,l),o.removeEventListener.call(e,"removed",d),i.deleteElementDependency(e,t)};o.addEventListener.call(e,"removed",d),l(s.getValue(t))}else{var p=i.getAttributeParts(t);for(var f in p)r.set(e,f,p[f])}}}),define("can-view-live/lib/html",["require","exports","module","can-view-live/lib/core","can-view-nodelist","can-util/dom/frag/frag","can-util/js/make-array/make-array","can-util/dom/child-nodes/child-nodes","can-reflect"],function(e,t,n){var i=e("can-view-live/lib/core"),a=e("can-view-nodelist"),r=e("can-util/dom/frag/frag"),o=e("can-util/js/make-array/make-array"),s=e("can-util/dom/child-nodes/child-nodes"),c=e("can-reflect");i.html=function(e,t,n,l){function u(e){a.first(f).parentNode&&p(e);var t=a.first(f).parentNode;d.teardownCheck(t)}var d,p,f;n=i.getParentNode(e,n),Object.defineProperty(u,"name",{value:"live.html update::"+c.getName(t)}),d=i.listen(n,t,u),f=l||[e],p=function(e){var t="function"==typeof e,n=r(t?"":e),c=o(f);i.addTextNodeIfNoChildren(n),c=a.update(f,s(n)),t&&e(n.firstChild),a.replace(c,n)},d.nodeList=f,l?l.unregistered=d.teardownCheck:a.register(f,d.teardownCheck),p(c.getValue(t))}}),define("can-view-live/lib/set-observable",["require","exports","module","can-simple-observable","can-reflect"],function(e,t,n){function i(e,t){this.setter=t,a.call(this,e)}var a=e("can-simple-observable"),r=e("can-reflect");(i.prototype=Object.create(a.prototype)).constructor=i,i.prototype.set=function(e){this.setter(e)},r.assignSymbols(i.prototype,{"can.setValue":i.prototype.set}),n.exports=i}),define("can-view-live/lib/patcher",["require","exports","module","can-reflect","can-key-tree","can-symbol","can-util/js/diff/diff","can-queues","can-symbol"],function(e,t,n){var i=e("can-reflect"),a=e("can-key-tree"),r=e("can-symbol"),o=e("can-util/js/diff/diff"),s=e("can-queues"),c=(r=e("can-symbol")).for("can.onValue"),l=r.for("can.offValue"),u=r.for("can.onPatches"),d=r.for("can.offPatches"),p=function(e,t){this.handlers=new a([Object,Array],{onFirst:this.setup.bind(this),onEmpty:this.teardown.bind(this)}),this.observableOrList=e,this.isObservableValue=i.isValueLike(this.observableOrList)||i.isObservableLike(this.observableOrList),this.isObservableValue?this.priority=i.getPriority(e):this.priority=t||0,this.onList=this.onList.bind(this),this.onPatchesNotify=this.onPatchesNotify.bind(this),this.onPatchesDerive=this.onPatchesDerive.bind(this),this.patches=[],Object.defineProperty(this.onList,"name",{value:"live.list new list::"+i.getName(e)}),Object.defineProperty(this.onPatchesNotify,"name",{value:"live.list notify::"+i.getName(e)}),Object.defineProperty(this.onPatchesDerive,"name",{value:"live.list derive::"+i.getName(e)})};p.prototype={constructor:p,setup:function(){this.observableOrList[c]?(i.onValue(this.observableOrList,this.onList,"notify"),this.setupList(i.getValue(this.observableOrList))):this.setupList(this.observableOrList||[])},teardown:function(){this.observableOrList[l]&&i.offValue(this.observableOrList,this.onList,"notify")},setupList:function(e){this.currentList=e,e[u]&&e[u](this.onPatchesNotify,"notify")},onList:function(e){var t=this.currentList||[];e=e||[],t[d]&&t[d](this.onPatchesNotify,"notify");var n=o(t,e);this.currentList=e,this.onPatchesNotify(n),e[u]&&e[u](this.onPatchesNotify,"notify")},onPatchesNotify:function(e){this.patches.push.apply(this.patches,e),s.deriveQueue.enqueue(this.onPatchesDerive,this,[],{priority:this.priority})},onPatchesDerive:function(){var e=this.patches;this.patches=[],s.enqueueByQueue(this.handlers.getNode([]),this.currentList,[e,this.currentList],null,["Apply patches",e])}},i.assignSymbols(p.prototype,{"can.onPatches":function(e,t){this.handlers.add([t||"mutate",e])},"can.offPatches":function(e,t){this.handlers.delete([t||"mutate",e])}}),n.exports=p}),define("can-view-live/lib/list",["require","exports","module","can-view-live/lib/core","can-view-nodelist","can-util/dom/frag/frag","can-util/dom/mutate/mutate","can-util/dom/child-nodes/child-nodes","can-util/js/make-array/make-array","can-util/js/each/each","can-reflect","can-symbol","can-simple-observable","can-view-live/lib/set-observable","can-view-live/lib/patcher"],function(e,t,n){function i(e,t,n,i,o,s,c){this.patcher=new v(t),o=a.getParentNode(e,o),this.value=t,this.render=n,this.context=i,this.parentNode=o,this.falseyRender=c,this.masterNodeList=s||r.register([e],null,!0),this.placeholder=e,this.indexMap=[],this.isValueLike=d.isValueLike(this.value),this.isObservableLike=d.isObservableLike(this.value),this.onPatches=this.onPatches.bind(this);var l=this.data=a.setup(o,this.setupValueBinding.bind(this),this.teardownValueBinding.bind(this));this.masterNodeList.unregistered=function(){l.teardownCheck()},Object.defineProperty(this.onPatches,"name",{value:"live.list update::"+d.getName(t)})}var a=e("can-view-live/lib/core"),r=e("can-view-nodelist"),o=e("can-util/dom/frag/frag"),s=e("can-util/dom/mutate/mutate"),c=e("can-util/dom/child-nodes/child-nodes"),l=e("can-util/js/make-array/make-array"),u=e("can-util/js/each/each"),d=e("can-reflect"),p=e("can-symbol"),f=e("can-simple-observable"),h=e("can-view-live/lib/set-observable"),v=e("can-view-live/lib/patcher"),m=[].splice,g=function(e,t,n,i,a){var s=[];t&&(r.register(s,null,t,!0),s.parentList=t,s.expression="#each SUBEXPRESSION");var u=n.apply(i,a.concat([s])),d=o(u),p=l(c(d));return t?(r.update(s,p),e.push(s)):e.push(r.register(p)),d},y=function(e,t,n){var i=e.splice(t+1,n),a=[];return u(i,function(e){var t=r.unregister(e);[].push.apply(a,t)}),a},b=p.for("can.onPatches"),w=p.for("can.offPatches"),b=p.for("can.onPatches"),w=p.for("can.offPatches");i.prototype={setupValueBinding:function(){this.patcher[b](this.onPatches,"domUI"),this.patcher.currentList&&this.patcher.currentList.length?this.onPatches([{insert:this.patcher.currentList,index:0,deleteCount:0}]):this.addFalseyIfEmpty(),a.addElementDependency(this.parentNode,this.patcher.observableOrList)},teardownValueBinding:function(){this.patcher[w](this.onPatches,"domUI"),this.exit=!0,this.remove({length:this.patcher.currentList.length},0,!0),a.deleteElementDependency(this.parentNode,this.patcher.observableOrList)},onPatches:function(e){if(!this.exit)for(var t=0,n=e.length;t<n;t++){var i=e[t];"move"===i.type?this.move(i.toIndex,i.fromIndex):(i.deleteCount&&this.remove({length:i.deleteCount},i.index,!0),i.insert&&i.insert.length&&this.add(i.insert,i.index))}},add:function(e,t){var n=this.placeholder.ownerDocument.createDocumentFragment(),i=[],a=[],o=this.masterNodeList,c=this.render,l=this.context;u(e,function(e,r){var s=new f(r+t),u=new h(e,function(e){d.setKeyValue(this.patcher.currentList,s.get(),e)}.bind(this)),p=g(i,o,c,l,[u,s]);n.appendChild(p),a.push(s)},this);var p=t+1;if(!this.indexMap.length){var v=y(o,0,o.length-1);r.remove(v)}if(o[p]){var b=r.first(o[p]);s.insertBefore.call(b.parentNode,n,b)}else r.after(1===p?[this.placeholder]:[r.last(this.masterNodeList[p-1])],n);m.apply(this.masterNodeList,[p,0].concat(i)),m.apply(this.indexMap,[t,0].concat(a));for(var w=t+a.length,k=this.indexMap.length;w<k;w++)this.indexMap[w].set(w)},remove:function(e,t){t<0&&(t=this.indexMap.length+t);var n=y(this.masterNodeList,t,e.length),i=this.indexMap;i.splice(t,e.length);for(var a=t,o=i.length;a<o;a++)i[a].set(a);this.exit?r.unregister(this.masterNodeList):(this.addFalseyIfEmpty(),r.remove(n))},addFalseyIfEmpty:function(){if(this.falseyRender&&0===this.indexMap.length){var e=[],t=g(e,this.masterNodeList,this.falseyRender,this.currentList,[this.currentList]);r.after([this.masterNodeList[0]],t),this.masterNodeList.push(e[0])}},move:function(e,t){e+=1,t+=1;var n,i=this.masterNodeList,a=this.indexMap,s=i[e],c=o(r.flatten(i[t]));n=t<e?r.last(s).nextSibling:r.first(s),i[0].parentNode.insertBefore(c,n);var l=i[t];[].splice.apply(i,[t,1]),[].splice.apply(i,[e,0,l]),e-=1;var u=a[t-=1];[].splice.apply(a,[t,1]),[].splice.apply(a,[e,0,u]);var d=Math.min(t,e),p=a.length;for(p;d<p;d++)a[d].set(d)},set:function(e,t){this.remove({length:1},t,!0),this.add([e],t)}},a.list=function(e,t,n,a,o,s,c){if(e.nodeType!==Node.TEXT_NODE){var l;s?(l=document.createTextNode(""),r.replace(s,l),r.update(s,[l]),e=l):(l=document.createTextNode(""),e.replaceWith(l),e=l)}new i(e,t,n,a,o,s,c)}}),define("can-view-live/lib/text",["require","exports","module","can-view-live/lib/core","can-view-nodelist","can-reflect"],function(e,t,n){var i=e("can-view-live/lib/core"),a=e("can-view-nodelist"),r=e("can-reflect");i.text=function(e,t,n,o){function s(t){e.nodeValue=i.makeString(t)}if(e.nodeType!==Node.TEXT_NODE){var c;o?(c=document.createTextNode(""),a.replace(o,c),a.update(o,[c]),e=c):(c=document.createTextNode(""),e.replaceWith(c),e=c)}var l=i.getParentNode(e,n);e.nodeValue=i.makeString(r.getValue(t)),Object.defineProperty(s,"name",{value:"live.text update::"+r.getName(t)});var u=i.listen(l,t,s);o||(o=a.register([e],null,!0)),o.unregistered=u.teardownCheck,u.nodeList=o}}),define("can-view-live",["require","exports","module","can-view-live/lib/core","can-view-live/lib/attr","can-view-live/lib/attrs","can-view-live/lib/html","can-view-live/lib/list","can-view-live/lib/text"],function(e,t,n){var i=e("can-view-live/lib/core");e("can-view-live/lib/attr"),e("can-view-live/lib/attrs"),e("can-view-live/lib/html"),e("can-view-live/lib/list"),e("can-view-live/lib/text"),n.exports=i}),define("can-util/js/base-url/base-url",["require","exports","module","can-globals/global/global","can-globals/document/document"],function(e,t,n){!function(e,t,n,i){"use strict";var a,r=t("can-globals/global/global"),o=t("can-globals/document/document");i.exports=function(e){if(void 0!==e&&(a=e),void 0!==a)return a;var t=r(),n=o();if(n&&"baseURI"in n)return n.baseURI;if(t.location){var i=t.location.href,s=i.lastIndexOf("/");return-1!==s?i.substr(0,s):i}return"undefined"!=typeof process?process.cwd():void 0}}(0,e,0,n)}),define("can-parse-uri",function(e,t,n){n.exports=function(e){var t=String(e).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return t?{href:t[0]||"",protocol:t[1]||"",authority:t[2]||"",host:t[3]||"",hostname:t[4]||"",port:t[5]||"",pathname:t[6]||"",search:t[7]||"",hash:t[8]||""}:null}}),define("can-util/js/join-uris/join-uris",["require","exports","module","can-parse-uri"],function(e,t,n){"use strict";var i=e("can-parse-uri");n.exports=function(e,t){return t=i(t||""),e=i(e||""),t&&e?(t.protocol||e.protocol)+(t.protocol||t.authority?t.authority:e.authority)+function(e){var t=[];return e.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(e){"/.."===e?t.pop():t.push(e)}),t.join("").replace(/^\//,"/"===e.charAt(0)?"/":"")}(t.protocol||t.authority||"/"===t.pathname.charAt(0)?t.pathname:t.pathname?(e.authority&&!e.pathname?"/":"")+e.pathname.slice(0,e.pathname.lastIndexOf("/")+1)+t.pathname:e.pathname)+(t.protocol||t.authority||t.pathname?t.search:t.search||e.search)+t.hash:null}}),define("can-stache/helpers/-debugger",["require","exports","module","can-util/js/log/log","can-reflect","can-symbol"],function(e,t,n){function i(){}var a=e("can-util/js/log/log"),r=i,o=i,s={},c=e("can-reflect"),l=e("can-symbol");s={allowDebugger:!0},r=function(e){return e&&e[l.for("can.getValue")]?c.getValue(e):e},o=function(e,t){switch(arguments.length){case 0:return!0;case 1:return!!r(e);case 2:return r(e)===r(t);default:throw a.log(["Usage:"," {{debugger}}: break any time this helper is evaluated"," {{debugger condition}}: break when `condition` is truthy"," {{debugger left right}}: break when `left` === `right`"].join("\n")),new Error("{{debugger}} must have less than three arguments")}},n.exports={helper:function(e,t){o.apply(null,Array.prototype.slice.call(arguments,0,-1))&&(arguments[arguments.length-1],a.log("Use `get(<path>)` to debug this template"),s.allowDebugger||a.warn("Forgotten {{debugger}} helper"))},evaluateArgs:o,resolveValue:r,__testing:s}}),define("can-stache/src/truthy-observable",["require","exports","module","can-observation","can-reflect"],function(e,t,n){var i=e("can-observation"),a=e("can-reflect");n.exports=function(e){return new i(function(){return!!a.getValue(e)})}}),define("can-stache/helpers/core",["require","exports","module","can-view-live","can-view-nodelist","can-stache/src/utils","can-util/js/is-function/is-function","can-util/js/base-url/base-url","can-util/js/join-uris/join-uris","can-util/js/each/each","can-util/js/assign/assign","can-util/js/is-iterable/is-iterable","can-util/js/dev/dev","can-symbol","can-reflect","can-util/js/is-empty-object/is-empty-object","can-stache/helpers/-debugger","can-stache/src/key-observable","can-observation","can-stache/src/truthy-observable","can-util/dom/data/data"],function(e,t,n){var i=e("can-view-live"),a=e("can-view-nodelist"),r=e("can-stache/src/utils"),o=e("can-util/js/is-function/is-function"),s=e("can-util/js/base-url/base-url"),c=e("can-util/js/join-uris/join-uris"),l=e("can-util/js/each/each"),u=e("can-util/js/assign/assign"),d=e("can-util/js/is-iterable/is-iterable"),p=e("can-util/js/dev/dev"),f=e("can-symbol"),h=e("can-reflect"),v=e("can-util/js/is-empty-object/is-empty-object"),m=e("can-stache/helpers/-debugger").helper,g=e("can-stache/src/key-observable"),y=e("can-observation"),b=e("can-stache/src/truthy-observable"),w=e("can-util/dom/data/data"),k=function(e){return e&&"function"==typeof e.fn&&"function"==typeof e.inverse},x=f.for("can.getValue"),j=f.for("can.isValueLike"),L=function(e){return e&&e[j]&&e[x]?e[x]():e},E={each:function(e){var t,n,o,s,c=[].slice.call(arguments),u=c.pop(),f=c.length,m=u.exprData.argExprs,y=u.exprData.hashExprs,b=L(e);if((2===f||3===f&&"as"===m[1].key)&&("string"!=typeof(t=c[f-1])&&(t=m[f-1].key),p.warn("can-stache: Using the `as` keyword is deprecated in favor of hash expressions. https://canjs.com/doc/can-stache.helpers.each.html"),p.warn("can-stache: Do not use `{{#"+u.nodeList.expression+"}}`, instead use `{{#"+u.nodeList.expression.split(" ")[0]+" "+u.nodeList.expression.split(" ")[1]+" "+t+"=value}}`")),v(y)||(n={},l(y,function(e,t){n[e.key]=t})),(h.isObservableLike(b)&&h.isListLike(b)||r.isArrayLike(b)&&e.isComputed)&&!u.stringOnly)return function(r){var o=[r];o.expression="live.list",a.register(o,null,u.nodeList,!0),a.update(u.nodeList,[r]);i.list(r,e,function(e,i,a){var r={"%index":i};return t&&(r[t]=e),v(n)||(n.value&&(r[n.value]=e),n.index&&(r[n.index]=i)),u.fn(u.scope.add(r,{notContext:!0}).add(e),u.options,a)},u.context,r.parentNode,o,function(e,t){return u.inverse(u.scope.add(e),u.options,t)})};var w,k=b;if(k&&r.isArrayLike(k))return w=r.getItemsFragContent(k,u,u.scope,t),u.stringOnly?w.join(""):w;if(d(k))return w=[],l(k,function(e,i){o={"%key":i},t&&(o[t]=e),v(n)||(n.value&&(o[n.value]=e),n.key&&(o[n.key]=i)),w.push(u.fn(u.scope.add(o,{notContext:!0}).add(e)))}),u.stringOnly?w.join(""):w;if(h.isObservableLike(k)&&h.isMapLike(k))return w=[],h.each(k,function(e,n){var i=new g(k,n);o={"%key":n},t&&(o[t]=k[n]),w.push(u.fn(u.scope.add(o,{notContext:!0}).add(i)))}),u.stringOnly?w.join(""):w;if(k instanceof Object){w=[];for(s in k)o={"%key":s},t&&(o[t]=k[s]),w.push(u.fn(u.scope.add(o,{notContext:!0}).add(k[s])));return u.stringOnly?w.join(""):w}},"%index":function(e,t){t||(t=e,e=0);var n=t.scope.peek("%index");return""+((o(n)?n():n)+e)},if:function(e,t){return(e&&e.isComputed?h.getValue(new b(e)):!!L(e))?t.fn(t.scope||this):t.inverse(t.scope||this)},is:function(){var e,t,n=arguments[arguments.length-1];if(arguments.length-2<=0)return n.inverse();var i=arguments;return new y(function(){for(var n=0;n<i.length-1;n++){if(t=L(i[n]),t=o(t)?t():t,n>0&&t!==e)return!1;e=t}return!0}).get()?n.fn():n.inverse()},eq:function(){return E.is.apply(this,arguments)},unless:function(e,t){return E.if.apply(this,[e,u(u({},t),{fn:t.inverse,inverse:t.fn})])},with:function(e,t){var n=e;return t?(e=L(e),t.hash&&!v(t.hash)&&(n=t.scope.add(t.hash).add(n))):(t=e,e=!0,n=t.hash),t.fn(n||{})},log:function(e){var t=[];l(arguments,function(e){k(e)||t.push(e)}),"undefined"!=typeof console&&console.log&&(t.length?console.log.apply(console,t):console.log(e.context))},data:function(e){var t=2===arguments.length?this:arguments[1];return function(n){w.set.call(n,e,t||this.context)}},switch:function(e,t){L(e);var n=!1,i=t.helpers.add({case:function(t,i){if(!n&&L(e)===L(t))return n=!0,i.fn(i.scope||this)},default:function(e){if(!n)return e.fn(e.scope||this)}});return t.fn(t.scope,i)},joinBase:function(e){var t=[].slice.call(arguments),n=t.pop(),i=t.map(function(e){var t=L(e);return o(t)?t():t}).join(""),a=n.helpers.peek("helpers.module"),r=a?a.uri:void 0;if("."===i[0]&&r)return c(r,i);var l="undefined"!=typeof System&&(System.renderingBaseURL||System.baseURL)||s();return"/"!==i[0]&&"/"!==l[l.length-1]&&(l+="/"),c(l,i)}};E.eachOf=E.each,E.debugger=m;var V=function(e,t){E[e]&&p.warn("The helper "+e+" has already been registered."),E[e]=t},O=function(e){return function(){var t=[];return l(arguments,function(e){for(;e&&e.isComputed;)e=e();t.push(e)}),e.apply(this,t)}};n.exports={registerHelper:V,registerSimpleHelper:function(e,t){V(e,O(t))},getHelper:function(e,t){var n=t&&t.get&&t.get("helpers."+e,{proxyMethods:!1});if(n||(n=E[e]),n)return{fn:n}},resolve:L,resolveHash:function(e){var t={};for(var n in e)t[n]=L(e[n]);return t},looksLikeOptions:k}}),define("can-util/js/last/last",function(e,t,n){"use strict";n.exports=function(e){return e&&e[e.length-1]}}),define("can-simple-observable/setter/setter",["require","exports","module","can-reflect","can-observation","can-key-tree","can-simple-observable/settable/settable"],function(e,t,n){function i(e,t){this.handlers=new o([Object,Array],{onFirst:this.setup.bind(this),onEmpty:this.teardown.bind(this)}),this.setter=t,this.observation=new r(e),this.handler=this.handler.bind(this),a.assignSymbols(this,{"can.getName":function(){return a.getName(this.constructor)+"<"+a.getName(e)+">"}}),Object.defineProperty(this.handler,"name",{value:a.getName(this)+".handler"})}var a=e("can-reflect"),r=e("can-observation"),o=e("can-key-tree"),s=e("can-simple-observable/settable/settable");(i.prototype=Object.create(s.prototype)).constructor=i,i.prototype.set=function(e){this.setter(e)},i.prototype.hasDependencies=function(){return a.valueHasDependencies(this.observation)},a.assignSymbols(i.prototype,{"can.setValue":i.prototype.set,"can.valueHasDependencies":i.prototype.hasDependencies}),n.exports=i}),define("can-stache/src/expression",["require","exports","module","can-stache-key","can-stache/src/utils","can-stache/helpers/core","can-util/js/each/each","can-util/js/is-empty-object/is-empty-object","can-util/js/dev/dev","can-util/js/assign/assign","can-util/js/last/last","can-reflect","can-symbol","can-observation","can-simple-observable/setter/setter","can-view-scope/make-compute-like"],function(e,t,n){var i=e("can-stache-key"),a=e("can-stache/src/utils"),r=e("can-stache/helpers/core"),o=e("can-util/js/each/each"),s=e("can-util/js/is-empty-object/is-empty-object"),c=e("can-util/js/dev/dev"),l=e("can-util/js/assign/assign"),u=e("can-util/js/last/last"),d=e("can-reflect"),p=e("can-symbol"),f=e("can-observation"),h=e("can-simple-observable/setter/setter"),v=e("can-view-scope/make-compute-like"),m=p.for("can-stache.sourceText"),g=function(e,t,n){var i=t.computeData(e,n);return f.temporarilyBind(i),i},y=function(e){return e[p.for("can.valueHasDependencies")]?d.valueHasDependencies(e):e.computeInstance.hasDependencies},b=function(e,t,n,i){var a=g(e,t,i),o={value:a};if(void 0===a.initialValue){"@"===e.charAt(0)&&(e=e.substr(1));var s=r.getHelper(e,n);o.helper=s&&s.fn}return o},w=function(e,t,n,a){var r=function(){return(""+d.getValue(e)).replace(".","\\.")},o=new h(function(){return i.get(d.getValue(t),r())},function(e){i.write(d.getValue(t),i.reads(r()),e)});return f.temporarilyBind(o),o},k=function(e){return e instanceof C||e instanceof E?e:new C(e)},x=function(e){return d.isObservableLike(e)?!1===d.valueHasDependencies(e)?d.getValue(e):e.compute?e.compute:v(e):e},j=function(e){return e?e.isComputed?e:e.compute?e.compute:v(e):e},L=function(e,t){this.root=t,this.key=e};L.prototype.value=function(e,t){var n=this.root?this.root.value(e,t):e.peek(".");return w(this.key.value(e,t),n,0,0)},L.prototype.sourceText=function(){return this.rootExpr?this.rootExpr.sourceText()+"["+this.key+"]":"["+this.key+"]"};var E=function(e){this._value=e};E.prototype.value=function(){return this._value},E.prototype.sourceText=function(){return JSON.stringify(this._value)};var V=function(e,t,n){this.key=e,this.rootExpr=t,d.setKeyValue(this,m,n)};V.prototype.value=function(e,t){if(this.rootExpr)return w(this.key,this.rootExpr.value(e,t),0,0);var n=b(this.key,e,t);return this.isHelper=n.helper&&!n.helper.callAsMethod,n.helper||n.value},V.prototype.sourceText=function(){return this[m]?this[m]:this.rootExpr?this.rootExpr.sourceText()+"."+this.key:this.key};var O=function(e,t){V.apply(this,arguments)};O.prototype.value=function(e,t){return this.rootExpr?w(this.key,this.rootExpr.value(e,t),0,0):g(this.key,e,t)},O.prototype.sourceText=V.prototype.sourceText;var C=function(e,t){this.expr=e,this.modifiers=t||{},this.isCompute=!1};C.prototype.value=function(){return this.expr.value.apply(this.expr,arguments)},C.prototype.sourceText=function(){return(this.modifiers.compute?"~":"")+this.expr.sourceText()};var _=function(e){this.hashExprs=e};_.prototype.value=function(e,t){var n={};for(var i in this.hashExprs){var a=k(this.hashExprs[i]),r=a.value.apply(a,arguments);n[i]={call:!a.modifiers||!a.modifiers.compute,value:r}}return new f(function(){var e={};for(var t in n)e[t]=n[t].call?d.getValue(n[t].value):x(n[t].value);return e})},_.prototype.sourceText=function(){var e=[];return o(this.hashExprs,function(t,n){e.push(n+"="+t.sourceText())}),e.join(" ")};var D=function(e,t){this.methodExpr=e,this.argExprs=t.map(k)};D.prototype.args=function(e,t){for(var n=[],i=0,a=this.argExprs.length;i<a;i++){var r=this.argExprs[i],o=r.value.apply(r,arguments);n.push({call:!r.modifiers||!r.modifiers.compute,value:o})}return function(){for(var e=[],t=0,i=n.length;t<i;t++)e[t]=n[t].call?d.getValue(n[t].value):j(n[t].value);return e}},D.prototype.value=function(e,t,n){var i=this.methodExpr.value(e,t),a=this.isHelper=this.methodExpr.isHelper,r=this.args(e,t),o=function(e){var t=d.getValue(i);if("function"==typeof t){var o=r();return a&&n&&o.push(n),arguments.length&&o.unshift(new W.SetIdentifier(e)),t.apply(null,o)}};Object.defineProperty(o,"name",{value:"{{"+this.sourceText()+"}}"});var s=new h(o,o);return f.temporarilyBind(s),s},D.prototype.sourceText=function(){var e=this.argExprs.map(function(e){return e.sourceText()});return this.methodExpr.sourceText()+"("+e.join(",")+")"},D.prototype.closingTag=function(){return this.methodExpr[m]?this.methodExpr[m]:this.methodExpr.key};var S=function(){V.apply(this,arguments)};S.prototype.value=function(e,t){var n=b(this.key,e,t,{isArgument:!0,args:[e.peek("."),e]});return n.helper||n.value},S.prototype.sourceText=V.prototype.sourceText;var T=function(){V.apply(this,arguments)};T.prototype.value=function(e,t){return g(this.key,e,{callMethodsOnObservables:!0,isArgument:!0,args:[e.peek("."),e]})},T.prototype.sourceText=V.prototype.sourceText;var N=function(e,t,n){this.methodExpr=e,this.argExprs=t,this.hashExprs=n,this.mode=null};N.prototype.args=function(e,t){for(var n=[],i=0,a=this.argExprs.length;i<a;i++){var r=this.argExprs[i];n.push(x(r.value.apply(r,arguments)))}return n},N.prototype.hash=function(e,t){var n={};for(var i in this.hashExprs){var a=this.hashExprs[i];n[i]=x(a.value.apply(a,arguments))}return n},N.prototype.helperAndValue=function(e,t){function n(){return a.initialValue.apply(null,o)}var i,a,o,l=this.argExprs.length||!s(this.hashExprs),u=this.methodExpr instanceof E?""+this.methodExpr._value:this.methodExpr.key;if(l&&(i=r.getHelper(u,t)),!i){if("function"==typeof(a=g(u,e,{isArgument:!0})).initialValue){o=this.args(e,t).map(x),Object.defineProperty(n,"name",{value:d.getName(this)});var p=new f(n);return f.temporarilyBind(p),{value:p}}if(void 0!==a.initialValue)return{value:a};l||(i=r.getHelper(u,t))}return i||(l?c.warn('can-stache/src/expression.js: Unable to find helper "'+u+'".'):c.warn('can-stache/src/expression.js: Unable to find key or helper "'+u+'".')),{value:a,args:o,helper:i&&i.fn}},N.prototype.evaluator=function(e,t,n,i,r,o,s,c){var u={stringOnly:c},d=t.peek("."),p=this.args(t,n,r,o,s,c),f=this.hash(t,n,r,o,s,c);return a.convertToScopes(u,t,n,r,o,s,c),l(u,{context:d,scope:t,contexts:t,hash:f,nodeList:r,exprData:this,helperOptions:n,helpers:n}),p.push(u),function(){return e.apply(d,p)}},N.prototype.value=function(e,t,n,i,a,r){var o=this.helperAndValue(e,t),s=o.helper;if(!s)return o.value;var c=this.evaluator(s,e,t,n,i,a,r),l=new f(c);return f.temporarilyBind(l),y(l)?l:l()},N.prototype.closingTag=function(){return this.methodExpr.key},N.prototype.sourceText=function(){var e=[this.methodExpr.sourceText()];return this.argExprs.length&&e.push(this.argExprs.map(function(e){return e.sourceText()}).join(" ")),s(this.hashExprs)||e.push(_.prototype.sourceText.call(this)),e.join(" ")},d.assignSymbols(N.prototype,{"can.getName":function(){return d.getName(this.constructor)+"{{"+this.sourceText()+"}}"}});var P=/[\w\.\\\-_@\/\&%]+/,M=/('.*?'|".*?"|=|[\w\.\\\-_@\/*%\$]+|[\(\)]|,|\~|\[|\]\s*|\s*(?=\[))/g,A=/\]\s+/,q=/^('.*?'|".*?"|[0-9]+\.?[0-9]*|true|false|null|undefined)$/,K=function(e){return P.test(e)},R=/^[\.@]\w/,I=function(e){return K(e)&&R.test(e)},H=function(e){return e.children||(e.children=[]),e},B=function(){this.root={children:[],type:"Root"},this.current=this.root,this.stack=[this.root]};l(B.prototype,{top:function(){return u(this.stack)},isRootTop:function(){return this.top()===this.root},popTo:function(e){this.popUntil(e),this.pop()},pop:function(){this.isRootTop()||this.stack.pop()},first:function(e){for(var t=this.stack.length-1;t>0&&-1===e.indexOf(this.stack[t].type);)t--;return this.stack[t]},firstParent:function(e){for(var t=this.stack.length-2;t>0&&-1===e.indexOf(this.stack[t].type);)t--;return this.stack[t]},popUntil:function(e){for(;-1===e.indexOf(this.top().type)&&!this.isRootTop();)this.stack.pop();return this.top()},addTo:function(e,t){var n=this.popUntil(e);H(n).children.push(t)},addToAndPush:function(e,t){this.addTo(e,t),this.stack.push(t)},push:function(e){this.stack.push(e)},topLastChild:function(){return u(this.top().children)},replaceTopLastChild:function(e){var t=H(this.top()).children;return t.pop(),t.push(e),e},replaceTopLastChildAndPush:function(e){this.replaceTopLastChild(e),this.stack.push(e)},replaceTopAndPush:function(e){var t;return this.top()===this.root?t=H(this.top()).children:(this.stack.pop(),t=H(this.top()).children),t.pop(),t.push(e),this.stack.push(e),e}});var F=function(e){var t=e.lastIndexOf("./"),n=e.lastIndexOf(".");if(n>t)return e.substr(0,n)+"@"+e.substr(n+1);var i=-1===t?0:t+2,a=e.charAt(i);return"."===a||"@"===a?e.substr(0,i)+"@"+e.substr(i+1):e.substr(0,i)+"@"+e.substr(i)},z=function(e){return"Lookup"===e.type&&(d.setKeyValue(e,m,e.key),e.key=F(e.key)),e},U=function(e){var t=e.top();if(t&&"Lookup"===t.type){var n=e.stack[e.stack.length-2];"Helper"!==n.type&&n&&e.replaceTopAndPush({type:"Helper",method:t})}},W={toComputeOrValue:x,convertKeyToLookup:F,Literal:E,Lookup:V,ScopeLookup:O,Arg:C,Hash:function(){},Hashes:_,Call:D,Helper:N,HelperLookup:S,HelperScopeLookup:T,Bracket:L,SetIdentifier:function(e){this.value=e},tokenize:function(e){var t=[];return(e.trim()+" ").replace(M,function(e,n){A.test(n)?(t.push(n[0]),t.push(n.slice(1))):t.push(n)}),t},lookupRules:{default:function(e,t,n){var i=("Helper"!==t||e.root?"":"Helper")+(n?"Scope":"")+"Lookup";return W[i]},method:function(e,t,n){return O}},methodRules:{default:function(e){return"Call"===e.type?D:N},call:function(e){return D}},parse:function(e,t){t=t||{};var n=this.ast(e);return t.lookupRule||(t.lookupRule="default"),"string"==typeof t.lookupRule&&(t.lookupRule=W.lookupRules[t.lookupRule]),t.methodRule||(t.methodRule="default"),"string"==typeof t.methodRule&&(t.methodRule=W.methodRules[t.methodRule]),this.hydrateAst(n,t,t.baseMethodType||"Helper")},hydrateAst:function(e,t,n,i){var a;if("Lookup"===e.type)return new(t.lookupRule(e,n,i))(e.key,e.root&&this.hydrateAst(e.root,t,n),e[m]);if("Literal"===e.type)return new E(e.value);if("Arg"===e.type)return new C(this.hydrateAst(e.children[0],t,n,i),{compute:!0});if("Hash"===e.type)throw new Error("");if("Hashes"===e.type)return a={},o(e.children,function(e){a[e.prop]=this.hydrateAst(e.children[0],t,n,!0)},this),new _(a);if("Call"===e.type||"Helper"===e.type){a={};var r=[],s=e.children,c=t.methodRule(e);if(s)for(var l=0;l<s.length;l++){var u=s[l];"Hashes"===u.type&&"Helper"===e.type&&c!==D?o(u.children,function(n){a[n.prop]=this.hydrateAst(n.children[0],t,e.type,!0)},this):r.push(this.hydrateAst(u,t,e.type,!0))}return new c(this.hydrateAst(e.method,t,e.type),r,a)}return"Bracket"===e.type?new L(this.hydrateAst(e.children[0],t),e.root?this.hydrateAst(e.root,t):void 0):void 0},ast:function(e){var t=this.tokenize(e);return this.parseAst(t,{index:0})},parseAst:function(e,t){for(var n,i,r,o=new B;t.index<e.length;){var s=e[t.index],c=e[t.index+1];if(t.index++,"="===c){(n=o.top())&&"Lookup"===n.type&&("Call"!==(i=o.firstParent(["Call","Helper","Hash"])).type&&"Root"!==i.type||(o.popUntil(["Call"]),n=o.top(),o.replaceTopAndPush({type:"Helper",method:"Root"===n.type?u(n.children):n})));var l={type:"Hash",prop:s};"Hashes"===(i=o.firstParent(["Call","Helper","Hashes"])).type?o.addToAndPush(["Hashes"],l):(o.addToAndPush(["Helper","Call"],{type:"Hashes",children:[l]}),o.push(l)),t.index++}else if(q.test(s))U(o),"Hash"===(i=o.first(["Helper","Call","Hash","Bracket"])).type&&i.children&&i.children.length>0?o.addTo(["Helper","Call","Bracket"],{type:"Literal",value:a.jsonParse(s)}):"Bracket"===i.type&&i.children&&i.children.length>0?o.addTo(["Helper","Call","Hash"],{type:"Literal",value:a.jsonParse(s)}):o.addTo(["Helper","Call","Hash","Bracket"],{type:"Literal",value:a.jsonParse(s)});else if(P.test(s))r=o.topLastChild(),i=o.first(["Helper","Call","Hash","Bracket"]),r&&("Call"===r.type||"Bracket"===r.type)&&I(s)?o.replaceTopLastChildAndPush({type:"Lookup",root:r,key:s.slice(1)}):"Bracket"===i.type?i.children&&i.children.length>0?"Helper"===o.first(["Helper","Call","Hash","Arg"]).type&&"."!==s[0]?o.addToAndPush(["Helper"],{type:"Lookup",key:s}):o.replaceTopAndPush({type:"Lookup",key:s.slice(1),root:i}):o.addToAndPush(["Bracket"],{type:"Lookup",key:s}):(U(o),o.addToAndPush(["Helper","Call","Hash","Arg","Bracket"],{type:"Lookup",key:s}));else if("~"===s)U(o),o.addToAndPush(["Helper","Call","Hash"],{type:"Arg",key:s});else if("("===s){if("Lookup"!==(n=o.top()).type)throw new Error("Unable to understand expression "+e.join(""));o.replaceTopAndPush({type:"Call",method:z(n)})}else")"===s?o.popTo(["Call"]):","===s?o.popUntil(["Call"]):"["===s?(n=o.top(),!(r=o.topLastChild())||"Call"!==r.type&&"Bracket"!==r.type?"Lookup"===n.type||"Bracket"===n.type?o.replaceTopAndPush({type:"Bracket",root:n}):"Call"===n.type?o.addToAndPush(["Call"],{type:"Bracket"}):" "===n?(o.popUntil(["Lookup"]),U(o),o.addToAndPush(["Helper","Call","Hash"],{type:"Bracket"})):o.replaceTopAndPush({type:"Bracket"}):o.replaceTopAndPush({type:"Bracket",root:r})):"]"===s?o.pop():" "===s&&o.push(s)}return o.root.children[0]}};n.exports=W}),define("can-util/dom/document/document",["require","exports","module","can-globals/document/document"],function(e,t,n){!function(e,t,n,i){"use strict";i.exports=t("can-globals/document/document")}(0,e,0,n)}),define("can-view-model",["require","exports","module","can-util/dom/data/data","can-simple-map","can-namespace","can-util/dom/document/document","can-util/js/is-array-like/is-array-like","can-reflect"],function(e,t,n){"use strict";var i=e("can-util/dom/data/data"),a=e("can-simple-map"),r=e("can-namespace"),o=e("can-util/dom/document/document"),s=e("can-util/js/is-array-like/is-array-like"),c=e("can-reflect");n.exports=r.viewModel=function(e,t,n){var r;if("string"==typeof e?e=o().querySelector(e):s(e)&&!e.nodeType&&(e=e[0]),c.isObservableLike(t)&&c.isMapLike(t))return i.set.call(e,"viewModel",t);switch((r=i.get.call(e,"viewModel"))||(r=new a,i.set.call(e,"viewModel",r)),arguments.length){case 0:case 1:return r;case 2:return c.getKeyValue(r,t);default:return c.setKeyValue(r,t,n),e}}}),define("can-dom-events/helpers/util",["require","exports","module","can-globals/document/document","can-globals/is-browser-window/is-browser-window"],function(e,t,n){!function(e,t,n,i){"use strict";function a(e){return e.ownerDocument||s()}function r(e){if(!e||!e.nodeName)return e===window;var t=e.nodeType;return t===Node.DOCUMENT_NODE||t===Node.ELEMENT_NODE}function o(e,t){var n=t.type,i="inserted"===n||"removed"===n,a=!!e.disabled;return i&&a}var s=t("can-globals/document/document"),c=t("can-globals/is-browser-window/is-browser-window"),l=!1;!function(){if(c()){var e="fix_synthetic_events_on_disabled_test",t=document.createElement("input");t.disabled=!0;var n=setTimeout(function(){l=!0},50),i=function i(){clearTimeout(n),t.removeEventListener(e,i)};t.addEventListener(e,i);try{var a=document.create("HTMLEvents");a.initEvent(e,!1),t.dispatchEvent(a)}catch(e){i(),l=!0}}}(),i.exports={createEvent:function(e,t,n,i){var r,o=a(e).createEvent("HTMLEvents");if("string"==typeof t)r=t;else{r=t.type;for(var s in t)void 0===o[s]&&(o[s]=t[s])}return void 0===n&&(n=!0),o.initEvent(r,n,i),o},addDomContext:function(e,t){return r(e)&&(t=Array.prototype.slice.call(t,0)).unshift(e),t},removeDomContext:function(e,t){return r(e)||(e=(t=Array.prototype.slice.call(t,0)).shift()),{context:e,args:t}},isDomEventTarget:r,getTargetDocument:a,forceEnabledForDispatch:function(e,t){return l&&o(e,t)}}}(0,e,0,n)}),define("can-dom-events/helpers/add-event-compat",["require","exports","module","can-dom-events/helpers/util"],function(e,t,n){"use strict";function i(e){return!!(e&&e.addEventListener&&e.removeEventListener&&e.dispatch)}function a(e){return"function"==typeof e.addEvent}var r=e("can-dom-events/helpers/util"),o=r.addDomContext,s=r.removeDomContext;n.exports=function(e,t,n){if(!i(e))throw new Error("addEventCompat() must be passed can-dom-events or can-util/dom/events/events");if(n=n||t.defaultEventType,a(e))return e.addEvent(t,n);var r=e._compatRegistry;if(r||(r=e._compatRegistry={}),r[n])return function(){};r[n]=t;var c={addEventListener:function(){var t=s(this,arguments);return e.addEventListener.apply(t.context,t.args)},removeEventListener:function(){var t=s(this,arguments);return e.removeEventListener.apply(t.context,t.args)},dispatch:function(){var t=s(this,arguments),n=t.args[0],i="object"==typeof n?n.args:[];return t.args.splice(1,0,i),e.dispatch.apply(t.context,t.args)}},l=!0,u=e.addEventListener,d=e.addEventListener=function(e){if(l&&e===n){var i=o(this,arguments);t.addEventListener.apply(c,i)}return u.apply(this,arguments)},p=e.removeEventListener,f=e.removeEventListener=function(e){if(l&&e===n){var i=o(this,arguments);t.removeEventListener.apply(c,i)}return p.apply(this,arguments)};return function(){l=!1,r[n]=null,e.addEventListener===d&&(e.addEventListener=u),e.removeEventListener===f&&(e.removeEventListener=p)}}}),define("can-event-dom-enter",["require","exports","module","can-dom-data-state","can-cid"],function(e,t,n){"use strict";function i(e){var t="Enter"===e.key,n=13===e.keyCode;return t||n}function a(e,t){return e+":"+c(t)}function r(e,t,n,i){var r=a(t,n);s.set.call(e,r,i)}function o(e,t,n){var i=a(t,n),r=s.get.call(e,i);return r&&s.clean.call(e,i),r}var s=e("can-dom-data-state"),c=e("can-cid");n.exports={defaultEventType:"enter",addEventListener:function(e,t,n){var a=function(e){if(i(e))return n.apply(this,arguments)};r(e,t,n,a),this.addEventListener(e,"keyup",a)},removeEventListener:function(e,t,n){var i=o(e,t,n);i&&this.removeEventListener(e,"keyup",i)}}}),define("can-event-dom-enter/compat",["require","exports","module","can-dom-events/helpers/add-event-compat","can-event-dom-enter"],function(e,t,n){var i=e("can-dom-events/helpers/add-event-compat"),a=e("can-event-dom-enter");n.exports=function(e,t){return i(e,a,t)}}),define("can-dom-events/helpers/make-event-registry",function(e,t,n){"use strict";function i(){this._registry={}}n.exports=function(){return new i},i.prototype.has=function(e){return!!this._registry[e]},i.prototype.get=function(e){return this._registry[e]},i.prototype.add=function(e,t){if(!e)throw new Error("An EventDefinition must be provided");if("function"!=typeof e.addEventListener)throw new TypeError("EventDefinition addEventListener must be a function");if("function"!=typeof e.removeEventListener)throw new TypeError("EventDefinition removeEventListener must be a function");if("string"!=typeof(t=t||e.defaultEventType))throw new TypeError("Event type must be a string, not "+t);if(this.has(t))throw new Error('Event "'+t+'" is already registered');this._registry[t]=e;var n=this;return function(){n._registry[t]=void 0}}}),define("can-dom-events",["require","exports","module","can-namespace","can-dom-events/helpers/util","can-dom-events/helpers/make-event-registry"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-namespace"),r=t("can-dom-events/helpers/util"),o={_eventRegistry:t("can-dom-events/helpers/make-event-registry")(),addEvent:function(e,t){return this._eventRegistry.add(e,t)},addEventListener:function(e,t){if(o._eventRegistry.has(t))return o._eventRegistry.get(t).addEventListener.apply(o,arguments);var n=Array.prototype.slice.call(arguments,1);return e.addEventListener.apply(e,n)},removeEventListener:function(e,t){if(o._eventRegistry.has(t))return o._eventRegistry.get(t).removeEventListener.apply(o,arguments);var n=Array.prototype.slice.call(arguments,1);return e.removeEventListener.apply(e,n)},dispatch:function(e,t,n,i){var a=r.createEvent(e,t,n,i),o=r.forceEnabledForDispatch(e,a);o&&(e.disabled=!1);var s=e.dispatchEvent(a);return o&&(e.disabled=!0),s}};i.exports=a.domEvents=o}(0,e,0,n)}),define("can-event-dom-radiochange",["require","exports","module","can-dom-data-state","can-globals/document/document","can-dom-events","can-cid/map/map"],function(e,t,n){!function(e,t,n,i){"use strict";function a(e){return e.ownerDocument||g().documentElement}function r(e){return"can-event-radiochange:"+e+":registry"}function o(e){return"can-event-radiochange:"+e+":listener"}function s(e,t){var n=r(t),i=m.get.call(e,n);return i||(i=new b,m.set.call(e,n,i)),i}function c(e){for(;e&&"FORM"!==e.nodeName;)e=e.parentNode;return e}function l(e,t){var n=e.getAttribute("name");return n&&n===t.getAttribute("name")&&c(e)===c(t)}function u(e){return"INPUT"===e.nodeName&&"radio"===e.type}function d(e,t){s(a(t),e).forEach(function(n){l(t,n)&&y.dispatch(n,e)})}function p(e,t,n){var i=o(t);if(!m.get.call(e,i)){var a=function(e){var n=e.target;u(n)&&d(t,n)};n.addEventListener(e,"change",a),m.set.call(e,i,a)}}function f(e,t,n){var i=o(t),a=m.get.call(e,i);a&&(s(e,t).size>0||(n.removeEventListener(e,"change",a),m.clean.call(e,i)))}function h(e,t,n){if(!u(t))throw new Error("Listeners for "+e+" must be radio inputs");var i=a(t);s(i,e).set(t,t),p(i,e,n)}function v(e,t,n){var i=a(t);s(i,e).delete(t),f(i,e,n)}var m=t("can-dom-data-state"),g=t("can-globals/document/document"),y=t("can-dom-events"),b=t("can-cid/map/map");i.exports={defaultEventType:"radiochange",addEventListener:function(e,t,n){h(t,e,this),e.addEventListener(t,n)},removeEventListener:function(e,t,n){v(t,e,this),e.removeEventListener(t,n)}}}(0,e,0,n)}),define("can-event-dom-radiochange/compat",["require","exports","module","can-dom-events/helpers/add-event-compat","can-event-dom-radiochange"],function(e,t,n){var i=e("can-dom-events/helpers/add-event-compat"),a=e("can-event-dom-radiochange");n.exports=function(e,t){return i(e,a,t)}}),define("can-stache-bindings",["require","exports","module","can-stache/src/expression","can-view-callbacks","can-view-scope","can-view-model","can-stache-key","can-observation","can-simple-observable","can-util/js/assign/assign","can-util/js/make-array/make-array","can-util/js/each/each","can-util/js/dev/dev","can-util/dom/events/events","can-util/dom/events/removed/removed","can-util/dom/data/data","can-util/dom/attr/attr","can-stache/helpers/core","can-symbol","can-reflect","can-util/js/single-reference/single-reference","can-attribute-encoder","can-queues","can-simple-observable/setter/setter","can-view-scope/make-compute-like","can-event-dom-enter/compat","can-event-dom-radiochange/compat"],function(e,t,n){function i(e){if(void 0!==e.special.on)return e.tokens[e.special.on+1]}function a(e){var t={tokens:[],special:{}};return e.split(":").forEach(function(e){H[e]?t.special[e]=t.tokens.push(e)-1:t.tokens.push(e)}),t}var r=e("can-stache/src/expression"),o=e("can-view-callbacks"),s=e("can-view-scope"),c=e("can-view-model"),l=e("can-stache-key"),u=e("can-observation"),d=e("can-simple-observable"),p=e("can-util/js/assign/assign"),f=e("can-util/js/make-array/make-array"),h=e("can-util/js/each/each"),v=e("can-util/js/dev/dev"),m=e("can-util/dom/events/events");e("can-util/dom/events/removed/removed");var g=e("can-util/dom/data/data"),y=e("can-util/dom/attr/attr"),b=e("can-stache/helpers/core"),w=e("can-symbol"),k=e("can-reflect"),x=e("can-util/js/single-reference/single-reference"),j=e("can-attribute-encoder"),L=e("can-queues"),E=e("can-simple-observable/setter/setter"),V=e("can-view-scope/make-compute-like");e("can-event-dom-enter/compat")(m),e("can-event-dom-radiochange/compat")(m);var O={on:function(e,t,n){m.canAddEventListener.call(this)?m.addEventListener.call(this,e,t,n):k.onKeyValue(this,e,t,n)},off:function(e,t,n){m.canAddEventListener.call(this)?m.removeEventListener.call(this,e,t,n):k.offKeyValue(this,e,t,n)},one:function(e,t,n){var i=function(){return O.off.call(this,e,i,n),t.apply(this,arguments)};return O.on.call(this,e,i,n),this}},C=function(){},_=w.for("can.getValue"),D=w.for("can.setValue"),S=w.for("can.onValue"),T=w.for("can.offValue"),N=function(){throw new Error("can-stache-bindings - you can not have contextual bindings ( this:from='value' ) and key bindings ( prop:from='value' ) on one element.")},P=function(e,t){var n=t.bindingInfo.parentToChild&&"viewModel"===t.bindingInfo.child;if(!n)return e;var i=t.bindingInfo.childName;if(n&&("this"===i||"."===i)){if(!e.isSettingViewModel&&!e.isSettingOnViewModel)return{isSettingViewModel:!0,initialViewModelData:void 0};N()}else{if(!e.isSettingViewModel)return{isSettingOnViewModel:!0,initialViewModelData:e.initialViewModelData};N()}},M={viewModel:function(e,t,n,i,a){var r,o={},s=[],c={},l={},u=p({},i),d={isSettingOnViewModel:!1,isSettingViewModel:!1,initialViewModelData:i||{}},v=!1;if(h(f(e.attributes),function(n){var i=z(n,e,{templateType:t.templateType,scope:t.scope,semaphore:o,getViewModel:function(){return r},attributeViewModelBindings:u,alreadyUpdatedChild:!0,nodeList:t.parentNodeList,favorViewModel:!0});i&&(d=P(d,i),v=!0,i.onCompleteBinding&&(i.bindingInfo.parentToChild&&void 0!==i.value&&(d.isSettingViewModel?d.initialViewModelData=i.value:d.initialViewModelData[Q(i.bindingInfo.childName)]=i.value),s.push(i.onCompleteBinding)),c[n.name]=i.onTeardown)}),!a||v){r=n(d.initialViewModelData,v);for(var g=0,y=s.length;g<y;g++)s[g]();return d.isSettingViewModel||m.addEventListener.call(e,"attributes",function(n){var i=n.attributeName,a=e.getAttribute(i);c[i]&&c[i]();var o=l[i]&&"attribute"===l[i].parent;if(null!==a||o){var s=z({name:i,value:a},e,{templateType:t.templateType,scope:t.scope,semaphore:{},getViewModel:function(){return r},attributeViewModelBindings:u,initializeValues:!0,nodeList:t.parentNodeList});s&&(s.onCompleteBinding&&s.onCompleteBinding(),l[i]=s.bindingInfo,c[i]=s.onTeardown)}}),function(){for(var e in c)c[e]()}}},data:function(e,t){if(!g.get.call(e,"preventDataBindings")){var n,i,a=u.ignore(function(){return n||(n=c(e))}),r={},o=z({name:t.attributeName,value:e.getAttribute(t.attributeName),nodeList:t.nodeList},e,{templateType:t.templateType,scope:t.scope,semaphore:r,getViewModel:a,syncChildWithParent:!1});"viewModel"!==o.bindingInfo.child||g.get(e,"viewModel")||v.warn("This element does not have a viewModel. (Attempting to bind `"+o.bindingInfo.bindingAttributeName+'="'+o.bindingInfo.parentName+'"`)'),o.onCompleteBinding&&o.onCompleteBinding(),i=o.onTeardown,O.one.call(e,"removed",function(){i()}),m.addEventListener.call(e,"attributes",function(n){var o=n.attributeName,s=e.getAttribute(o);if(o===t.attributeName&&(i&&i(),null!==s)){var c=z({name:o,value:s},e,{templateType:t.templateType,scope:t.scope,semaphore:r,getViewModel:a,initializeValues:!0,nodeList:t.nodeList,syncChildWithParent:!1});c&&(c.onCompleteBinding&&c.onCompleteBinding(),i=c.onTeardown)}})}},event:function(e,t){var n,i,a=j.decode(t.attributeName);if(-1!==a.indexOf(":to:")||-1!==a.indexOf(":from:")||-1!==a.indexOf(":bind:"))return this.data(e,t);if(!K.call(a,"on:"))throw new Error("can-stache-bindings - unsupported event bindings "+a);n=a.substr("on:".length);var o=g.get.call(e,"viewModel"),s=t.scope;if(K.call(n,"el:"))n=n.substr("el:".length),i=e;else{K.call(n,"vm:")?(n=n.substr("vm:".length),i=o,s=o):i=o||e;var u=n.indexOf(":by:");u>=0&&(i=s.get(n.substr(u+":by:".length)),n=n.substr(0,u))}var d=function(n){var i=e.getAttribute(j.encode(a));if(i){var o=c(e),s=r.parse(i,{lookupRule:function(){return r.Lookup},methodRule:"call"});if(!(s instanceof r.Call))throw new Error("can-stache-bindings: Event bindings must be a call expression. Make sure you have a () in "+t.attributeName+"="+JSON.stringify(i));var u,d,p,f=t.scope.add({"%element":this,"%event":n,"%viewModel":o,"%scope":t.scope,"%context":t.scope._context,"%arguments":arguments},{notContext:!0}),h=f.read(s.methodExpr.key,{isArgument:!0});if(!h.value){var m=l.reads(s.methodExpr.key).map(function(e){return e.key}).join(".");return(d=b.getHelper(m))?(u=s.args(f,null)(),"function"==typeof(p=d.fn.apply(f.peek("."),u))&&p(e),p):(v.warn("can-stache-bindings: "+a+" couldn't find method named "+s.methodExpr.key,{element:e,scope:t.scope}),null)}u=s.args(f,null)(),L.batch.start(),L.notifyQueue.enqueue(h.value,h.parent,u,{reasonLog:[e,n,a+"="+i]}),L.batch.stop()}},p=function(e){var t=e.attributeName===a,n=!this.getAttribute(a);t&&n&&h()},f=function(e){h()},h=function(){O.off.call(i,n,d),O.off.call(e,"attributes",p),O.off.call(e,"removed",f)};O.on.call(i,n,d),O.on.call(e,"attributes",p),O.on.call(e,"removed",f)}};o.attr(/[\w\.:]+:to$/,M.data),o.attr(/[\w\.:]+:from$/,M.data),o.attr(/[\w\.:]+:bind$/,M.data),o.attr(/[\w\.:]+:to:on:[\w\.:]+/,M.data),o.attr(/[\w\.:]+:from:on:[\w\.:]+/,M.data),o.attr(/[\w\.:]+:bind:on:[\w\.:]+/,M.data),o.attr(/on:[\w\.:]+/,M.event);var A={viewModelOrAttribute:function(e,t,n,i,a,r,o){return g.get.call(e,"viewModel")?this.viewModel.apply(this,arguments):this.attribute.apply(this,arguments)},scope:function(e,t,n,i,a,o){if(n){if(a)return r.parse(n,{baseMethodType:"Call"}).value(t,new s.Options({}));var c=new u(function(){});return c[D]=function(e){t.set(Q(n),e)},c}return new d},viewModel:function(e,t,n,i,a,r,o){function s(){var e=i.getViewModel();return l.read(e,p,{}).value}var c=Q(n),u="."===n||"this"===n,p=u?[]:l.reads(n);return Object.defineProperty(s,"name",{value:"viewModel."+n}),new E(s,function(e){var t=i.getViewModel();if(r){var n=k.getKeyValue(t,c);k.isObservableLike(n)?k.setValue(n,e):k.setKeyValue(t,c,new d(k.getValue(r)))}else u?k.setValue(t,e):k.setKeyValue(t,c,e)})},attribute:function(e,t,n,i,a,r,o){if(!o){o="change";var s="INPUT"===e.nodeName&&"radio"===e.type,c="checked"===n&&!i.legacyBindings;s&&c&&(o="radiochange"),y.special[n]&&y.special[n].addEventListener&&(o=n)}var l="select"===e.nodeName.toLowerCase(),d=function(){return y.get(e,n)};"value"===n&&l&&e.multiple&&(n="values");var p=new u(d);return p[D]=function(t){return i.legacyBindings&&l&&"selectedIndex"in e&&"value"===n?y.setAttrOrProp(e,n,null==t?"":t):y.setAttrOrProp(e,n,t),t},p[_]=d,p[S]=function(t){var n=function(){t(d())};x.set(t,this,n),"radiochange"===o&&O.on.call(e,"change",n),O.on.call(e,o,n)},p[T]=function(t){var n=x.getAndDelete(t,this);"radiochange"===o&&O.off.call(e,"change",n),O.off.call(e,o,n)},p}},q={childToParent:function(e,t,n,i,a,r,o){function s(o){if(!i[a])if(t&&t[_]){var s=k.valueHasDependencies(t);s&&k.getValue(t)===o||k.setValue(t,o),r&&s&&k.getValue(t)!==k.getValue(n)&&(i[a]=(i[a]||0)+1,L.batch.start(),k.setValue(n,k.getValue(t)),L.mutateQueue.enqueue(function(){--i[a]},null,[],{}),L.batch.stop())}else if(k.isMapLike(t)){var c=e.getAttribute(a);v.warn("can-stache-bindings: Merging "+a+" into "+c+" because its parent is non-observable"),k.eachKey(t,function(e){k.deleteKeyValue(t,e)}),k.setValue(t,o&&o.serialize?o.serialize():o,!0)}}return Object.defineProperty(s,"name",{value:"update "+o.parent+"."+o.parentName+" of <"+e.nodeName.toLowerCase()+">"}),n&&n[_]&&k.onValue(n,s,"mutate"),s},parentToChild:function(e,t,n,i,a,r){var o=function(e){i[a]=(i[a]||0)+1,L.batch.start(),k.setValue(n,e),L.mutateQueue.enqueue(function(){--i[a]},null,[],{}),L.batch.stop()};return Object.defineProperty(o,"name",{value:"update "+r.child+"."+r.childName+" of <"+e.nodeName.toLowerCase()+">"}),t&&t[_]&&k.onValue(t,o,"mutate"),o}},K=String.prototype.startsWith||function(e){return 0===this.indexOf(e)},R={to:{childToParent:!0,parentToChild:!1,syncChildWithParent:!1},from:{childToParent:!1,parentToChild:!0,syncChildWithParent:!1},bind:{childToParent:!0,parentToChild:!0,syncChildWithParent:!0}},I=[],H={vm:!0,on:!0};h(R,function(e,t){I.push(t),H[t]=!0});var B=function(e,t){return e.indexOf("vm")>=0?"viewModel":e.indexOf("el")>=0?"attribute":t?"viewModel":"viewModelOrAttribute"},F=function(e,t,n,r,o){var s,c,l,u=j.decode(e.name),d=e.value||"",f=a(u);if(I.forEach(function(e){if(void 0!==f.special[e]&&f.special[e]>0)return c=e,l=f.special[e],!1}),c){var h=i(f),v=!h;return s=p({parent:"scope",child:B(f.tokens,o),childName:f.tokens[l-1],childEvent:h,bindingAttributeName:u,parentName:d,initializeValues:v},R[c]),"~"===d.trim().charAt(0)&&(s.stickyParentToChild=!0),s}},z=function(e,t,n){var i=F(e,n.attributeViewModelBindings,n.templateType,t.nodeName.toLowerCase(),n.favorViewModel);if(i){i.alreadyUpdatedChild=n.alreadyUpdatedChild,n.initializeValues&&(i.initializeValues=!0);var a,r,o=A[i.parent](t,n.scope,i.parentName,n,i.parentToChild,void 0,void 0,i),s=A[i.child](t,n.scope,i.childName,n,i.childToParent,i.stickyParentToChild&&o,i.childEvent,i);n.nodeList&&(o&&k.setPriority(o,n.nodeList.nesting+1),s&&k.setPriority(s,n.nodeList.nesting+1)),i.parentToChild&&(r=q.parentToChild(t,o,s,n.semaphore,i.bindingAttributeName,i));var c=function(){i.childToParent?a=q.childToParent(t,o,s,n.semaphore,i.bindingAttributeName,i.syncChildWithParent,i):i.stickyParentToChild&&s[S]&&k.onValue(s,C,"mutate"),i.initializeValues&&U(i,s,o,r,a)},l=function(){W(o,r),W(s,a),W(s,C)};return"viewModel"===i.child?{value:i.stickyParentToChild?V(o):k.getValue(o),onCompleteBinding:c,bindingInfo:i,onTeardown:l}:(c(),{bindingInfo:i,onTeardown:l})}},U=function(e,t,n,i,a){var r=!1;e.parentToChild&&!e.childToParent||(!e.parentToChild&&e.childToParent?r=!0:void 0===k.getValue(t)||void 0===k.getValue(n)&&(r=!0)),r?a(k.getValue(t)):e.alreadyUpdatedChild||i(k.getValue(n))},W=function(e,t){e&&e[_]&&"function"==typeof t&&k.offValue(e,t,"mutate")},Q=function(e){return e.replace(/@/g,"")};n.exports={behaviors:M,getBindingInfo:F}}),define("can-component",["require","exports","module","can-component/control/control","can-namespace","can-construct","can-stache-bindings","can-view-scope","can-view-callbacks","can-view-nodelist","can-util/dom/data/data","can-util/dom/mutate/mutate","can-util/dom/child-nodes/child-nodes","can-util/dom/dispatch/dispatch","can-util/js/string/string","can-reflect","can-util/js/each/each","can-util/js/assign/assign","can-util/js/is-function/is-function","can-util/js/log/log","can-util/js/dev/dev","can-util/js/make-array/make-array","can-util/js/is-empty-object/is-empty-object","can-simple-observable","can-simple-map","can-util/dom/events/inserted/inserted","can-util/dom/events/removed/removed","can-view-model","can-globals/document/document"],function(e,t,n){!function(e,t,n,i){function a(e,t,n){var i;f.set.call(e,"preventDataBindings",!0);var a=l.behaviors.viewModel(e,n,function(e){return i=new V(e)},void 0,!0);return a?w(w({},t),{teardown:a,scope:t.scope.add(i)}):t}function r(e,t,n,i,r){var o=n.options._context;return function n(s,c){var l=r(s)||c.subtemplate,u=l!==c.subtemplate;if(l){delete o.tags[e];var d;d=u?i.toLightContent?a(s,{scope:c.scope.cloneFromRef(),options:c.options},c):a(s,t,c):a(s,c,c);var f=p.register([s],function(){d.teardown&&d.teardown()},c.parentNodeList||!0,!1);f.expression="<can-slot name='"+s.getAttribute("name")+"'/>";var h=l(d.scope,d.options,f),m=L(v(h));p.replace(f,h),p.update(f,m),o.tags[e]=n}}}var o=t("can-component/control/control"),s=t("can-namespace"),c=t("can-construct"),l=t("can-stache-bindings"),u=t("can-view-scope"),d=t("can-view-callbacks"),p=t("can-view-nodelist"),f=t("can-util/dom/data/data"),h=t("can-util/dom/mutate/mutate"),v=t("can-util/dom/child-nodes/child-nodes"),m=t("can-util/dom/dispatch/dispatch"),g=t("can-util/js/string/string"),y=t("can-reflect"),b=t("can-util/js/each/each"),w=t("can-util/js/assign/assign"),k=t("can-util/js/is-function/is-function"),x=t("can-util/js/log/log"),j=t("can-util/js/dev/dev"),L=t("can-util/js/make-array/make-array"),E=t("can-util/js/is-empty-object/is-empty-object"),V=t("can-simple-observable"),O=t("can-simple-map");t("can-util/dom/events/inserted/inserted"),t("can-util/dom/events/removed/removed"),t("can-view-model");var C=t("can-globals/document/document"),_=c.extend({setup:function(){if(c.setup.apply(this,arguments),_){var e=this;E(this.prototype.events)||(this.Control=o.extend(this.prototype.events)),this.prototype.viewModel&&y.isConstructorLike(this.prototype.viewModel)&&j.warn("can-component: Assigning a DefineMap or constructor type to the viewModel property may not be what you intended. Did you mean ViewModel instead? More info: https://canjs.com/doc/can-component.prototype.ViewModel.html");var t=this.prototype.viewModel||this.prototype.scope;if(t&&this.prototype.ViewModel)throw new Error("Cannot provide both a ViewModel and a viewModel property");var n=g.capitalize(g.camelize(this.prototype.tag))+"VM";this.prototype.ViewModel?"function"==typeof this.prototype.ViewModel?this.ViewModel=this.prototype.ViewModel:this.ViewModel=O.extend(n,this.prototype.ViewModel):t?"function"==typeof t?y.isObservableLike(t.prototype)&&y.isMapLike(t.prototype)?this.ViewModel=t:this.viewModelHandler=t:y.isObservableLike(t)&&y.isMapLike(t)?(x.warn("can-component: "+this.prototype.tag+" is sharing a single map across all component instances"),this.viewModelInstance=t):this.ViewModel=O.extend(n,t):this.ViewModel=O.extend(n,{}),this.prototype.template&&(x.warn("can-component.prototype.template: is deprecated and will be removed in a future release. Use can-component.prototype.view"),this.renderer=this.prototype.template),this.prototype.view&&(this.renderer=this.prototype.view),d.tag(this.prototype.tag,function(t,n){new e(t,n)}),this.prototype.autoMount&&b(C().getElementsByTagName(this.prototype.tag),function(t){f.get.call(t,"viewModel")||new e(t,{scope:new u,options:new u.Options({}),templates:{},subtemplate:null})})}}},{setup:function(e,t){var n,i,a,o=this,s=[];if(!f.get.call(e,"preventDataBindings")){var c=t.setupBindings||function(e,n,i){return l.behaviors.viewModel(e,t,n,i)};a=c(e,function(i){var a=o.constructor.ViewModel,r=o.constructor.viewModelHandler,s=o.constructor.viewModelInstance;if(r){var c=r.call(o,i,t.scope,e);y.isObservableLike(c)&&y.isMapLike(c)?s=c:a=y.isObservableLike(c.prototype)&&y.isMapLike(c.prototype)?c:O.extend(c)}return a&&(s=new o.constructor.ViewModel(i)),n=s,s},{})}this.viewModel=n,f.set.call(e,"viewModel",n),f.set.call(e,"preventDataBindings",!0);var d={helpers:{},tags:{}};b(this.helpers||{},function(e,t){k(e)&&(d.helpers[t]=e.bind(n))}),this.constructor.Control&&(this._control=new this.constructor.Control(e,{scope:this.viewModel,viewModel:this.viewModel,destroy:function(){for(var e=0,t=s.length;e<t;e++)s[e]()}}));var g,w,x={toLightContent:!0===this.leakScope,intoShadowContent:!0===this.leakScope};if(!!this.constructor.renderer){var j;j=x.intoShadowContent?{scope:t.scope.add(new u.Refs).add(this.viewModel,{viewModel:!0}),options:t.options.add(d)}:{scope:u.refsScope().add(this.viewModel,{viewModel:!0}),options:new u.Options(d)},d.tags["can-slot"]=r("can-slot",t,j,x,function(e){return t.templates[e.getAttribute("name")]}),d.tags.content=r("content",t,j,x,function(){return t.subtemplate}),g=this.constructor.renderer,w=j}else w={scope:t.scope.add(this.viewModel,{viewModel:!0}),options:t.options.add(d)},g=t.subtemplate||e.ownerDocument.createDocumentFragment.bind(e.ownerDocument);var L=p.register([],function(){m.call(e,"beforeremove",[],!1),a&&a()},t.parentNodeList||!0,!1);L.expression="<"+this.tag+">",s.push(function(){p.unregister(L)}),i=g(w.scope,w.options,L),h.appendChild.call(e,i),p.update(L,v(e))}});i.exports=s.Component=_}(0,e,0,n)}),define("can-simple-observable/async/async",["require","exports","module","can-simple-observable","can-observation","can-key-tree","can-queues","can-simple-observable/settable/settable","can-reflect","can-observation-recorder"],function(e,t,n){function i(e,t,n){function i(){return this.resolveCalled=!1,e.call(t,this.lastSetValue.get(),!0===this.bound?this.resolve:void 0)}this.handlers=new o([Object,Array],{onFirst:this.setup.bind(this),onEmpty:this.teardown.bind(this)}),this.resolve=this.resolve.bind(this),this.lastSetValue=new a(n),this.handler=this.handler.bind(this),l.assignSymbols(this,{"can.getName":function(){return l.getName(this.constructor)+"<"+l.getName(e)+">"}}),Object.defineProperty(this.handler,"name",{value:l.getName(this)+".handler"}),Object.defineProperty(i,"name",{value:l.getName(e)+"::"+l.getName(this.constructor)}),this.observation=new r(i,this)}var a=e("can-simple-observable"),r=e("can-observation"),o=e("can-key-tree"),s=e("can-queues"),c=e("can-simple-observable/settable/settable"),l=e("can-reflect"),u=e("can-observation-recorder");(i.prototype=Object.create(c.prototype)).constructor=i,i.prototype.handler=function(e){void 0!==e&&c.prototype.handler.apply(this,arguments)};var d=u.ignore(l.getValue.bind(l));i.prototype.setup=function(){this.bound=!0,l.onValue(this.observation,this.handler,"notify"),this.resolveCalled||(this.value=d(this.observation))},i.prototype.resolve=function(e){this.resolveCalled=!0;var t=this.value;this.value=e,"function"==typeof this._log&&this._log(t,e),s.enqueueByQueue(this.handlers.getNode([]),this,[e,t],function(){return{}})},n.exports=i}),define("can-util/js/defaults/defaults",function(e,t,n){"use strict";n.exports=function(e){for(var t=arguments.length,n=1;n<t;n++)for(var i in arguments[n])void 0===e[i]&&(e[i]=arguments[n][i]);return e}}),define("can-util/js/string-to-any/string-to-any",function(e,t,n){"use strict";n.exports=function(e){switch(e){case"NaN":case"Infinity":return+e;case"null":return null;case"undefined":return;case"true":case"false":return"true"===e;default:var t=+e;return isNaN(t)?e:t}}}),define("can-define-lazy-value",function(e,t,n){n.exports=function(e,t,n,i){Object.defineProperty(e,t,{configurable:!0,get:function(){Object.defineProperty(this,t,{value:void 0,writable:!0});var a=n.call(this,e,t);return Object.defineProperty(this,t,{value:a,writable:!!i}),a},set:function(e){return Object.defineProperty(this,t,{value:e,writable:!!i}),e}})}}),define("can-define",["require","exports","module","can-namespace","can-symbol","can-reflect","can-observation","can-simple-observable/async/async","can-simple-observable/settable/settable","can-cid","can-event-queue","can-queues","can-util/js/is-empty-object/is-empty-object","can-util/js/assign/assign","can-util/js/dev/dev","can-util/js/is-plain-object/is-plain-object","can-util/js/each/each","can-util/js/defaults/defaults","can-util/js/string-to-any/string-to-any","can-define-lazy-value"],function(e,t,n){"use strict";"format cjs";function i(e){return f.isValueLike(e)&&f.isObservableLike(e)}var a,r,o,s,c,l,u,d=e("can-namespace"),p=e("can-symbol"),f=e("can-reflect"),h=e("can-observation"),v=e("can-simple-observable/async/async"),m=e("can-simple-observable/settable/settable"),g=e("can-cid"),y=e("can-event-queue"),b=e("can-queues"),w=e("can-util/js/is-empty-object/is-empty-object"),k=e("can-util/js/assign/assign"),x=e("can-util/js/dev/dev"),j=e("can-util/js/is-plain-object/is-plain-object"),L=e("can-util/js/each/each"),E=e("can-util/js/defaults/defaults"),V=e("can-util/js/string-to-any/string-to-any"),O=e("can-define-lazy-value"),C=function(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:!0,value:n})},_=function(e,t){for(var n in e)e.hasOwnProperty(n)&&t(n,Object.getOwnPropertyDescriptor(e,n))};n.exports=r=d.define=function(e,t,n){var i,o=Object.create(n?n.dataInitializers:null),s=Object.create(n?n.computedInitializers:null),l=c(t,n);if(l.dataInitializers=o,l.computedInitializers=s,L(l.definitions,function(t,n){r.property(e,n,t,o,s)}),e.hasOwnProperty("_data"))for(i in o)O(e._data,i,o[i].bind(e),!0);else O(e,"_data",function(){var e=this,t={};for(var n in o)O(t,n,o[n].bind(e),!0);return t});if(e.hasOwnProperty("_computed"))for(i in s)O(e._computed,i,s[i].bind(e));else O(e,"_computed",function(){var e=this,t=Object.create(null);for(var n in s)O(t,n,s[n].bind(e));return t});e.hasOwnProperty("_cid")||O(e,"_cid",function(){return g({})});for(i in a)Object.defineProperty(e,i,{enumerable:!1,value:a[i],configurable:!0,writable:!0});Object.defineProperty(e,"_define",{enumerable:!1,value:l,configurable:!0,writable:!0});var u=p.iterator||p.for("iterator");return e[u]||C(e,u,function(){return new r.Iterator(this)}),l},r.extensions=function(){};var D=function(e){for(var t in e)if("type"!==t)return!1;return!0};r.property=function(e,t,n,i,a){var s=r.extensions.apply(this,arguments);s&&(n=s);var c=n.type;if(c&&f.isConstructorLike(c)&&x.warn("can-define: the definition for "+t+(e.constructor.shortName?" on "+e.constructor.shortName:"")+' uses a constructor for "type". Did you mean "Type"?'),c&&D(n)&&c===r.types["*"])Object.defineProperty(e,t,{get:o.get.data(t),set:o.set.events(t,o.get.data(t),o.set.data(t),o.eventType.data(t)),enumerable:!0,configurable:!0});else{n.type=c;var l,u=n.get?"computed":"data",d=o.read[u](t),p=o.get[u](t),v=o.set[u](t);n.get&&Object.defineProperty(n.get,"name",{value:f.getName(e)+"'s "+t+" getter"}),n.set&&Object.defineProperty(n.set,"name",{value:f.getName(e)+"'s "+t+" setter"});var m=function(e){return e};n.Type&&(m=o.set.Type(t,n.Type,m)),c&&(m=o.set.type(t,c,m));var g=o.set.events(t,d,v,o.eventType[u](t));void 0===n.value&&void 0===n.Value||(null!==n.value&&"object"==typeof n.value&&x.warn("can-define: The value for "+t+" is set to an object. This will be shared by all instances of the DefineMap. Use a function that returns the object instead."),n.value&&f.isConstructorLike(n.value)&&x.warn('can-define: The "value" for '+t+' is set to a constructor. Did you mean "Value" instead?'),l=h.ignore(o.get.defaultValue(t,n,m,g))),n.get?a[t]=o.compute(t,n.get,l):l&&(i[t]=l),n.get&&n.set?v=o.set.setter(t,n.set,o.read.lastSet(t),v,!0):n.set?v=o.set.setter(t,n.set,d,g,!1):n.get?n.get.length<1&&(v=function(){x.warn("can-define: Set value for property "+t+(e.constructor.shortName?" on "+e.constructor.shortName:"")+" ignored, as its definition has a zero-argument getter and no setter")}):v=g,c&&(v=o.set.type(t,c,v)),n.Type&&(v=o.set.Type(t,n.Type,v)),Object.defineProperty(e,t,{get:p,set:v,enumerable:"serialize"in n?!!n.serialize:!n.get,configurable:!0})}},r.Constructor=function(e){var t=function(e){r.setup.call(this,e)};return r(t.prototype,e),t},o={compute:function(e,t,n){return function(){var i,a,r=this,o=n&&n.call(this);return i=0===t.length?new h(t,r):1===t.length?new m(t,r,o):new v(t,r,o),a={oldValue:void 0,compute:i,count:0,handler:function(t){var n=a.oldValue;a.oldValue=t,r.dispatch({type:e,target:r},[t,n])}},Object.defineProperty(a.handler,"name",{value:f.getName(t).replace("getter","event emitter")}),a}},set:{data:function(e){return function(t){this._data[e]=t}},computed:function(e){return function(t){f.setValue(this._computed[e].compute,t)}},events:function(e,t,n,i){return function(i){if(this.__inSetup)n.call(this,i);else{var a=t.call(this);i!==a&&(n.call(this,i),this.dispatch({type:e,target:this,reasonLog:[f.getName(this)+"'s",e,"changed to",i,"from",a]},[i,a]))}}},setter:function(e,t,n,i,a){return function(r){var o,s=this;b.batch.start();var c=!1,l=n.call(this),u=t.call(this,r,function(e){i.call(s,e),c=!0,clearTimeout(o)},l);if(c)b.batch.stop();else if(a)if(void 0!==u)l!==u&&i.call(this,u),b.batch.stop();else{if(0===t.length)return i.call(this,r),void b.batch.stop();if(1!==t.length)return o=setTimeout(function(){x.warn('can/map/setter.js: Setter "'+e+'" did not return a value or call the setter callback.')},x.warnTimeout),void b.batch.stop();b.batch.stop()}else if(void 0!==u)i.call(this,u),b.batch.stop();else{if(0===t.length)return i.call(this,r),void b.batch.stop();if(1!==t.length)return o=setTimeout(function(){x.warn('can/map/setter.js: Setter "'+e+'" did not return a value or call the setter callback.')},x.warnTimeout),void b.batch.stop();i.call(this,void 0),b.batch.stop()}}},type:function(e,t,n){return"object"==typeof t?o.set.Type(e,t,n):function(i){return n.call(this,t.call(this,i,e))}},Type:function(e,t,n){return Array.isArray(t)&&r.DefineList?t=r.DefineList.extend({"#":t[0]}):"object"==typeof t&&(t=r.DefineMap?r.DefineMap.extend(t):r.Constructor(t)),function(e){return e instanceof t||null==e?n.call(this,e):n.call(this,new t(e))}}},eventType:{data:function(e){return function(t,n){return void 0!==n||this._data.hasOwnProperty(e)?"set":"add"}},computed:function(){return function(){return"set"}}},read:{data:function(e){return function(){return this._data[e]}},computed:function(e){return function(){return f.getValue(this._computed[e].compute)}},lastSet:function(e){return function(){var t=this._computed[e].compute;if(t.lastSetValue)return f.getValue(t.lastSetValue)}}},get:{defaultValue:function(e,t,n,i){return function(){var a=t.value;if(void 0!==a)"function"==typeof a&&(a=a.call(this)),a=n(a);else{var r=t.Value;r&&(a=n(new r))}if(t.set){var s,c=!0;return o.set.setter(e,t.set,function(){},function(e){c?s=e:i.call(this,e)},t.get).call(this,a),c=!1,s}return a}},data:function(e){return function(){return this.__inSetup||h.add(this,e),this._data[e]}},computed:function(e){return function(){return f.getValue(this._computed[e].compute)}}}},r.behaviors=["get","set","value","Value","type","Type","serialize"];var S=function(e,t,n){if("type"===t){var i=n;"string"==typeof i&&"object"==typeof(i=r.types[i])&&(k(e,i),i=i[t]),e[t]=i}else e[t]=n};s=function(e,t,n){var i={};return L(t,function(e,t){S(i,t,e)}),L(n,function(e,t){void 0===i[t]&&"type"!==t&&"Type"!==t&&(i[t]=e)}),i.type||i.Type||E(i,n),w(i)&&(i.type=r.types["*"]),i},u=function(e,t,n){var i;return"string"==typeof t?i={type:t}:"function"==typeof t?f.isConstructorLike(t)?i={Type:t}:l(t)&&(i={type:t}):Array.isArray(t)?i={Type:t}:j(t)&&(i=t),i?s(0,i,n):t},c=function(e,t){var n,i=Object.create(t?t.definitions:null),a={},r=e["*"];return r?(delete e["*"],n=u(0,r,{})):n=Object.create(null),_(e,function(e,t){var r;if(r=t.get||t.set?{get:t.get,set:t.set}:t.value,"constructor"!==e){var o=u(0,r,n);o&&"object"==typeof o?i[e]=o:a[e]=o}else a[e]=r}),r&&(e["*"]=r),{definitions:i,methods:a,defaultDefinition:n}},a=y({});var T=p.for("can.meta");k(a,{_eventSetup:function(){},_eventTeardown:function(){},addEventListener:function(e,t,n){var i=this._computed&&this._computed[e];return i&&i.compute&&(i.count?i.count++:(i.count=1,f.onValue(i.compute,i.handler,"notify"),i.oldValue=f.getValue(i.compute))),y.addEventListener.apply(this,arguments)},removeEventListener:function(e,t){var n=this._computed&&this._computed[e];return n&&(1===n.count?(n.count=0,f.offValue(n.compute,n.handler,"notify")):n.count--),y.removeEventListener.apply(this,arguments)}}),a.on=a.bind=a.addEventListener,a.off=a.unbind=a.removeEventListener,delete a.one,r.setup=function(e,t){g(this),Object.defineProperty(this,"_cid",{value:this._cid,enumerable:!1,writable:!1}),Object.defineProperty(this,"constructor",{value:this.constructor,enumerable:!1,writable:!1}),Object.defineProperty(this,T,{value:Object.create(null),enumerable:!1,writable:!1});var n=this._define.definitions,i=Object.create(null),a=this;f.eachKey(e,function(e,t){if(void 0!==n[t])a[t]=e;else{var o=r.makeSimpleGetterSetter(t);i[t]={},Object.defineProperty(a,t,o),a[t]=r.types.observable(e)}}),w(i)||C(this,"_instanceDefinitions",i),this._data,this._computed,!1!==t&&Object.seal(this)},r.replaceWith=O,r.eventsProto=a,r.defineConfigurableAndNotEnumerable=C,r.make=o,r.getDefinitionOrMethod=u;var N={};r.makeSimpleGetterSetter=function(e){if(!N[e]){var t=o.set.events(e,o.get.data(e),o.set.data(e),o.eventType.data(e));N[e]={get:o.get.data(e),set:function(e){return t.call(this,r.types.observable(e))},enumerable:!0}}return N[e]},r.Iterator=function(e){this.obj=e,this.definitions=Object.keys(e._define.definitions),this.instanceDefinitions=e._instanceDefinitions?Object.keys(e._instanceDefinitions):Object.keys(e),this.hasGet="function"==typeof e.get},r.Iterator.prototype.next=function(){var e;if(this.definitions.length){if(e=this.definitions.shift(),this.obj._define.definitions[e].get)return this.next()}else{if(!this.instanceDefinitions.length)return{value:void 0,done:!0};e=this.instanceDefinitions.shift()}return{value:[e,this.hasGet?this.obj.get(e):this.obj[e]],done:!1}},l=function(e){return e&&!0===e.canDefineType},r.types={date:function(e){var t=typeof e;return"string"===t?(e=Date.parse(e),isNaN(e)?null:new Date(e)):"number"===t?new Date(e):e},number:function(e){return null==e?e:+e},boolean:function(e){return null==e?e:!("false"===e||"0"===e||!e)},observable:function(e){return Array.isArray(e)&&r.DefineList?e=new r.DefineList(e):j(e)&&r.DefineMap&&(e=new r.DefineMap(e)),e},stringOrObservable:function(e){return Array.isArray(e)?new r.DefaultList(e):j(e)?new r.DefaultMap(e):r.types.string(e)},htmlbool:function(e){return""===e||!!V(e)},"*":function(e){return e},any:function(e){return e},string:function(e){return null==e?e:""+e},compute:{set:function(e,t,n,a){return i(e)?e:i(a)?(f.setValue(a,e),a):e},get:function(e){return i(e)?f.getValue(e):e}}}}),define("can-define/define-helpers/define-helpers",["require","exports","module","can-define","can-reflect","can-queues"],function(e,t,n){var i=e("can-define"),a=e("can-reflect"),r=e("can-queues"),o={defineExpando:function(e,t,n){var a=e._define.definitions;if(!a||!a[t]){var o=e._instanceDefinitions;if(o||(Object.defineProperty(e,"_instanceDefinitions",{configurable:!0,enumerable:!1,value:{}}),o=e._instanceDefinitions),!o[t]){var s=e._define.defaultDefinition||{type:i.types.observable};return i.property(e,t,s,{},{}),e._data[t]=s.type?s.type(n):i.types.observable(n),o[t]=s,r.batch.start(),e.dispatch({type:"__keys",target:e}),void 0!==e._data[t]&&e.dispatch({type:t,target:e},[e._data[t],void 0]),r.batch.stop(),!0}}},reflectSerialize:function(e){var t=this._define.definitions,n=this._define.defaultDefinition;return this.each(function(i,r){var o=t[r];void 0!==(i=o&&"function"==typeof o.serialize?o.serialize.call(this,i,r):n&&"function"==typeof n.serialize?n.serialize.call(this,i,r):a.serialize(i))&&(e[r]=i)},this),e},reflectUnwrap:function(e){return this.forEach(function(t,n){void 0!==t&&(e[n]=a.unwrap(t))}),e}};n.exports=o}),define("can-util/js/cid-set/cid-set",["require","exports","module","can-cid/set/set"],function(e,t,n){!function(e,t,n,i){"use strict";i.exports=t("can-cid/set/set")}(0,e,0,n)}),define("can-define/ensure-meta",["require","exports","module","can-symbol","can-reflect"],function(e,t,n){var i=e("can-symbol"),a=e("can-reflect");n.exports=function(e){var t=i.for("can.meta"),n=e[t];return n||(n={},a.setKeyValue(e,t,n)),n}}),define("can-define/map/map",["require","exports","module","can-construct","can-define","can-define/define-helpers/define-helpers","can-observation","can-namespace","can-util/js/log/log","can-reflect","can-symbol","can-util/js/cid-set/cid-set","can-util/js/cid-map/cid-map","can-util/js/dev/dev","can-queues","can-define/ensure-meta","can-log/dev/dev"],function(e,t,n){function i(e){w.batch.start(),v.assignMap(this,e||{}),w.batch.stop()}function a(e){w.batch.start(),v.updateMap(this,e||{}),w.batch.stop()}function r(e){w.batch.start(),v.assignDeepMap(this,e||{}),w.batch.stop()}function o(e){w.batch.start(),v.updateDeepMap(this,e||{}),w.batch.stop()}function s(e,t){d.defineExpando(this,e,t)||(this[e]=t)}function c(e){var t=this[e];return void 0!==t||e in this||Object.isSealed(this)?t:(p.add(this,e),this[e])}var l=e("can-construct"),u=e("can-define"),d=e("can-define/define-helpers/define-helpers"),p=e("can-observation"),f=e("can-namespace"),h=e("can-util/js/log/log"),v=e("can-reflect"),m=e("can-symbol"),g=e("can-util/js/cid-set/cid-set"),y=e("can-util/js/cid-map/cid-map"),b=e("can-util/js/dev/dev"),w=e("can-queues"),k=e("can-define/ensure-meta"),x=e("can-log/dev/dev"),j=function(e){var t=[];for(var n in e){var i=e[n];"object"==typeof i&&("serialize"in i?!i.serialize:i.get)||t.push(n)}return t},L=l.extend("DefineMap",{setup:function(e){var t,n=this.prototype;if(L){u(n,n,e.prototype._define);for(t in L.prototype)u.defineConfigurableAndNotEnumerable(n,t,n[t]);this.prototype.setup=function(e){u.setup.call(this,e||{},this.constructor.seal)}}else for(t in n)u.defineConfigurableAndNotEnumerable(n,t,n[t]);u.defineConfigurableAndNotEnumerable(n,"constructor",this)}},{setup:function(e,t){this._define||(Object.defineProperty(this,"_define",{enumerable:!1,value:{definitions:{}}}),Object.defineProperty(this,"_data",{enumerable:!1,value:{}})),u.setup.call(this,e||{},!0===t)},get:function(e){return e?c.call(this,e):v.unwrap(this,y)},set:function(e,t){return"object"==typeof e?(b.warn("can-define/map/map.prototype.set is deprecated; please use can-define/map/map.prototype.assign or can-define/map/map.prototype.update instead"),!0===t?o.call(this,e):r.call(this,e)):s.call(this,e,t),this},assignDeep:function(e){return r.call(this,e),this},updateDeep:function(e){return o.call(this,e),this},assign:function(e){return i.call(this,e),this},update:function(e){return a.call(this,e),this},serialize:function(){return v.serialize(this,y)},forEach:function(){var e=function(e,t,n){return v.eachKey(e,t,n)},t=p.ignore(e);return function(n,i,a){return!1===a?t(this,n,i):e(this,n,i)}}(),"*":{type:u.types.observable},log:function(e){var t=this,n=function(e){return"string"==typeof e?JSON.stringify(e):e},i=k(t),a=i.allowedLogKeysSet||new Set;i.allowedLogKeysSet=a,e&&a.add(e),i._log=function(i,r){var o=i.type;"__keys"===o||e&&!a.has(o)||x.log(v.getName(t),"\n key ",n(o),"\n is ",n(r[0]),"\n was ",n(r[1]))}}});v.assignSymbols(L.prototype,{"can.isMapLike":!0,"can.isListLike":!1,"can.isValueLike":!1,"can.getKeyValue":c,"can.setKeyValue":s,"can.deleteKeyValue":function(e){return this.set(e,void 0),this},"can.getOwnEnumerableKeys":function(){return p.add(this,"__keys"),j(this._define.definitions).concat(j(this._instanceDefinitions))},"can.assignDeep":r,"can.updateDeep":o,"can.unwrap":d.reflectUnwrap,"can.serialize":d.reflectSerialize,"can.keyHasDependencies":function(e){return!!(this._computed&&this._computed[e]&&this._computed[e].compute)},"can.getKeyDependencies":function(e){var t;return this._computed&&this._computed[e]&&this._computed[e].compute&&((t={}).valueDependencies=new g,t.valueDependencies.add(this._computed[e].compute)),t},"can.getName":function(){return v.getName(this.constructor)+"{}"}}),v.setKeyValue(L.prototype,m.iterator,function(){return new u.Iterator(this)});for(var E in u.eventsProto)L[E]=u.eventsProto[E],Object.defineProperty(L.prototype,E,{enumerable:!1,value:u.eventsProto[E],writable:!0});("getOwnPropertySymbols"in Object?Object.getOwnPropertySymbols(u.eventsProto):[m.for("can.onKeyValue"),m.for("can.offKeyValue")]).forEach(function(e){Object.defineProperty(L.prototype,e,{enumerable:!1,value:u.eventsProto[e],writable:!0})}),u.DefineMap=L,Object.defineProperty(L.prototype,"toObject",{enumerable:!1,writable:!0,value:function(){return h.warn("Use DefineMap::get instead of DefineMap::toObject"),this.get()}}),Object.defineProperty(L.prototype,"each",{enumerable:!1,writable:!0,value:L.prototype.forEach}),n.exports=f.DefineMap=L}),define("can-define/list/list",["require","exports","module","can-construct","can-define","can-queues","can-observation","can-util/js/log/log","can-util/js/dev/dev","can-define/define-helpers/define-helpers","can-log/dev/dev","can-define/ensure-meta","can-util/js/assign/assign","can-util/js/diff/diff","can-util/js/each/each","can-util/js/make-array/make-array","can-namespace","can-reflect","can-symbol","can-util/js/cid-set/cid-set","can-util/js/cid-map/cid-map","can-util/js/single-reference/single-reference"],function(e,t,n){var i=e("can-construct"),a=e("can-define"),r=a.make,o=e("can-queues"),s=e("can-observation"),c=e("can-util/js/log/log"),l=e("can-util/js/dev/dev"),u=e("can-define/define-helpers/define-helpers"),d=e("can-log/dev/dev"),p=e("can-define/ensure-meta"),f=e("can-util/js/assign/assign"),h=e("can-util/js/diff/diff"),v=e("can-util/js/each/each"),m=e("can-util/js/make-array/make-array"),g=e("can-namespace"),y=e("can-reflect"),b=e("can-symbol"),w=e("can-util/js/cid-set/cid-set"),k=e("can-util/js/cid-map/cid-map"),x=e("can-util/js/single-reference/single-reference"),j=[].splice,L=!1,E=function(e){return e},V=function(e){return function(t){for(var n in e)if(t[n]!==e[n])return!1;return!0}},O=a.eventsProto[b.for("can.onKeyValue")],C=a.eventsProto[b.for("can.offKeyValue")],_=i.extend("DefineList",{setup:function(e){if(_){var t=this.prototype,n=a(t,t,e.prototype._define),i=n.definitions["#"]||n.defaultDefinition;i&&(i.Type?this.prototype.__type=r.set.Type("*",i.Type,E):i.type&&(this.prototype.__type=r.set.type("*",i.type,E)))}}},{setup:function(e){this._define||(Object.defineProperty(this,"_define",{enumerable:!1,value:{definitions:{length:{type:"number"},_length:{type:"number"}}}}),Object.defineProperty(this,"_data",{enumerable:!1,value:{}})),a.setup.call(this,{},!1),Object.defineProperty(this,"_length",{enumerable:!1,configurable:!0,writable:!0,value:0}),e&&this.splice.apply(this,[0,0].concat(y.toArray(e)))},__type:a.types.observable,_triggerChange:function(e,t,n,i){var a=+e;if(isNaN(a))this.dispatch({type:""+e,target:this},[n,i]);else{var r=this._define.definitions["#"];"add"===t?(r&&"function"==typeof r.added&&s.ignore(r.added).call(this,n,a),o.batch.start(),this.dispatch({type:t,reasonLog:[y.getName(this),"added",JSON.stringify(n),"at",a]},[n,a]),this.dispatch("can.onPatches",[[{insert:n,index:a,deleteCount:0}]]),o.batch.stop()):"remove"===t?(r&&"function"==typeof r.removed&&s.ignore(r.removed).call(this,i,a),o.batch.start(),this.dispatch({type:t,reasonLog:[y.getName(this),"remove",JSON.stringify(i),"at",a]},[i,a]),this.dispatch("can.onPatches",[[{index:a,deleteCount:i.length}]]),o.batch.stop()):this.dispatch(t,[n,a])}},get:function(e){return arguments.length?(isNaN(e)?s.add(this,e):s.add(this,"length"),this[e]):y.unwrap(this,k)},set:function(e,t){if("object"!=typeof e)if("number"==typeof(e=isNaN(+e)||e%1?e:+e)){if("number"==typeof e&&e>this._length-1){var n=new Array(e+1-this._length);return n[n.length-1]=t,this.push.apply(this,n),n}this.splice(e,1,t)}else u.defineExpando(this,e,t)||(this[e]=t);else l.warn("can-define/list/list.prototype.set is deprecated; please use can-define/list/list.prototype.assign or can-define/list/list.prototype.update instead"),y.isListLike(e)?t?this.replace(e):y.assignList(this,e):y.assignMap(this,e);return this},assign:function(e){return y.isListLike(e)?y.assignList(this,e):y.assignMap(this,e),this},update:function(e){return y.isListLike(e)?y.updateList(this,e):y.updateMap(this,e),this},assignDeep:function(e){return y.isListLike(e)?y.assignDeepList(this,e):y.assignDeepMap(this,e),this},updateDeep:function(e){return y.isListLike(e)?y.updateDeepList(this,e):y.updateDeepMap(this,e),this},_items:function(){var e=[];return this._each(function(t){e.push(t)}),e},_each:function(e){for(var t=0,n=this._length;t<n;t++)e(this[t],t)},splice:function(e,t){var n,i,a,r=m(arguments),s=[],c=r.length>2,l=this._length;for(e=e||0,n=0,i=r.length-2;n<i;n++)r[a=n+2]=this.__type(r[a],a),s.push(r[a]),this[n+e]!==r[a]&&(c=!1);if(c&&this._length<=s.length)return s;void 0===t&&(t=r[1]=this._length-e),L=!0;var u=j.apply(this,r);return L=!1,o.batch.start(),t>0&&this._triggerChange(""+e,"remove",void 0,u),r.length>2&&this._triggerChange(""+e,"add",s,u),this.dispatch("length",[this._length,l]),o.batch.stop(),u},serialize:function(){return y.serialize(this,k)},log:function(e){var t=this,n=function(e){return"string"==typeof e?JSON.stringify(e):e},i=p(t),a=i.allowedLogKeysSet||new Set;i.allowedLogKeysSet=a,e&&a.add(e),i._log=function(i,r){var o=i.type;"can.onPatches"===o||e&&!a.has(o)||("add"===o||"remove"===o?d.log(y.getName(t),"\n how ",n(o),"\n what ",n(r[0]),"\n index ",n(r[1])):d.log(y.getName(t),"\n key ",n(o),"\n is ",n(r[0]),"\n was ",n(r[1])))}}}),D=function(e){return e[0]&&Array.isArray(e[0])?e[0]:m(e)};v({push:"length",unshift:0},function(e,t){var n=[][t];_.prototype[t]=function(){for(var t,i,a=[],r=e?this._length:0,s=arguments.length;s--;)i=arguments[s],a[s]=this.__type(i,s);return L=!0,t=n.apply(this,a),L=!1,this.comparator&&!a.length||(o.batch.start(),this._triggerChange(""+r,"add",a,void 0),this.dispatch("length",[this._length,r]),o.batch.stop()),t}}),v({pop:"length",shift:0},function(e,t){var n=[][t];_.prototype[t]=function(){if(this._length){var t,i=D(arguments),a=e&&this._length?this._length-1:0,r=this._length?this._length:0;return L=!0,t=n.apply(this,i),L=!1,o.batch.start(),this._triggerChange(""+a,"remove",void 0,[t]),this.dispatch("length",[this._length,r]),o.batch.stop(),t}}}),v({map:3,filter:3,reduce:4,reduceRight:4,every:3,some:3},function(e,t){_.prototype[t]=function(){var n=this,i=[].slice.call(arguments,0),a=i[0],r=i[e-1]||n;"object"==typeof a&&(a=V(a)),i[0]=function(){var t=[].slice.call(arguments,0);return t[e-3]=n.get(t[e-2]),a.apply(r,t)};var o=Array.prototype[t].apply(this,i);return"map"===t?new _(o):"filter"===t?new n.constructor(o):o}}),f(_.prototype,{indexOf:function(e,t){for(var n=t||0,i=this.length;n<i;n++)if(this.get(n)===e)return n;return-1},lastIndexOf:function(e,t){for(var n=t=void 0===t?this.length-1:t;n>=0;n--)if(this.get(n)===e)return n;return-1},join:function(){return s.add(this,"length"),[].join.apply(this,arguments)},reverse:function(){var e=[].reverse.call(this._items());return this.replace(e)},slice:function(){s.add(this,"length");var e=Array.prototype.slice.apply(this,arguments);return new this.constructor(e)},concat:function(){var e=[];return v(arguments,function(t){y.isListLike(t)?(Array.isArray(t)?t:m(t)).forEach(function(t){e.push(this.__type(t))},this):e.push(this.__type(t))},this),new this.constructor(Array.prototype.concat.apply(m(this),e))},forEach:function(e,t){for(var n,i=0,a=this.length;i<a&&(n=this.get(i),!1!==e.call(t||n,n,i,this));i++);return this},replace:function(e){var t=h(this,e);o.batch.start();for(var n=0,i=t.length;n<i;n++)this.splice.apply(this,[t[n].index,t[n].deleteCount].concat(t[n].insert));return o.batch.stop(),this},sort:function(e){var t=Array.prototype.slice.call(this);Array.prototype.sort.call(this,e);var n=Array.prototype.slice.call(this);return o.batch.start(),this.dispatch("remove",[t,0]),this.dispatch("add",[n,0]),this.dispatch("length",[this._length,this._length]),o.batch.stop(),this}});for(var S in a.eventsProto)_[S]=a.eventsProto[S],Object.defineProperty(_.prototype,S,{enumerable:!1,value:a.eventsProto[S],writable:!0});Object.defineProperty(_.prototype,"length",{get:function(){return this.__inSetup||s.add(this,"length"),this._length},set:function(e){if(L)this._length=e;else if(null!=e&&!isNaN(+e)&&e!==this._length)if(e>this._length-1){var t=new Array(e-this._length);this.push.apply(this,t)}else this.splice(e)},enumerable:!0}),Object.defineProperty(_.prototype,"each",{enumerable:!1,writable:!0,value:_.prototype.forEach}),_.prototype.attr=function(e,t){return c.warn("DefineMap::attr shouldn't be called"),0===arguments.length?this.get():e&&"object"==typeof e?this.set.apply(this,arguments):1===arguments.length?this.get(e):this.set(e,t)},_.prototype.item=function(e,t){return 1===arguments.length?this.get(e):this.set(e,t)},_.prototype.items=function(){return c.warn("DefineList::get should should be used instead of DefineList::items"),this.get()},y.assignSymbols(_.prototype,{"can.isMoreListLikeThanMapLike":!0,"can.isMapLike":!0,"can.isListLike":!0,"can.isValueLike":!1,"can.getKeyValue":_.prototype.get,"can.setKeyValue":_.prototype.set,"can.onKeyValue":function(e,t,n){var i;return isNaN(e)?O.apply(this,arguments):(i=function(){t(this[e])},Object.defineProperty(i,"name",{value:"translationHandler("+e+")::"+y.getName(this)+".onKeyValue('length',"+y.getName(t)+")"}),x.set(t,this,i,e),O.call(this,"length",i,n))},"can.offKeyValue":function(e,t,n){var i;return isNaN(e)?C.apply(this,arguments):(i=x.getAndDelete(t,this,e),C.call(this,"length",i,n))},"can.deleteKeyValue":function(e){if("number"==typeof(e=isNaN(+e)||e%1?e:+e))this.splice(e,1);else{if("length"===e||"_length"===e)return;this.set(e,void 0)}return this},"can.assignDeep":function(e){o.batch.start(),y.assignList(this,e),o.batch.stop()},"can.updateDeep":function(e){o.batch.start(),this.replace(e),o.batch.stop()},"can.keyHasDependencies":function(e){return!!(this._computed&&this._computed[e]&&this._computed[e].compute)},"can.getKeyDependencies":function(e){var t;return this._computed&&this._computed[e]&&this._computed[e].compute&&((t={}).valueDependencies=new w,t.valueDependencies.add(this._computed[e].compute)),t},"can.splice":function(e,t,n){this.splice.apply(this,[e,t].concat(n))},"can.onPatches":function(e,t){this[b.for("can.onKeyValue")]("can.onPatches",e,t)},"can.offPatches":function(e,t){this[b.for("can.offKeyValue")]("can.onPatches",e,t)},"can.getName":function(){return y.getName(this.constructor)+"[]"}}),y.setKeyValue(_.prototype,b.iterator,function(){var e=-1;return"number"!=typeof this._length&&(this._length=0),{next:function(){return e++,{value:this[e],done:e>=this._length}}.bind(this)}}),a.DefineList=_,n.exports=g.DefineList=_}),define("can-view-target",["require","exports","module","can-util/dom/child-nodes/child-nodes","can-util/dom/attr/attr","can-util/js/each/each","can-util/js/make-array/make-array","can-util/dom/document/document","can-util/dom/mutate/mutate","can-namespace","can-globals/mutation-observer/mutation-observer"],function(e,t,n){!function(e,t,n,i){function a(e,t,n,i){var a,r,o,s,c,u=n,d=typeof e,p=function(){return a||(a={path:n,callbacks:[]},t.push(a),u=[]),a};if("object"===d){if(e.tag){if(r=b&&e.namespace?i.createElementNS(e.namespace,e.tag):i.createElement(e.tag),e.attrs)for(var h in e.attrs){var v=e.attrs[h];"function"==typeof v?p().callbacks.push({callback:v}):l.setAttribute(r,h,v)}if(e.attributes)for(s=0,c=e.attributes.length;s<c;s++)p().callbacks.push({callback:e.attributes[s]});e.children&&e.children.length&&(o=a?a.paths=[]:t,r.appendChild(m(e.children,o,u,i)))}else if(e.comment&&(r=i.createComment(e.comment),e.callbacks))for(s=0,c=e.attributes.length;s<c;s++)p().callbacks.push({callback:e.callbacks[s]})}else"string"===d?r=i.createTextNode(e):"function"===d&&(g?(r=i.createTextNode(""),p().callbacks.push({callback:e})):(r=i.createComment("~"),p().callbacks.push({callback:function(){var t=i.createTextNode("");return f.replaceChild.call(this.parentNode,t,this),e.apply(t,arguments)}})));return r}function r(e,t,n){for(var i=t.path,a=t.callbacks,o=t.paths,s=e,c=i?i.length:0,l=o?o.length:0,u=0;u<c;u++)s=s.childNodes.item(i[u]);for(u=0;u<l;u++)r(s,o[u],n);n.push({element:s,callbacks:a})}function o(e,t){for(var n,i,a,r=e.length,o=0;o<r;o++){n=(a=e[o]).callbacks.length,i=a.element;for(var s=0;s<n;s++)a.callbacks[s].callback.apply(i,t)}}function s(e,t){var n=[],i=m(e,n,[],t||p());return{paths:n,clone:i,hydrate:function(){for(var e=w(this.clone),t=d(arguments),i=[],a=0;a<n.length;a++)r(e,n[a],i);return o(i,t),e}}}var c=t("can-util/dom/child-nodes/child-nodes"),l=t("can-util/dom/attr/attr"),u=t("can-util/js/each/each"),d=t("can-util/js/make-array/make-array"),p=t("can-util/dom/document/document"),f=t("can-util/dom/mutate/mutate"),h=t("can-namespace"),v=t("can-globals/mutation-observer/mutation-observer"),m=function(e,t,n,i){for(var r=i.createDocumentFragment(),o=0,s=e.length;o<s;o++){var c=e[o];r.appendChild(a(c,t,n.concat(o),i))}return r},g="undefined"!=typeof document&&function(){var e=document.createDocumentFragment(),t=document.createElement("div");t.appendChild(document.createTextNode("")),t.appendChild(document.createTextNode("")),e.appendChild(t);var n=e.cloneNode(!0);return 2===c(n.firstChild).length}(),y="undefined"!=typeof document&&function(){var e=document.createElement("a");e.innerHTML="<xyz></xyz>";var t,n,i=e.cloneNode(!0),a="<xyz></xyz>"===i.innerHTML;return a?((e=document.createDocumentFragment()).appendChild(document.createTextNode("foo-bar")),(t=v())?((n=new t(function(){})).observe(document.documentElement,{childList:!0,subtree:!0}),i=e.cloneNode(!0),n.disconnect()):i=e.cloneNode(!0),1===i.childNodes.length):a}(),b="undefined"!=typeof document&&!!document.createElementNS,w=y?function(e){return e.cloneNode(!0)}:function(e){var t,n=e.ownerDocument;if(1===e.nodeType?t="http://www.w3.org/1999/xhtml"!==e.namespaceURI&&b&&n.createElementNS?n.createElementNS(e.namespaceURI,e.nodeName):n.createElement(e.nodeName):3===e.nodeType?t=n.createTextNode(e.nodeValue):8===e.nodeType?t=n.createComment(e.nodeValue):11===e.nodeType&&(t=n.createDocumentFragment()),e.attributes){var i=d(e.attributes);u(i,function(e){e&&e.specified&&l.setAttribute(t,e.nodeName||e.name,e.nodeValue||e.value)})}if(e&&e.firstChild)for(var a=e.firstChild;a;)t.appendChild(w(a)),a=a.nextSibling;return t};s.keepsTextNodes=g,s.cloneNode=w,h.view=h.view||{},i.exports=h.view.target=s}(0,e,0,n)}),define("can-stache/src/mustache_core",["require","exports","module","can-view-live","can-view-nodelist","can-observation","can-stache/src/utils","can-stache/src/expression","can-util/dom/frag/frag","can-util/dom/attr/attr","can-symbol","can-reflect"],function(e,t,n){var i=e("can-view-live"),a=e("can-view-nodelist"),r=e("can-observation"),o=e("can-stache/src/utils"),s=e("can-stache/src/expression"),c=e("can-util/dom/frag/frag"),l=e("can-util/dom/attr/attr"),u=e("can-symbol"),d=e("can-reflect"),p=/(?:(^|\r?\n)(\s*)(\{\{([\s\S]*)\}\}\}?)([^\S\n\r]*)($|\r?\n))|(\{\{([\s\S]*)\}\}\}?)/g,f=/(\s*)(\{\{\{?)(-?)([\s\S]*?)(-?)(\}\}\}?)(\s*)/g,h=function(){},v={expression:s,makeEvaluator:function(e,t,n,i,a,r,l,u){if("^"===i){var p=r;r=l,l=p}var f,h;if(a instanceof s.Call){if(h={context:e.peek("."),scope:e,nodeList:n,exprData:a,helpersScope:t},o.convertToScopes(h,e,t,n,r,l,u),f=a.value(e,t,h),a.isHelper)return f}else if(a instanceof s.Bracket){if(f=a.value(e),a.isHelper)return f}else if(a instanceof s.Lookup){if(f=a.value(e),a.isHelper)return f}else if(a instanceof s.Helper&&a.methodExpr instanceof s.Bracket){if(f=a.methodExpr.value(e),a.isHelper)return f}else{var v={isArgument:!0,args:[e.peek("."),e],asCompute:!0},m=a.helperAndValue(e,t,v,n,r,l,u),g=m.helper;if(f=m.value,g)return a.evaluator(g,e,t,v,n,r,l,u)}return i?"#"===i||"^"===i?(h={},o.convertToScopes(h,e,t,n,r,l,u),function(){var n=d.getValue(f);if("function"==typeof n)return n;if("string"!=typeof n&&o.isArrayLike(n)){var i=d.isObservableLike(n)&&d.isListLike(n);return(i?n.attr("length"):n.length)?u?o.getItemsStringContent(n,i,h,t):c(o.getItemsFragContent(n,h,e)):h.inverse(e,t)}return n?h.fn(n||e,t):h.inverse(e,t)}):void 0:f},makeLiveBindingPartialRenderer:function(e,t){var n,o=(e=e.trim()).split(/\s+/).shift();return o!==e&&(n=v.expression.parse(e)),function(e,s,l){var u=[this];u.expression=">"+o,a.register(u,null,l||!0,t.directlyNested);var p=new r(function(){var t=o;if(n&&1===n.argExprs.length){var i=d.getValue(n.argExprs[0].value(e,s));void 0===i?dev.warn("The context ("+n.argExprs[0].key+") you passed into thepartial ("+o+") is not defined in the scope!"):e=e.add(i)}var a,l=s.peek("partials."+t);if(l=l||s.inlinePartials&&s.inlinePartials[t])a=function(){return l.render?l.render(e,s,u):l(e,s)};else{var p=e.read(t,{isArgument:!0}).value;if(null===p||!p&&"*"===t[0])return c("");p&&(t=p),a=function(){return"function"==typeof t?t(e,s,u):v.getTemplateById(t)(e,s,u)}}var f=r.ignore(a)();return c(f)});d.setPriority(p,u.nesting),i.html(this,p,this.parentNode,u)}},makeStringBranchRenderer:function(e,t){var n=v.expression.parse(t),i=e+t;n instanceof s.Helper||n instanceof s.Call||(n=new s.Helper(n,[],{}));var a=function(t,a,r,o){var s=t.__cache[i];!e&&s||(s=m(t,a,null,e,n,r,o,!0),e||(t.__cache[i]=s));var c;return null==(c=s[u.for("can.onValue")]?d.getValue(s):s())?"":""+c};return a.exprData=n,a},makeLiveBindingBranchRenderer:function(e,t,n){var o=v.expression.parse(t);o instanceof s.Helper||o instanceof s.Call||o instanceof s.Bracket||o instanceof s.Lookup||(o=new s.Helper(o,[],{}));var p=function(s,p,f,v,g){var y=[this];y.expression=t,a.register(y,null,f||!0,n.directlyNested);var b,w=m(s,p,y,e,o,v,g,n.tag);if(w[u.for("can.onValue")]?b=w:(Object.defineProperty(w,"name",{value:"{{"+t+"}}"}),b=new r(w,null,{isObservable:!1})),!1===d.setPriority(b,y.nesting))throw new Error("can-stache unable to set priority on observable");d.onValue(b,h);var k=d.getValue(b);"function"==typeof k?r.ignore(k)(this):d.valueHasDependencies(b)?n.attr?i.attr(this,n.attr,b):n.tag?i.attrs(this,b):n.text&&"object"!=typeof k?i.text(this,b,this.parentNode,y):i.html(this,b,this.parentNode,y):n.attr?l.set(this,n.attr,k):n.tag?i.attrs(this,k):n.text&&"string"==typeof k?this.nodeValue=k:null!=k&&a.replace([this],c(k,this.ownerDocument)),d.offValue(b,h)};return p.exprData=o,p},splitModeFromExpression:function(e,t){var n=(e=e.trim()).charAt(0);return"#/{&^>!<".indexOf(n)>=0?e=e.substr(1).trim():n=null,"{"===n&&t.node&&(n=null),{mode:n,expression:e}},cleanLineEndings:function(e){return e.replace(p,function(e,t,n,i,a,r,o,s,c,l){r=r||"",t=t||"",n=n||"";var u=g(a||c,{});return s||">{".indexOf(u.mode)>=0?e:"^#!/".indexOf(u.mode)>=0?(n=t+n&&" ")+i+(0!==l&&o.length?t+"\n":""):n+i+r+(n.length||0!==l?t+"\n":"")})},cleanWhitespaceControl:function(e){return e.replace(f,function(e,t,n,i,a,r,o,s,c){return"-"===i&&(t=""),"-"===r&&(s=""),t+n+a+o+s})},Options:o.Options,getTemplateById:function(){}},m=v.makeEvaluator,g=v.splitModeFromExpression;n.exports=v}),define("can-stache/src/html_section",["require","exports","module","can-view-target","can-view-scope","can-observation","can-stache/src/utils","can-stache/src/mustache_core","can-util/dom/document/document","can-util/js/assign/assign","can-util/js/last/last"],function(e,t,n){var i=e("can-view-target"),a=e("can-view-scope"),r=e("can-observation"),o=e("can-stache/src/utils"),s=e("can-stache/src/mustache_core"),c=e("can-util/dom/document/document"),l=e("can-util/js/assign/assign"),u=e("can-util/js/last/last"),d="undefined"!=typeof document&&function(){var e=c().createElement("div");return function(t){return-1===t.indexOf("&")?t.replace(/\r\n/g,"\n"):(e.innerHTML=t,0===e.childNodes.length?"":e.childNodes.item(0).nodeValue)}}(),p=function(){this.stack=[new f]};p.scopify=function(e){return r.ignore(function(t,n,i){return t instanceof a||(t=a.refsScope().add(t||{})),n instanceof s.Options||(n=new s.Options(n||{})),e(t,n,i)})},l(p.prototype,o.mixins),l(p.prototype,{startSubSection:function(e){var t=new f(e);return this.stack.push(t),t},endSubSectionAndReturnRenderer:function(){if(this.last().isEmpty())return this.stack.pop(),null;var e=this.endSection();return e.compiled.hydrate.bind(e.compiled)},startSection:function(e){var t=new f(e);this.last().add(t.targetCallback),this.stack.push(t)},endSection:function(){return this.last().compile(),this.stack.pop()},inverse:function(){this.last().inverse()},compile:function(){var e=this.stack.pop().compile();return r.ignore(function(t,n,i){return t instanceof a||(t=a.refsScope().add(t||{})),n instanceof s.Options||(n=new s.Options(n||{})),e.hydrate(t,n,i)})},push:function(e){this.last().push(e)},pop:function(){return this.last().pop()},removeCurrentNode:function(){this.last().removeCurrentNode()}});var f=function(e){this.data="targetData",this.targetData=[],this.targetStack=[];var t=this;this.targetCallback=function(n,i,a){e.call(this,n,i,a,t.compiled.hydrate.bind(t.compiled),t.inverseCompiled&&t.inverseCompiled.hydrate.bind(t.inverseCompiled))}};l(f.prototype,{inverse:function(){this.inverseData=[],this.data="inverseData"},push:function(e){this.add(e),this.targetStack.push(e)},pop:function(){return this.targetStack.pop()},add:function(e){"string"==typeof e&&(e=d(e)),this.targetStack.length?u(this.targetStack).children.push(e):this[this.data].push(e)},compile:function(){return this.compiled=i(this.targetData,c()),this.inverseData&&(this.inverseCompiled=i(this.inverseData,c()),delete this.inverseData),this.targetStack=this.targetData=null,this.compiled},removeCurrentNode:function(){return this.children().pop()},children:function(){return this.targetStack.length?u(this.targetStack).children:this[this.data]},isEmpty:function(){return!this.targetData.length}}),p.HTMLSection=f,n.exports=p}),define("can-stache/src/text_section",["require","exports","module","can-view-live","can-stache/src/utils","can-util/dom/attr/attr","can-util/js/assign/assign","can-reflect","can-observation"],function(e,t,n){var i=e("can-view-live"),a=e("can-stache/src/utils"),r=e("can-util/dom/attr/attr"),o=e("can-util/js/assign/assign"),s=e("can-reflect"),c=e("can-observation"),l=function(){},u=function(){this.stack=[new p]};o(u.prototype,a.mixins),o(u.prototype,{startSection:function(e){var t=new p;this.last().add({process:e,truthy:t}),this.stack.push(t)},endSection:function(){this.stack.pop()},inverse:function(){this.stack.pop();var e=new p;this.last().last().falsey=e,this.stack.push(e)},compile:function(e){var t=this.stack[0].compile();return Object.defineProperty(t,"name",{value:"textSectionRenderer<"+e.tag+"."+e.attr+">"}),function(n,a){function o(){return t(n,a)}Object.defineProperty(o,"name",{value:"textSectionRender<"+e.tag+"."+e.attr+">"});var u=new c(o,null,{isObservable:!1});s.onValue(u,l);var d=s.getValue(u);s.valueHasDependencies(u)?(e.textContentOnly?i.text(this,u):e.attr?i.attr(this,e.attr,u):i.attrs(this,u,n,a),s.offValue(u,l)):e.textContentOnly?this.nodeValue=d:e.attr?r.set(this,e.attr,d):i.attrs(this,d)}}});var d=function(e,t,n){return function(i,a){return e.call(this,i,a,t,n)}},p=function(){this.values=[]};o(p.prototype,{add:function(e){this.values.push(e)},last:function(){return this.values[this.values.length-1]},compile:function(){for(var e=this.values,t=e.length,n=0;n<t;n++){var i=this.values[n];"object"==typeof i&&(e[n]=d(i.process,i.truthy&&i.truthy.compile(),i.falsey&&i.falsey.compile()))}return function(n,i){for(var a,r="",o=0;o<t;o++)r+="string"==typeof(a=e[o])?a:a.call(this,n,i);return r}}}),n.exports=u}),define("can-stache/helpers/converter",["require","exports","module","can-stache/helpers/core","can-stache/src/expression","can-util/js/make-array/make-array"],function(e,t,n){var i=e("can-stache/helpers/core"),a=e("can-stache/src/expression"),r=e("can-util/js/make-array/make-array");i.registerConverter=function(e,t){t=t||{},i.registerHelper(e,function(e,n){var i=r(arguments);return e instanceof a.SetIdentifier?"function"==typeof t.set?t.set.apply(this,[e.value].concat(i.slice(1))):n(e.value):"function"==typeof t.get?t.get.apply(this,i):i[0]})},n.exports=i}),define("can-stache/src/intermediate_and_imports",["require","exports","module","can-stache/src/mustache_core","can-view-parser"],function(e,t,n){var i=e("can-stache/src/mustache_core"),a=e("can-view-parser");n.exports=function(e){function t(){f&&(s[f]=h,f=""),p?o.push(h):r.push(h)}var n=e;n=i.cleanWhitespaceControl(n),n=i.cleanLineEndings(n);var r=[],o=[],s={},c=!1,l=!1,u=!1,d=!1,p=!1,f="",h="";return{intermediate:a(n,{start:function(e,t){"can-import"===e?(d=t,p=!1,c=!0):"can-dynamic-import"===e?(d=t,p=!0,c=!0):c&&(p=!0,c=!1)},attrStart:function(e){"from"===e?l=!0:"as"!==e&&"export-as"!==e||(u=!0)},attrEnd:function(e){"from"===e?l=!1:"as"!==e&&"export-as"!==e||(u=!1)},attrValue:function(e){l&&c?h=e:u&&c&&(f=e)},end:function(e){"can-import"!==e&&"can-dymamic-import"!==e||!d||t()},close:function(e){"can-import"!==e&&"can-dymamic-import"!==e||t()},chars:function(e){e.trim().length>0&&(p=!0)},special:function(e){p=!0}},!0),imports:r,dynamicImports:o,ases:s,exports:s}}}),define("can-util/js/import/import",["require","exports","module","can-util/js/is-function/is-function","can-globals/global/global"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-util/js/is-function/is-function"),e=t("can-globals/global/global")();i.exports=function(t,n){return new Promise(function(i,r){try{"object"==typeof e.System&&a(e.System.import)?e.System.import(t,{name:n}).then(i,r):e.define&&e.define.amd?e.require([t],function(e){i(e)}):e.require?i(e.require(t)):i()}catch(e){r(e)}})}}(function(){return this}(),e,0,n)}),define("can-stache",["require","exports","module","can-view-parser","can-view-callbacks","can-stache/src/html_section","can-stache/src/text_section","can-stache/src/mustache_core","can-stache/helpers/core","can-stache/helpers/converter","can-stache/src/intermediate_and_imports","can-stache/src/utils","can-attribute-encoder","can-util/js/dev/dev","can-namespace","can-util/dom/document/document","can-util/js/assign/assign","can-util/js/last/last","can-util/js/import/import","can-view-target","can-view-nodelist"],function(e,t,n){function i(e){var t={};"string"==typeof e&&(e=c.cleanWhitespaceControl(e),e=c.cleanLineEndings(e));var n=new o,i={node:null,attr:null,sectionElementStack:[],text:!1,namespaceStack:[],textContentOnly:null},l=function(e,n,a){if(">"===n)e.add(c.makeLiveBindingPartialRenderer(a,u()));else if("/"===n){if("<"===e.last().startedWith?(t[a]=e.endSubSectionAndReturnRenderer(),e.removeCurrentNode()):e.endSection(),e instanceof o){var r=i.sectionElementStack[i.sectionElementStack.length-1].tag;""!==a&&a!==r&&f.warn("unexpected closing tag {{/"+a+"}} expected {{/"+r+"}}"),i.sectionElementStack.pop()}}else if("else"===n)e.inverse();else{var s=e instanceof o?c.makeLiveBindingBranchRenderer:c.makeStringBranchRenderer;if("{"===n||"&"===n)e.add(s(null,a,u()));else if("#"===n||"^"===n||"<"===n){var l=s(n,a,u());if(e.startSection(l),e.last().startedWith=n,e instanceof o){var d="function"==typeof l.exprData.closingTag?l.exprData.closingTag():"";i.sectionElementStack.push({type:"section",tag:d})}}else e.add(s(null,a,u({text:!0})))}},u=function(e){var t=i.sectionElementStack[i.sectionElementStack.length-1],n={tag:i.node&&i.node.tag,attr:i.attr&&i.attr.name,directlyNested:!i.sectionElementStack.length||("section"===t.type||"custom"===t.type),textContentOnly:!!i.textContentOnly};return e?m(n,e):n},h=function(e,t){e.attributes||(e.attributes=[]),e.attributes.unshift(t)};a(e,{start:function(e,t){var n=k[e];n&&!t&&i.namespaceStack.push(n),i.node={tag:e,children:[],namespace:n||g(i.namespaceStack)}},end:function(e,t){var a=r.tag(e);t?(n.add(i.node),a&&h(i.node,function(t,n,i){r.tagHandler(this,e,{scope:t,options:n,subtemplate:null,templateType:"stache",parentNodeList:i})})):(n.push(i.node),i.sectionElementStack.push({type:a?"custom":null,tag:a?null:e,templates:{}}),a?n.startSubSection():x[e]&&(i.textContentOnly=new s)),i.node=null},close:function(e){k[e]&&i.namespaceStack.pop();var t,a=r.tag(e);a&&(t=n.endSubSectionAndReturnRenderer()),x[e]&&(n.last().add(i.textContentOnly.compile(u())),i.textContentOnly=null);var o=n.pop();if(a)if("can-template"===e)i.sectionElementStack[i.sectionElementStack.length-2].templates[o.attrs.name]=d(t),n.removeCurrentNode();else{var s=i.sectionElementStack[i.sectionElementStack.length-1];h(o,function(n,i,a){r.tagHandler(this,e,{scope:n,options:i,subtemplate:t?d(t):t,templateType:"stache",parentNodeList:a,templates:s.templates})})}i.sectionElementStack.pop()},attrStart:function(e){i.node.section?i.node.section.add(e+'="'):i.attr={name:e,value:""}},attrEnd:function(e){if(i.node.section)i.node.section.add('" ');else{i.node.attrs||(i.node.attrs={}),i.node.attrs[i.attr.name]=i.attr.section?i.attr.section.compile(u()):i.attr.value;var t=r.attr(e),n=p.decode(e);weirdAttribute=!!b.test(n)||!!w.test(n),weirdAttribute&&!t&&f.warn("unknown attribute binding "+n+". Is can-stache-bindings imported?"),t&&(i.node.attributes||(i.node.attributes=[]),i.node.attributes.push(function(n,i,a){t(this,{attributeName:e,scope:n,options:i,nodeList:a})})),i.attr=null}},attrValue:function(e){var t=i.node.section||i.attr.section;t?t.add(e):i.attr.value+=e},chars:function(e){(i.textContentOnly||n).add(e)},special:function(e){var t=c.splitModeFromExpression(e,i),a=t.mode,r=t.expression;if("else"!==r){if("!"!==a)if(i.node&&i.node.section)l(i.node.section,a,r),0===i.node.section.subSectionDepth()&&(i.node.attributes.push(i.node.section.compile(u())),delete i.node.section);else if(i.attr)i.attr.section||(i.attr.section=new s,i.attr.value&&i.attr.section.add(i.attr.value)),l(i.attr.section,a,r);else if(i.node)if(i.node.attributes||(i.node.attributes=[]),a){if("#"!==a&&"^"!==a)throw new Error(a+" is currently not supported within a tag.");i.node.section||(i.node.section=new s),l(i.node.section,a,r)}else i.node.attributes.push(c.makeLiveBindingBranchRenderer(null,r,u()));else l(i.textContentOnly||n,a,r)}else{(i.attr&&i.attr.section?i.attr.section:i.node&&i.node.section?i.node.section:i.textContentOnly||n).inverse()}},comment:function(e){n.add({comment:e})},done:function(){}});var v=n.compile(),y=o.scopify(function(e,n,i){return Object.keys(t).length&&(n.inlinePartials=n.inlinePartials||{},m(n.inlinePartials,t)),e.set("*self",y),v.apply(this,arguments)});return y}var a=e("can-view-parser"),r=e("can-view-callbacks"),o=e("can-stache/src/html_section"),s=e("can-stache/src/text_section"),c=e("can-stache/src/mustache_core"),l=e("can-stache/helpers/core");e("can-stache/helpers/converter");var u=e("can-stache/src/intermediate_and_imports"),d=e("can-stache/src/utils").makeRendererConvertScopes,p=e("can-attribute-encoder"),f=e("can-util/js/dev/dev"),h=e("can-namespace"),v=e("can-util/dom/document/document"),m=e("can-util/js/assign/assign"),g=e("can-util/js/last/last"),y=e("can-util/js/import/import");e("can-view-target"),e("can-view-nodelist"),r.tag("content",function(e,t){return t.scope});var b=/[{(].*[)}]/,w=/^on:|(:to|:from|:bind)$|.*:to:on:.*/,k={svg:"http://www.w3.org/2000/svg",g:"http://www.w3.org/2000/svg"},x={style:!0,script:!0};m(i,l),i.safeString=function(e){return{toString:function(){return e}}},i.async=function(e){var t=u(e),n=t.imports.map(function(e){return y(e)});return Promise.all(n).then(function(){return i(t.intermediate)})};var j={};i.from=c.getTemplateById=function(e){if(!j[e]){var t=v().getElementById(e);j[e]=i(t.innerHTML)}return j[e]},i.registerPartial=function(e,t){j[e]="string"==typeof t?i(t):t},n.exports=h.stache=i}),define("can-debug",["require","exports","module","can-namespace","can-symbol","can-reflect"],function(e,t,n){function i(e,t){var n=2===arguments.length,o={obj:e,key:t,keyDependencies:{},valueDependencies:[],name:c.getName(e),value:n?c.getKeyValue(e,t):c.getValue(e)},s=n?a(e,t):r(e);return s?(s.keyDependencies&&c.each(s.keyDependencies,function(e,t){c.each(e,function(e){o.keyDependencies[e]=i(t,e)})}),s.valueDependencies&&c.each(s.valueDependencies,function(e){o.valueDependencies.push(i(e))}),o):o}function a(e,t){if(e[l])return c.getKeyDependencies(e,t)}function r(e){if(e[u])return c.getValueDependencies(e)}var o=e("can-namespace"),s=e("can-symbol"),c=e("can-reflect"),l=s.for("can.getKeyDependencies"),u=s.for("can.getValueDependencies");i.logWhatChangesMe=function(e,t){var n=function(e){return"string"==typeof e?JSON.stringify(e):e},a=function e(t){var i=[t.name,null!=t.key?"."+t.key:""];console.group(i.join("")),console.log("value ",n(t.value)),console.log("object ",t.obj),c.each(t.keyDependencies,e),c.each(t.valueDependencies,e),console.groupEnd()};return a(2===arguments.length?i(e,t):i(e))},n.exports=o.debug=i}),define("can",["require","exports","module","can-util/namespace","can-component","can-define/map/map","can-define/list/list","can-stache","can-stache-bindings","can-debug"],function(e,t,n){!function(e,t,n,i){var a=t("can-util/namespace");t("can-component"),t("can-define/map/map"),t("can-define/list/list"),t("can-stache"),t("can-stache-bindings"),t("can-debug"),i.exports=a}(0,e,0,n)}),define("can-util/js/omit/omit",function(e,t,n){"use strict";n.exports=function(e,t){var n={};for(var i in e)t.indexOf(i)<0&&(n[i]=e[i]);return n}}),define("can-param",["require","exports","module","can-namespace"],function(e,t,n){function i(e,t,n){if(Array.isArray(t))for(var a=0,r=t.length;a<r;++a)n(e+"[]",t[a]);else if(t&&"object"==typeof t)for(var o in t)i(e+"["+o+"]",t[o],n);else n(e,t)}var a=e("can-namespace");n.exports=a.param=function(e){var t=[];for(var n in e)i(n,e[n],function(e,n){t.push(encodeURIComponent(e)+"="+encodeURIComponent(n))});return t.join("&").replace(/%20/g,"+")}}),define("can-ajax",["require","exports","module","can-globals/global/global","can-assign","can-namespace","can-parse-uri","can-param"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-globals/global/global"),r=t("can-assign"),o=t("can-namespace"),s=t("can-parse-uri"),c=t("can-param"),l=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Microsoft.XMLHTTP")},function(){return new ActiveXObject("MSXML2.XMLHTTP.3.0")},function(){return new ActiveXObject("MSXML2.XMLHTTP")}],u=null,d=s(a().location.href),p=function(){if(null!=u)return u();for(var e=0,t=l.length;e<t;e++)try{var n=l[e],i=n();if(null!=i)return u=n,i}catch(e){continue}return function(){}},f={json:"application/json",form:"application/x-www-form-urlencoded"},h=function(e,t){switch(t.dataType||e.getResponseHeader("Content-Type").split(";")[0]){case"text/xml":case"xml":return e.responseXML;case"text/json":case"application/json":case"text/javascript":case"application/javascript":case"application/x-javascript":case"json":return JSON.parse(e.responseText);default:return e.responseText}};i.exports=o.ajax=function(e){var t,n,i=p(),a=0,o={},l=new Promise(function(e,t){o.resolve=e,o.reject=t});if(l.abort=function(){i.abort()},(e=r({userAgent:"XMLHttpRequest",lang:"en",type:"GET",data:null,dataType:"json"},e)).contentType||(e.contentType="GET"===e.type.toUpperCase()?f.form:f.json),null==e.crossDomain)try{n=s(e.url),e.crossDomain=!!(n.protocol&&n.protocol!==d.protocol||n.host&&n.host!==d.host)}catch(t){e.crossDomain=!0}e.timeout&&(t=setTimeout(function(){i.abort(),e.timeoutFn&&e.timeoutFn(e.url)},e.timeout)),i.onreadystatechange=function(){try{4===i.readyState?(t&&clearTimeout(t),i.status<300?e.success&&e.success(h(i,e)):e.error&&e.error(i,i.status,i.statusText),e.complete&&e.complete(i,i.statusText),i.status>=200&&i.status<300?o.resolve(h(i,e)):o.reject(i)):e.progress&&e.progress(++a)}catch(e){o.reject(e)}};var u=e.url,v=null,m=e.type.toUpperCase(),g=e.contentType===f.json,y="POST"===m||"PUT"===m;!y&&e.data&&(u+="?"+(g?JSON.stringify(e.data):c(e.data))),i.open(m,u);var b=e.crossDomain&&-1!==["GET","POST","HEAD"].indexOf(m);if(y){v=g&&!b?"object"==typeof e.data?JSON.stringify(e.data):e.data:c(e.data);var w=g&&!b?"application/json":"application/x-www-form-urlencoded";i.setRequestHeader("Content-Type",w)}else i.setRequestHeader("Content-Type",e.contentType);return b||i.setRequestHeader("X-Requested-With","XMLHttpRequest"),i.send(v),l}}(0,e,0,n)}),define("can-util/dom/ajax/ajax",["require","exports","module","can-log/dev/dev","can-ajax"],function(e,t,n){"use strict";e("can-log/dev/dev").warn("js/ajax/ajax is deprecated; please use can-ajax instead: https://github.com/canjs/can-ajax"),n.exports=e("can-ajax")}),define("can-globals/location/location",["require","exports","module","can-globals/global/global","can-globals/can-globals-instance"],function(e,t,n){!function(e,t,n,i){"use strict";t("can-globals/global/global");var a=t("can-globals/can-globals-instance");a.define("location",function(){return a.getKeyValue("global").location}),i.exports=a.makeExport("location")}(0,e,0,n)}),define("can-globals",["require","exports","module","can-globals/can-globals-instance","can-globals/global/global","can-globals/document/document","can-globals/location/location","can-globals/mutation-observer/mutation-observer","can-globals/is-browser-window/is-browser-window"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-globals/can-globals-instance");t("can-globals/global/global"),t("can-globals/document/document"),t("can-globals/location/location"),t("can-globals/mutation-observer/mutation-observer"),t("can-globals/is-browser-window/is-browser-window"),i.exports=a}(0,e,0,n)}),define("can-util/dom/mutation-observer/mutation-observer",["require","exports","module","can-globals"],function(e,t,n){!function(e,t,n,i){"use strict";var a=t("can-globals");i.exports=function(e){return void 0!==e&&a.setKeyValue("MutationObserver",function(){return e}),a.getKeyValue("MutationObserver")}}(0,e,0,n)}),define("can-util/dom/dom",["require","exports","module","can-util/dom/ajax/ajax","can-util/dom/attr/attr","can-util/dom/child-nodes/child-nodes","can-util/dom/class-name/class-name","can-util/dom/contains/contains","can-util/dom/data/data","can-util/dom/dispatch/dispatch","can-util/dom/document/document","can-util/dom/events/events","can-util/dom/frag/frag","can-util/dom/fragment/fragment","can-util/dom/is-of-global-document/is-of-global-document","can-util/dom/matches/matches","can-util/dom/mutate/mutate","can-util/dom/mutation-observer/mutation-observer"],function(e,t,n){!function(e,t,n,i){"use strict";i.exports={ajax:t("can-util/dom/ajax/ajax"),attr:t("can-util/dom/attr/attr"),childNodes:t("can-util/dom/child-nodes/child-nodes"),className:t("can-util/dom/class-name/class-name"),contains:t("can-util/dom/contains/contains"),data:t("can-util/dom/data/data"),dispatch:t("can-util/dom/dispatch/dispatch"),document:t("can-util/dom/document/document"),events:t("can-util/dom/events/events"),frag:t("can-util/dom/frag/frag"),fragment:t("can-util/dom/fragment/fragment"),isOfGlobalDocument:t("can-util/dom/is-of-global-document/is-of-global-document"),matches:t("can-util/dom/matches/matches"),mutate:t("can-util/dom/mutate/mutate"),mutationObserver:t("can-util/dom/mutation-observer/mutation-observer")}}(0,e,0,n)}),define("can-util/js/is-browser-window/is-browser-window",["require","exports","module","can-globals/is-browser-window/is-browser-window"],function(e,t,n){!function(e,t,n,i){"use strict";i.exports=t("can-globals/is-browser-window/is-browser-window")}(0,e,0,n)}),define("can-util/js/is-node/is-node",function(e,t,n){!function(e,t,n,i){"use strict";i.exports=function(){return"object"==typeof process&&"[object process]"==={}.toString.call(process)}}(0,0,0,n)}),define("can-util/js/is-promise/is-promise",["require","exports","module","can-reflect"],function(e,t,n){"use strict";var i=e("can-reflect");n.exports=function(e){return i.isPromise(e)}}),define("can-util/js/is-string/is-string",["require","exports","module","can-log/dev/dev"],function(e,t,n){"use strict";var i=e("can-log/dev/dev"),a=!1;n.exports=function(e){return a||(i.warn('js/is-string/is-string is deprecated; use typeof x === "string"'),a=!0),"string"==typeof e}}),define("can-util/js/is-web-worker/is-web-worker",function(e,t,n){!function(e,t,n,i){"use strict";i.exports=function(){return"undefined"!=typeof WorkerGlobalScope&&this instanceof WorkerGlobalScope}}(0,0,0,n)}),define("can-util/js/js",["require","exports","module","can-assign","can-cid","can-util/js/deep-assign/deep-assign","can-util/js/dev/dev","can-util/js/diff/diff","can-util/js/each/each","can-util/js/global/global","can-util/js/import/import","can-util/js/is-array/is-array","can-util/js/is-array-like/is-array-like","can-util/js/is-browser-window/is-browser-window","can-util/js/is-empty-object/is-empty-object","can-util/js/is-function/is-function","can-util/js/is-node/is-node","can-util/js/is-plain-object/is-plain-object","can-util/js/is-promise/is-promise","can-util/js/is-string/is-string","can-util/js/is-web-worker/is-web-worker","can-util/js/join-uris/join-uris","can-util/js/last/last","can-util/js/make-array/make-array","can-util/js/omit/omit","can-util/js/set-immediate/set-immediate","can-util/js/string/string","can-types"],function(e,t,n){!function(e,t,n,i){"use strict";i.exports={assign:t("can-assign"),cid:t("can-cid"),deepAssign:t("can-util/js/deep-assign/deep-assign"),dev:t("can-util/js/dev/dev"),diff:t("can-util/js/diff/diff"),each:t("can-util/js/each/each"),global:t("can-util/js/global/global"),import:t("can-util/js/import/import"),isArray:t("can-util/js/is-array/is-array"),isArrayLike:t("can-util/js/is-array-like/is-array-like"),isBrowserWindow:t("can-util/js/is-browser-window/is-browser-window"),isEmptyObject:t("can-util/js/is-empty-object/is-empty-object"),isFunction:t("can-util/js/is-function/is-function"),isNode:t("can-util/js/is-node/is-node"),isPlainObject:t("can-util/js/is-plain-object/is-plain-object"),isPromise:t("can-util/js/is-promise/is-promise"),isString:t("can-util/js/is-string/is-string"),isWebWorker:t("can-util/js/is-web-worker/is-web-worker"),joinURIs:t("can-util/js/join-uris/join-uris"),last:t("can-util/js/last/last"),makeArray:t("can-util/js/make-array/make-array"),omit:t("can-util/js/omit/omit"),setImmediate:t("can-util/js/set-immediate/set-immediate"),string:t("can-util/js/string/string"),types:t("can-types")}}(0,e,0,n)}),define("can-util",["require","exports","module","can-util/js/deep-assign/deep-assign","can-util/js/omit/omit","can-namespace","can-util/dom/dom","can-util/js/js"],function(e,t,n){var i=e("can-util/js/deep-assign/deep-assign"),a=e("can-util/js/omit/omit"),r=e("can-namespace");n.exports=i(r,e("can-util/dom/dom"),a(e("can-util/js/js"),["cid","types"]))}),define("can-construct-super",["require","exports","module","can-util","can-construct"],function(e,t,n){!function(e,t,n,i){var a=t("can-util"),r=t("can-construct"),o=Object.prototype.hasOwnProperty,s=a.isFunction,c=/xyz/.test(function(){return this.xyz})?/\b_super\b/:/.*/,l=["get","set"],u=function(e,t,n){return function(){var i,a=!1,r=d(this),s=r._super;o.call(this,"_super")&&(a=!0,i=this._super,delete this._super),r._super=e[t];var c=n.apply(this,arguments);return r._super=s,a&&(this._super=i),c}};r._defineProperty=function(e,t,n,i){var r=Object.getOwnPropertyDescriptor(t,n);r&&a.each(l,function(e){s(r[e])&&s(i[e])?i[e]=u(r,e,i[e]):s(i[e])||(i[e]=r[e])}),Object.defineProperty(e,n,i)};var d=Object.getPrototypeOf||function(e){return e.__proto__},p=Object.getPropertyDescriptor||function(e,t){if(t in e){for(var n=Object.getOwnPropertyDescriptor(e,t),i=d(e);void 0===n&&null!==i;)n=Object.getOwnPropertyDescriptor(i,t),i=d(i);return n}};r._overwrite=function(e,t,n,i){var a=p(t,n),r=a&&a.value;Object.defineProperty(e,n,{value:s(i)&&s(r)&&c.test(i)?u(t,n,i):i,configurable:!0,enumerable:!0,writable:!0})},i.exports=r}(0,e,0,n)}),define("can/ecosystem",["require","exports","module","can-util/namespace","can-construct-super"],function(e,t,n){var i=e("can-util/namespace");e("can-construct-super"),n.exports=i}),define("can/legacy",["require","exports","module","can-util/namespace","can-view-model"],function(e,t,n){var i=e("can-util/namespace");e("can-view-model"),n.exports=i}),define("can/all",["require","exports","module","can-util/namespace","can","can/ecosystem","can/legacy"],function(e,t,n){var i=e("can-util/namespace");e("can"),e("can/ecosystem"),e("can/legacy"),n.exports=i}),function(e){e._define=e.define,e.define=e.define.orig}("object"==typeof self&&self.Object==Object?self:window); |
ajax/libs/react-router/0.9.0/react-router.min.js | ppoffice/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)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.ReactRouter=e()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&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}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module){var LocationActions={SETUP:"setup",PUSH:"push",REPLACE:"replace",POP:"pop"};module.exports=LocationActions},{}],2:[function(_dereq_,module){var LocationActions=_dereq_("../actions/LocationActions"),ImitateBrowserBehavior={updateScrollPosition:function(position,actionType){switch(actionType){case LocationActions.PUSH:case LocationActions.REPLACE:window.scrollTo(0,0);break;case LocationActions.POP:window.scrollTo(position.x,position.y)}}};module.exports=ImitateBrowserBehavior},{"../actions/LocationActions":1}],3:[function(_dereq_,module){var ScrollToTopBehavior={updateScrollPosition:function(){window.scrollTo(0,0)}};module.exports=ScrollToTopBehavior},{}],4:[function(_dereq_,module){function DefaultRoute(props){return Route(merge(props,{path:null,isDefault:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=DefaultRoute},{"./Route":8,"react/lib/merge":45}],5:[function(_dereq_,module){function isLeftClickEvent(event){return 0===event.button}function isModifiedEvent(event){return!!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,merge=_dereq_("react/lib/merge"),ActiveState=_dereq_("../mixins/ActiveState"),Navigation=_dereq_("../mixins/Navigation"),Link=React.createClass({displayName:"Link",mixins:[ActiveState,Navigation],propTypes:{activeClassName:React.PropTypes.string.isRequired,to:React.PropTypes.string.isRequired,params:React.PropTypes.object,query:React.PropTypes.object,onClick:React.PropTypes.func},getDefaultProps:function(){return{activeClassName:"active"}},handleClick:function(event){var clickResult,allowTransition=!0;this.props.onClick&&(clickResult=this.props.onClick(event)),!isModifiedEvent(event)&&isLeftClickEvent(event)&&((clickResult===!1||event.defaultPrevented===!0)&&(allowTransition=!1),event.preventDefault(),allowTransition&&this.transitionTo(this.props.to,this.props.params,this.props.query))},getHref:function(){return this.makeHref(this.props.to,this.props.params,this.props.query)},getClassName:function(){var className=this.props.className||"";return this.isActive(this.props.to,this.props.params,this.props.query)&&(className+=" "+this.props.activeClassName),className},render:function(){var props=merge(this.props,{href:this.getHref(),className:this.getClassName(),onClick:this.handleClick});return React.DOM.a(props,this.props.children)}});module.exports=Link},{"../mixins/ActiveState":16,"../mixins/Navigation":19,"react/lib/merge":45}],6:[function(_dereq_,module){function NotFoundRoute(props){return Route(merge(props,{path:null,catchAll:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=NotFoundRoute},{"./Route":8,"react/lib/merge":45}],7:[function(_dereq_,module){function createRedirectHandler(to){return React.createClass({statics:{willTransitionTo:function(transition,params,query){transition.redirect(to,params,query)}},render:function(){return null}})}function Redirect(props){return Route({name:props.name,path:props.from||props.path||"*",handler:createRedirectHandler(props.to)})}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Route=_dereq_("./Route");module.exports=Redirect},{"./Route":8}],8:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,withoutProperties=_dereq_("../utils/withoutProperties"),RESERVED_PROPS={handler:!0,path:!0,defaultRoute:!0,notFoundRoute:!0,paramNames:!0,children:!0},Route=React.createClass({displayName:"Route",statics:{getUnreservedProps:function(props){return withoutProperties(props,RESERVED_PROPS)}},propTypes:{handler:React.PropTypes.any.isRequired,path:React.PropTypes.string,name:React.PropTypes.string},render:function(){throw new Error("The <Route> component should not be rendered directly. You may be missing a <Routes> wrapper around your list of routes.")}});module.exports=Route},{"../utils/withoutProperties":30}],9:[function(_dereq_,module){function makeMatch(route,params){return{route:route,params:params}}function getRootMatch(matches){return matches[matches.length-1]}function findMatches(path,routes,defaultRoute,notFoundRoute){for(var route,params,matches=null,i=0,len=routes.length;len>i;++i){if(route=routes[i],matches=findMatches(path,route.props.children,route.props.defaultRoute,route.props.notFoundRoute),null!=matches){var rootParams=getRootMatch(matches).params;return params=route.props.paramNames.reduce(function(params,paramName){return params[paramName]=rootParams[paramName],params},{}),matches.unshift(makeMatch(route,params)),matches}if(params=Path.extractParams(route.props.path,path))return[makeMatch(route,params)]}return defaultRoute&&(params=Path.extractParams(defaultRoute.props.path,path))?[makeMatch(defaultRoute,params)]:notFoundRoute&&(params=Path.extractParams(notFoundRoute.props.path,path))?[makeMatch(notFoundRoute,params)]:matches}function hasMatch(matches,match){return matches.some(function(m){if(m.route!==match.route)return!1;for(var property in m.params)if(m.params[property]!==match.params[property])return!1;return!0})}function updateMatchComponents(matches,refs){for(var component,i=0;component=refs.__activeRoute__;)matches[i++].component=component,refs=component.refs}function computeNextState(component,transition,callback){if(component.state.path===transition.path)return callback();var currentMatches=component.state.matches,nextMatches=component.match(transition.path);warning(nextMatches,'No route matches path "'+transition.path+'". Make sure you have <Route path="'+transition.path+'"> somewhere in your routes'),nextMatches||(nextMatches=[]);var fromMatches,toMatches;currentMatches.length?(updateMatchComponents(currentMatches,component.refs),fromMatches=currentMatches.filter(function(match){return!hasMatch(nextMatches,match)}),toMatches=nextMatches.filter(function(match){return!hasMatch(currentMatches,match)})):(fromMatches=[],toMatches=nextMatches);var query=Path.extractQuery(transition.path)||{};runTransitionFromHooks(fromMatches,transition,function(error){return error||transition.isAborted?callback(error):void runTransitionToHooks(toMatches,transition,query,function(error){if(error||transition.isAborted)return callback(error);var matches=currentMatches.slice(0,currentMatches.length-fromMatches.length).concat(toMatches),rootMatch=getRootMatch(matches),params=rootMatch&&rootMatch.params||{},routes=matches.map(function(match){return match.route});callback(null,{path:transition.path,matches:matches,activeRoutes:routes,activeParams:params,activeQuery:query})})})}function runTransitionFromHooks(matches,transition,callback){var hooks=reversedArray(matches).map(function(match){return function(){var handler=match.route.props.handler;if(!transition.isAborted&&handler.willTransitionFrom)return handler.willTransitionFrom(transition,match.component);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runTransitionToHooks(matches,transition,query,callback){var hooks=matches.map(function(match){return function(){var handler=match.route.props.handler;!transition.isAborted&&handler.willTransitionTo&&handler.willTransitionTo(transition,match.params,query);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runHooks(hooks,callback){try{var promise=hooks.reduce(function(promise,hook){return promise?promise.then(hook):hook()},null)}catch(error){return callback(error)}promise?promise.then(function(){setTimeout(callback)},function(error){setTimeout(function(){callback(error)})}):callback()}function returnNull(){return null}function computeHandlerProps(matches,query){var handler=returnNull,props={ref:null,params:null,query:null,activeRouteHandler:handler,key:null};return reversedArray(matches).forEach(function(match){var route=match.route;props=Route.getUnreservedProps(route.props),props.ref="__activeRoute__",props.params=match.params,props.query=query,props.activeRouteHandler=handler,route.props.addHandlerKey&&(props.key=Path.injectParams(route.props.path,match.params)),handler=function(props,addedProps){if(arguments.length>2&&"undefined"!=typeof arguments[2])throw new Error("Passing children to a route handler is not supported");return route.props.handler(copyProperties(props,addedProps))}.bind(this,props)}),props}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,warning=_dereq_("react/lib/warning"),invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,copyProperties=_dereq_("react/lib/copyProperties"),PathStore=_dereq_("../stores/PathStore"),HashLocation=_dereq_("../locations/HashLocation"),reversedArray=_dereq_("../utils/reversedArray"),Transition=_dereq_("../utils/Transition"),Redirect=_dereq_("../utils/Redirect"),Path=_dereq_("../utils/Path"),Route=_dereq_("./Route"),BrowserTransitionHandling={handleTransitionError:function(component,error){throw error},handleAbortedTransition:function(component,transition){var reason=transition.abortReason;reason instanceof Redirect?component.replaceWith(reason.to,reason.params,reason.query):component.goBack()}},ServerTransitionHandling={handleTransitionError:function(){},handleAbortedTransition:function(){}},TransitionHandling=canUseDOM?BrowserTransitionHandling:ServerTransitionHandling,ActiveContext=_dereq_("../mixins/ActiveContext"),LocationContext=_dereq_("../mixins/LocationContext"),RouteContext=_dereq_("../mixins/RouteContext"),ScrollContext=_dereq_("../mixins/ScrollContext"),Routes=React.createClass({displayName:"Routes",mixins:[ActiveContext,LocationContext,RouteContext,ScrollContext],propTypes:{initialPath:React.PropTypes.string,onChange:React.PropTypes.func},getInitialState:function(){return{matches:[]}},componentWillMount:function(){this.handlePathChange(this.props.initialPath)},componentDidMount:function(){PathStore.addChangeListener(this.handlePathChange)},componentWillUnmount:function(){PathStore.removeChangeListener(this.handlePathChange)},handlePathChange:function(_path){var path=_path||PathStore.getCurrentPath(),actionType=PathStore.getCurrentActionType();if(this.state.path!==path){this.state.path&&this.recordScroll(this.state.path);var self=this;this.dispatch(path,function(error,transition){error?TransitionHandling.handleTransitionError(self,error):transition.isAborted?TransitionHandling.handleAbortedTransition(self,transition):(self.updateScroll(path,actionType),self.props.onChange&&self.props.onChange.call(self))})}},match:function(path){return findMatches(Path.withoutQuery(path),this.getRoutes(),this.props.defaultRoute,this.props.notFoundRoute)},dispatch:function(path,callback){var transition=new Transition(this,path),self=this;computeNextState(this,transition,function(error,nextState){return error||null==nextState?callback(error,transition):void self.setState(nextState,function(){callback(null,transition)})})},getHandlerProps:function(){return computeHandlerProps(this.state.matches,this.state.activeQuery)},getActiveComponent:function(){return this.refs.__activeRoute__},getCurrentPath:function(){return this.state.path},makePath:function(to,params,query){var path;if(Path.isAbsolute(to))path=Path.normalize(to);else{var namedRoutes=this.getNamedRoutes(),route=namedRoutes[to];invariant(route,'Unable to find a route named "'+to+'". Make sure you have a <Route name="'+to+'"> defined somewhere in your <Routes>'),path=route.props.path}return Path.withQuery(Path.injectParams(path,params),query)},makeHref:function(to,params,query){var path=this.makePath(to,params,query);return this.getLocation()===HashLocation?"#"+path:path},transitionTo:function(to,params,query){var location=this.getLocation();invariant(location,"You cannot use transitionTo without a location"),location.push(this.makePath(to,params,query))},replaceWith:function(to,params,query){var location=this.getLocation();invariant(location,"You cannot use replaceWith without a location"),location.replace(this.makePath(to,params,query))},goBack:function(){var location=this.getLocation();invariant(location,"You cannot use goBack without a location"),location.pop()},render:function(){var match=this.state.matches[0];return null==match?null:match.route.props.handler(this.getHandlerProps())},childContextTypes:{currentPath:React.PropTypes.string,makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},getChildContext:function(){return{currentPath:this.getCurrentPath(),makePath:this.makePath,makeHref:this.makeHref,transitionTo:this.transitionTo,replaceWith:this.replaceWith,goBack:this.goBack}}});module.exports=Routes},{"../locations/HashLocation":12,"../mixins/ActiveContext":15,"../mixins/LocationContext":18,"../mixins/RouteContext":20,"../mixins/ScrollContext":21,"../stores/PathStore":22,"../utils/Path":23,"../utils/Redirect":25,"../utils/Transition":26,"../utils/reversedArray":28,"./Route":8,"react/lib/ExecutionEnvironment":40,"react/lib/copyProperties":41,"react/lib/invariant":43,"react/lib/warning":49}],10:[function(_dereq_,module){var copyProperties=_dereq_("react/lib/copyProperties"),Dispatcher=_dereq_("flux").Dispatcher,LocationDispatcher=copyProperties(new Dispatcher,{handleViewAction:function(action){this.dispatch({source:"VIEW_ACTION",action:action})}});module.exports=LocationDispatcher},{flux:32,"react/lib/copyProperties":41}],11:[function(_dereq_,module,exports){exports.DefaultRoute=_dereq_("./components/DefaultRoute"),exports.Link=_dereq_("./components/Link"),exports.NotFoundRoute=_dereq_("./components/NotFoundRoute"),exports.Redirect=_dereq_("./components/Redirect"),exports.Route=_dereq_("./components/Route"),exports.Routes=_dereq_("./components/Routes"),exports.ActiveState=_dereq_("./mixins/ActiveState"),exports.CurrentPath=_dereq_("./mixins/CurrentPath"),exports.Navigation=_dereq_("./mixins/Navigation")},{"./components/DefaultRoute":4,"./components/Link":5,"./components/NotFoundRoute":6,"./components/Redirect":7,"./components/Route":8,"./components/Routes":9,"./mixins/ActiveState":16,"./mixins/CurrentPath":17,"./mixins/Navigation":19}],12:[function(_dereq_,module){function getHashPath(){return window.location.hash.substr(1)}function ensureSlash(){var path=getHashPath();return"/"===path.charAt(0)?!0:(HashLocation.replace("/"+path),!1)}function onHashChange(){if(ensureSlash()){{getHashPath()}LocationDispatcher.handleViewAction({type:_actionType||LocationActions.POP,path:getHashPath()}),_actionType=null}}var _actionType,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,LocationActions=_dereq_("../actions/LocationActions"),LocationDispatcher=_dereq_("../dispatchers/LocationDispatcher"),getWindowPath=_dereq_("../utils/getWindowPath"),_isSetup=!1,HashLocation={setup:function(){_isSetup||(invariant(canUseDOM,"You cannot use HashLocation in an environment with no DOM"),ensureSlash(),LocationDispatcher.handleViewAction({type:LocationActions.SETUP,path:getHashPath()}),window.addEventListener?window.addEventListener("hashchange",onHashChange,!1):window.attachEvent("onhashchange",onHashChange),_isSetup=!0)},teardown:function(){window.removeEventListener?window.removeEventListener("hashchange",onHashChange,!1):window.detachEvent("onhashchange",onHashChange),_isSetup=!1},push:function(path){_actionType=LocationActions.PUSH,window.location.hash=path},replace:function(path){_actionType=LocationActions.REPLACE,window.location.replace(getWindowPath()+"#"+path)},pop:function(){_actionType=LocationActions.POP,window.history.back()},toString:function(){return"<HashLocation>"}};module.exports=HashLocation},{"../actions/LocationActions":1,"../dispatchers/LocationDispatcher":10,"../utils/getWindowPath":27,"react/lib/ExecutionEnvironment":40,"react/lib/invariant":43}],13:[function(_dereq_,module){function onPopState(){LocationDispatcher.handleViewAction({type:LocationActions.POP,path:getWindowPath()})}var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,LocationActions=_dereq_("../actions/LocationActions"),LocationDispatcher=_dereq_("../dispatchers/LocationDispatcher"),getWindowPath=_dereq_("../utils/getWindowPath"),_isSetup=!1,HistoryLocation={setup:function(){_isSetup||(invariant(canUseDOM,"You cannot use HistoryLocation in an environment with no DOM"),LocationDispatcher.handleViewAction({type:LocationActions.SETUP,path:getWindowPath()}),window.addEventListener?window.addEventListener("popstate",onPopState,!1):window.attachEvent("popstate",onPopState),_isSetup=!0)},teardown:function(){window.removeEventListener?window.removeEventListener("popstate",onPopState,!1):window.detachEvent("popstate",onPopState),_isSetup=!1},push:function(path){window.history.pushState({path:path},"",path),LocationDispatcher.handleViewAction({type:LocationActions.PUSH,path:getWindowPath()})},replace:function(path){window.history.replaceState({path:path},"",path),LocationDispatcher.handleViewAction({type:LocationActions.REPLACE,path:getWindowPath()})},pop:function(){window.history.back()},toString:function(){return"<HistoryLocation>"}};module.exports=HistoryLocation},{"../actions/LocationActions":1,"../dispatchers/LocationDispatcher":10,"../utils/getWindowPath":27,"react/lib/ExecutionEnvironment":40,"react/lib/invariant":43}],14:[function(_dereq_,module){var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,LocationActions=_dereq_("../actions/LocationActions"),LocationDispatcher=_dereq_("../dispatchers/LocationDispatcher"),getWindowPath=_dereq_("../utils/getWindowPath"),RefreshLocation={setup:function(){invariant(canUseDOM,"You cannot use RefreshLocation in an environment with no DOM"),LocationDispatcher.handleViewAction({type:LocationActions.SETUP,path:getWindowPath()})},push:function(path){window.location=path},replace:function(path){window.location.replace(path)},pop:function(){window.history.back()},toString:function(){return"<RefreshLocation>"}};module.exports=RefreshLocation},{"../actions/LocationActions":1,"../dispatchers/LocationDispatcher":10,"../utils/getWindowPath":27,"react/lib/ExecutionEnvironment":40,"react/lib/invariant":43}],15:[function(_dereq_,module){function routeIsActive(activeRoutes,routeName){return activeRoutes.some(function(route){return route.props.name===routeName})}function paramsAreActive(activeParams,params){for(var property in params)if(String(activeParams[property])!==String(params[property]))return!1;return!0}function queryIsActive(activeQuery,query){for(var property in query)if(String(activeQuery[property])!==String(query[property]))return!1;return!0}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,copyProperties=_dereq_("react/lib/copyProperties"),ActiveContext={propTypes:{initialActiveState:React.PropTypes.object},getDefaultProps:function(){return{initialActiveState:{}}},getInitialState:function(){var state=this.props.initialActiveState;return{activeRoutes:state.activeRoutes||[],activeParams:state.activeParams||{},activeQuery:state.activeQuery||{}}},getActiveRoutes:function(){return this.state.activeRoutes.slice(0)},getActiveParams:function(){return copyProperties({},this.state.activeParams)},getActiveQuery:function(){return copyProperties({},this.state.activeQuery)},isActive:function(routeName,params,query){var isActive=routeIsActive(this.state.activeRoutes,routeName)&¶msAreActive(this.state.activeParams,params);return query?isActive&&queryIsActive(this.state.activeQuery,query):isActive},childContextTypes:{activeRoutes:React.PropTypes.array.isRequired,activeParams:React.PropTypes.object.isRequired,activeQuery:React.PropTypes.object.isRequired,isActive:React.PropTypes.func.isRequired},getChildContext:function(){return{activeRoutes:this.getActiveRoutes(),activeParams:this.getActiveParams(),activeQuery:this.getActiveQuery(),isActive:this.isActive}}};module.exports=ActiveContext},{"react/lib/copyProperties":41}],16:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,ActiveState={contextTypes:{activeRoutes:React.PropTypes.array.isRequired,activeParams:React.PropTypes.object.isRequired,activeQuery:React.PropTypes.object.isRequired,isActive:React.PropTypes.func.isRequired},getActiveRoutes:function(){return this.context.activeRoutes},getActiveParams:function(){return this.context.activeParams},getActiveQuery:function(){return this.context.activeQuery},isActive:function(to,params,query){return this.context.isActive(to,params,query)}};module.exports=ActiveState},{}],17:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,CurrentPath={contextTypes:{currentPath:React.PropTypes.string.isRequired},getCurrentPath:function(){return this.context.currentPath}};module.exports=CurrentPath},{}],18:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,HashLocation=_dereq_("../locations/HashLocation"),HistoryLocation=_dereq_("../locations/HistoryLocation"),RefreshLocation=_dereq_("../locations/RefreshLocation"),supportsHistory=_dereq_("../utils/supportsHistory"),NAMED_LOCATIONS={none:null,hash:HashLocation,history:HistoryLocation,refresh:RefreshLocation},LocationContext={propTypes:{location:function(props,propName,componentName){var location=props[propName];return"string"!=typeof location||location in NAMED_LOCATIONS?void 0:new Error('Unknown location "'+location+'", see '+componentName)}},getDefaultProps:function(){return{location:canUseDOM?HashLocation:null}},getInitialState:function(){var location=this.props.location;return"string"==typeof location&&(location=NAMED_LOCATIONS[location]),location!==HistoryLocation||supportsHistory()||(location=RefreshLocation),{location:location}},componentWillMount:function(){var location=this.getLocation();invariant(null==location||canUseDOM,"Cannot use location without a DOM"),location&&location.setup&&location.setup()},getLocation:function(){return this.state.location},childContextTypes:{location:React.PropTypes.object},getChildContext:function(){return{location:this.getLocation()}}};module.exports=LocationContext},{"../locations/HashLocation":12,"../locations/HistoryLocation":13,"../locations/RefreshLocation":14,"../utils/supportsHistory":29,"react/lib/ExecutionEnvironment":40,"react/lib/invariant":43}],19:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Navigation={contextTypes:{makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},makePath:function(to,params,query){return this.context.makePath(to,params,query)},makeHref:function(to,params,query){return this.context.makeHref(to,params,query)},transitionTo:function(to,params,query){this.context.transitionTo(to,params,query)},replaceWith:function(to,params,query){this.context.replaceWith(to,params,query)},goBack:function(){this.context.goBack()}};module.exports=Navigation},{}],20:[function(_dereq_,module){function processRoute(route,container,namedRoutes){var props=route.props;invariant(React.isValidClass(props.handler),'The handler for the "%s" route must be a valid React class',props.name||props.path);var parentPath=container&&container.props.path||"/";if(!props.path&&!props.name||props.isDefault||props.catchAll)props.path=parentPath,props.catchAll&&(props.path+="*");else{var path=props.path||props.name;Path.isAbsolute(path)||(path=Path.join(parentPath,path)),props.path=Path.normalize(path)}if(props.paramNames=Path.extractParamNames(props.path),container&&Array.isArray(container.props.paramNames)&&container.props.paramNames.forEach(function(paramName){invariant(-1!==props.paramNames.indexOf(paramName),'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"',props.path,paramName,container.props.path)}),props.name){var existingRoute=namedRoutes[props.name];invariant(!existingRoute||route===existingRoute,'You cannot use the name "%s" for more than one route',props.name),namedRoutes[props.name]=route}return props.catchAll?(invariant(container,"<NotFoundRoute> must have a parent <Route>"),invariant(null==container.props.notFoundRoute,"You may not have more than one <NotFoundRoute> per <Route>"),container.props.notFoundRoute=route,null):props.isDefault?(invariant(container,"<DefaultRoute> must have a parent <Route>"),invariant(null==container.props.defaultRoute,"You may not have more than one <DefaultRoute> per <Route>"),container.props.defaultRoute=route,null):(props.children=processRoutes(props.children,route,namedRoutes),route)}function processRoutes(children,container,namedRoutes){var routes=[];return React.Children.forEach(children,function(child){(child=processRoute(child,container,namedRoutes))&&routes.push(child)}),routes}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),Path=_dereq_("../utils/Path"),RouteContext={getInitialState:function(){var namedRoutes={};return{routes:processRoutes(this.props.children,this,namedRoutes),namedRoutes:namedRoutes}},getRoutes:function(){return this.state.routes},getNamedRoutes:function(){return this.state.namedRoutes},getRouteByName:function(routeName){return this.state.namedRoutes[routeName]||null},childContextTypes:{routes:React.PropTypes.array.isRequired,namedRoutes:React.PropTypes.object.isRequired},getChildContext:function(){return{routes:this.getRoutes(),namedRoutes:this.getNamedRoutes()}}};module.exports=RouteContext},{"../utils/Path":23,"react/lib/invariant":43}],21:[function(_dereq_,module){function getWindowScrollPosition(){return invariant(canUseDOM,"Cannot get current scroll position without a DOM"),{x:window.scrollX,y:window.scrollY}}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,ImitateBrowserBehavior=_dereq_("../behaviors/ImitateBrowserBehavior"),ScrollToTopBehavior=_dereq_("../behaviors/ScrollToTopBehavior"),NAMED_SCROLL_BEHAVIORS={none:null,browser:ImitateBrowserBehavior,imitateBrowser:ImitateBrowserBehavior,scrollToTop:ScrollToTopBehavior},ScrollContext={propTypes:{scrollBehavior:function(props,propName,componentName){var behavior=props[propName];return"string"!=typeof behavior||behavior in NAMED_SCROLL_BEHAVIORS?void 0:new Error('Unknown scroll behavior "'+behavior+'", see '+componentName)}},getDefaultProps:function(){return{scrollBehavior:canUseDOM?ImitateBrowserBehavior:null}},getInitialState:function(){var behavior=this.props.scrollBehavior;return"string"==typeof behavior&&(behavior=NAMED_SCROLL_BEHAVIORS[behavior]),{scrollBehavior:behavior}},componentWillMount:function(){var behavior=this.getScrollBehavior();invariant(null==behavior||canUseDOM,"Cannot use scroll behavior without a DOM"),null!=behavior&&(this._scrollPositions={})},recordScroll:function(path){this._scrollPositions&&(this._scrollPositions[path]=getWindowScrollPosition())},updateScroll:function(path,actionType){var behavior=this.getScrollBehavior(),position=this._scrollPositions[path];behavior&&position&&behavior.updateScrollPosition(position,actionType)},getScrollBehavior:function(){return this.state.scrollBehavior},childContextTypes:{scrollBehavior:React.PropTypes.object},getChildContext:function(){return{scrollBehavior:this.getScrollBehavior()}}};module.exports=ScrollContext},{"../behaviors/ImitateBrowserBehavior":2,"../behaviors/ScrollToTopBehavior":3,"react/lib/ExecutionEnvironment":40,"react/lib/invariant":43}],22:[function(_dereq_,module){function notifyChange(){_events.emit(CHANGE_EVENT)}var _currentPath,_currentActionType,EventEmitter=_dereq_("events").EventEmitter,LocationActions=_dereq_("../actions/LocationActions"),LocationDispatcher=_dereq_("../dispatchers/LocationDispatcher"),CHANGE_EVENT="change",_events=new EventEmitter,PathStore={addChangeListener:function(listener){_events.addListener(CHANGE_EVENT,listener)},removeChangeListener:function(listener){_events.removeListener(CHANGE_EVENT,listener)},removeAllChangeListeners:function(){_events.removeAllListeners(CHANGE_EVENT)},getCurrentPath:function(){return _currentPath},getCurrentActionType:function(){return _currentActionType},dispatchToken:LocationDispatcher.register(function(payload){var action=payload.action;switch(action.type){case LocationActions.SETUP:case LocationActions.PUSH:case LocationActions.REPLACE:case LocationActions.POP:_currentPath!==action.path&&(_currentPath=action.path,_currentActionType=action.type,notifyChange())}})};module.exports=PathStore},{"../actions/LocationActions":1,"../dispatchers/LocationDispatcher":10,events:31}],23:[function(_dereq_,module){function encodeURL(url){return encodeURIComponent(url).replace(/%20/g,"+")}function decodeURL(url){return decodeURIComponent(url.replace(/\+/g," "))}function encodeURLPath(path){return String(path).split("/").map(encodeURL).join("/")}function compilePattern(pattern){if(!(pattern in _compiledPatterns)){var paramNames=[],source=pattern.replace(paramMatcher,function(match,paramName){return paramName?(paramNames.push(paramName),"([^/?#]+)"):"*"===match?(paramNames.push("splat"),"(.*?)"):"\\"+match});_compiledPatterns[pattern]={matcher:new RegExp("^"+source+"$","i"),paramNames:paramNames}}return _compiledPatterns[pattern]}var invariant=_dereq_("react/lib/invariant"),merge=_dereq_("qs/lib/utils").merge,qs=_dereq_("qs"),paramMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g,queryMatcher=/\?(.+)/,_compiledPatterns={},Path={extractParamNames:function(pattern){return compilePattern(pattern).paramNames},extractParams:function(pattern,path){var object=compilePattern(pattern),match=decodeURL(path).match(object.matcher);if(!match)return null;var params={};return object.paramNames.forEach(function(paramName,index){params[paramName]=match[index+1]}),params},injectParams:function(pattern,params){params=params||{};var splatIndex=0;return pattern.replace(paramMatcher,function(match,paramName){paramName=paramName||"splat",invariant(null!=params[paramName],'Missing "'+paramName+'" parameter for path "'+pattern+'"');var segment;return"splat"===paramName&&Array.isArray(params[paramName])?(segment=params[paramName][splatIndex++],invariant(null!=segment,"Missing splat # "+splatIndex+' for path "'+pattern+'"')):segment=params[paramName],encodeURLPath(segment)})},extractQuery:function(path){var match=decodeURL(path).match(queryMatcher);return match&&qs.parse(match[1])},withoutQuery:function(path){return path.replace(queryMatcher,"")},withQuery:function(path,query){var existingQuery=Path.extractQuery(path);existingQuery&&(query=query?merge(existingQuery,query):existingQuery);
var queryString=query&&qs.stringify(query);return queryString?Path.withoutQuery(path)+"?"+queryString:path},isAbsolute:function(path){return"/"===path.charAt(0)},normalize:function(path){return path.replace(/^\/*/,"/")},join:function(a,b){return a.replace(/\/*$/,"/")+b}};module.exports=Path},{qs:35,"qs/lib/utils":39,"react/lib/invariant":43}],24:[function(_dereq_,module){var Promise=_dereq_("when/lib/Promise");module.exports=Promise},{"when/lib/Promise":50}],25:[function(_dereq_,module){function Redirect(to,params,query){this.to=to,this.params=params,this.query=query}module.exports=Redirect},{}],26:[function(_dereq_,module){function Transition(routesComponent,path){this.routesComponent=routesComponent,this.path=path,this.abortReason=null,this.isAborted=!1}var mixInto=_dereq_("react/lib/mixInto"),Promise=_dereq_("./Promise"),Redirect=_dereq_("./Redirect");mixInto(Transition,{abort:function(reason){this.abortReason=reason,this.isAborted=!0},redirect:function(to,params,query){this.abort(new Redirect(to,params,query))},wait:function(value){this.promise=Promise.resolve(value)},retry:function(){this.routesComponent.replaceWith(this.path)}}),module.exports=Transition},{"./Promise":24,"./Redirect":25,"react/lib/mixInto":48}],27:[function(_dereq_,module){function getWindowPath(){return window.location.pathname+window.location.search}module.exports=getWindowPath},{}],28:[function(_dereq_,module){function reversedArray(array){return array.slice(0).reverse()}module.exports=reversedArray},{}],29:[function(_dereq_,module){function supportsHistory(){var ua=navigator.userAgent;return-1===ua.indexOf("Android 2.")&&-1===ua.indexOf("Android 4.0")||-1===ua.indexOf("Mobile Safari")||-1!==ua.indexOf("Chrome")?window.history&&"pushState"in window.history:!1}module.exports=supportsHistory},{}],30:[function(_dereq_,module){function withoutProperties(object,properties){var result={};for(var property in object)object.hasOwnProperty(property)&&!properties[property]&&(result[property]=object[property]);return result}module.exports=withoutProperties},{}],31:[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length))throw er=arguments[1],er instanceof Error?er:TypeError('Uncaught, unspecified "error" event.');if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},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;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],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(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],32:[function(_dereq_,module){module.exports.Dispatcher=_dereq_("./lib/Dispatcher")},{"./lib/Dispatcher":33}],33:[function(_dereq_,module){"use strict";function Dispatcher(){this.$Dispatcher_callbacks={},this.$Dispatcher_isPending={},this.$Dispatcher_isHandled={},this.$Dispatcher_isDispatching=!1,this.$Dispatcher_pendingPayload=null}var invariant=_dereq_("./invariant"),_lastID=1,_prefix="ID_";Dispatcher.prototype.register=function(callback){var id=_prefix+_lastID++;return this.$Dispatcher_callbacks[id]=callback,id},Dispatcher.prototype.unregister=function(id){invariant(this.$Dispatcher_callbacks[id],"Dispatcher.unregister(...): `%s` does not map to a registered callback.",id),delete this.$Dispatcher_callbacks[id]},Dispatcher.prototype.waitFor=function(ids){invariant(this.$Dispatcher_isDispatching,"Dispatcher.waitFor(...): Must be invoked while dispatching.");for(var ii=0;ii<ids.length;ii++){var id=ids[ii];this.$Dispatcher_isPending[id]?invariant(this.$Dispatcher_isHandled[id],"Dispatcher.waitFor(...): Circular dependency detected while waiting for `%s`.",id):(invariant(this.$Dispatcher_callbacks[id],"Dispatcher.waitFor(...): `%s` does not map to a registered callback.",id),this.$Dispatcher_invokeCallback(id))}},Dispatcher.prototype.dispatch=function(payload){invariant(!this.$Dispatcher_isDispatching,"Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch."),this.$Dispatcher_startDispatching(payload);try{for(var id in this.$Dispatcher_callbacks)this.$Dispatcher_isPending[id]||this.$Dispatcher_invokeCallback(id)}finally{this.$Dispatcher_stopDispatching()}},Dispatcher.prototype.isDispatching=function(){return this.$Dispatcher_isDispatching},Dispatcher.prototype.$Dispatcher_invokeCallback=function(id){this.$Dispatcher_isPending[id]=!0,this.$Dispatcher_callbacks[id](this.$Dispatcher_pendingPayload),this.$Dispatcher_isHandled[id]=!0},Dispatcher.prototype.$Dispatcher_startDispatching=function(payload){for(var id in this.$Dispatcher_callbacks)this.$Dispatcher_isPending[id]=!1,this.$Dispatcher_isHandled[id]=!1;this.$Dispatcher_pendingPayload=payload,this.$Dispatcher_isDispatching=!0},Dispatcher.prototype.$Dispatcher_stopDispatching=function(){this.$Dispatcher_pendingPayload=null,this.$Dispatcher_isDispatching=!1},module.exports=Dispatcher},{"./invariant":34}],34:[function(_dereq_,module){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;error=new Error("Invariant Violation: "+format.replace(/%s/g,function(){return args[argIndex++]}))}throw error.framesToPop=1,error}};module.exports=invariant},{}],35:[function(_dereq_,module){module.exports=_dereq_("./lib")},{"./lib":36}],36:[function(_dereq_,module){var Stringify=_dereq_("./stringify"),Parse=_dereq_("./parse");module.exports={stringify:Stringify,parse:Parse}},{"./parse":37,"./stringify":38}],37:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3};internals.parseValues=function(str,options){for(var obj={},parts=str.split(options.delimiter,1/0===options.parameterLimit?void 0:options.parameterLimit),i=0,il=parts.length;il>i;++i){var part=parts[i],pos=-1===part.indexOf("]=")?part.indexOf("="):part.indexOf("]=")+1;if(-1===pos)obj[Utils.decode(part)]="";else{var key=Utils.decode(part.slice(0,pos)),val=Utils.decode(part.slice(pos+1));obj[key]=obj[key]?[].concat(obj[key]).concat(val):val}}return obj},internals.parseObject=function(chain,val,options){if(!chain.length)return val;var root=chain.shift(),obj={};if("[]"===root)obj=[],obj=obj.concat(internals.parseObject(chain,val,options));else{var cleanRoot="["===root[0]&&"]"===root[root.length-1]?root.slice(1,root.length-1):root,index=parseInt(cleanRoot,10);!isNaN(index)&&root!==cleanRoot&&index<=options.arrayLimit?(obj=[],obj[index]=internals.parseObject(chain,val,options)):obj[cleanRoot]=internals.parseObject(chain,val,options)}return obj},internals.parseKeys=function(key,val,options){if(key){var parent=/^([^\[\]]*)/,child=/(\[[^\[\]]*\])/g,segment=parent.exec(key);if(!Object.prototype.hasOwnProperty(segment[1])){var keys=[];segment[1]&&keys.push(segment[1]);for(var i=0;null!==(segment=child.exec(key))&&i<options.depth;)++i,Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g,""))||keys.push(segment[1]);return segment&&keys.push("["+key.slice(segment.index)+"]"),internals.parseObject(keys,val,options)}}},module.exports=function(str,options){if(""===str||null===str||"undefined"==typeof str)return{};options=options||{},options.delimiter="string"==typeof options.delimiter||Utils.isRegExp(options.delimiter)?options.delimiter:internals.delimiter,options.depth="number"==typeof options.depth?options.depth:internals.depth,options.arrayLimit="number"==typeof options.arrayLimit?options.arrayLimit:internals.arrayLimit,options.parameterLimit="number"==typeof options.parameterLimit?options.parameterLimit:internals.parameterLimit;for(var tempObj="string"==typeof str?internals.parseValues(str,options):str,obj={},keys=Object.keys(tempObj),i=0,il=keys.length;il>i;++i){var key=keys[i],newObj=internals.parseKeys(key,tempObj[key],options);obj=Utils.merge(obj,newObj)}return Utils.compact(obj)}},{"./utils":39}],38:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&"};internals.stringify=function(obj,prefix){if(Utils.isBuffer(obj)?obj=obj.toString():obj instanceof Date?obj=obj.toISOString():null===obj&&(obj=""),"string"==typeof obj||"number"==typeof obj||"boolean"==typeof obj)return[encodeURIComponent(prefix)+"="+encodeURIComponent(obj)];var values=[];for(var key in obj)obj.hasOwnProperty(key)&&(values=values.concat(internals.stringify(obj[key],prefix+"["+key+"]")));return values},module.exports=function(obj,options){options=options||{};var delimiter="undefined"==typeof options.delimiter?internals.delimiter:options.delimiter,keys=[];for(var key in obj)obj.hasOwnProperty(key)&&(keys=keys.concat(internals.stringify(obj[key],key)));return keys.join(delimiter)}},{"./utils":39}],39:[function(_dereq_,module,exports){exports.arrayToObject=function(source){for(var obj={},i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(obj[i]=source[i]);return obj},exports.merge=function(target,source){if(!source)return target;if(Array.isArray(source)){for(var i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(target[i]="object"==typeof target[i]?exports.merge(target[i],source[i]):source[i]);return target}if(Array.isArray(target)){if("object"!=typeof source)return target.push(source),target;target=exports.arrayToObject(target)}for(var keys=Object.keys(source),k=0,kl=keys.length;kl>k;++k){var key=keys[k],value=source[key];target[key]=value&&"object"==typeof value&&target[key]?exports.merge(target[key],value):value}return target},exports.decode=function(str){try{return decodeURIComponent(str.replace(/\+/g," "))}catch(e){return str}},exports.compact=function(obj,refs){if("object"!=typeof obj||null===obj)return obj;refs=refs||[];var lookup=refs.indexOf(obj);if(-1!==lookup)return refs[lookup];if(refs.push(obj),Array.isArray(obj)){for(var compacted=[],i=0,l=obj.length;l>i;++i)"undefined"!=typeof obj[i]&&compacted.push(obj[i]);return compacted}for(var keys=Object.keys(obj),i=0,il=keys.length;il>i;++i){var key=keys[i];obj[key]=exports.compact(obj[key],refs)}return obj},exports.isRegExp=function(obj){return"[object RegExp]"===Object.prototype.toString.call(obj)},exports.isBuffer=function(obj){return"undefined"!=typeof Buffer?Buffer.isBuffer(obj):!1}},{}],40:[function(_dereq_,module){"use strict";var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),ExecutionEnvironment={canUseDOM:canUseDOM,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:canUseDOM&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:canUseDOM&&!!window.screen,isInWorker:!canUseDOM};module.exports=ExecutionEnvironment},{}],41:[function(_dereq_,module){function copyProperties(obj,a,b,c,d,e,f){obj=obj||{};for(var v,args=[a,b,c,d,e],ii=0;args[ii];){v=args[ii++];for(var k in v)obj[k]=v[k];v.hasOwnProperty&&v.hasOwnProperty("toString")&&"undefined"!=typeof v.toString&&obj.toString!==v.toString&&(obj.toString=v.toString)}return obj}module.exports=copyProperties},{}],42:[function(_dereq_,module){function makeEmptyFunction(arg){return function(){return arg}}function emptyFunction(){}var copyProperties=_dereq_("./copyProperties");copyProperties(emptyFunction,{thatReturns:makeEmptyFunction,thatReturnsFalse:makeEmptyFunction(!1),thatReturnsTrue:makeEmptyFunction(!0),thatReturnsNull:makeEmptyFunction(null),thatReturnsThis:function(){return this},thatReturnsArgument:function(arg){return arg}}),module.exports=emptyFunction},{"./copyProperties":41}],43:[function(_dereq_,module){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;error=new Error("Invariant Violation: "+format.replace(/%s/g,function(){return args[argIndex++]}))}throw error.framesToPop=1,error}};module.exports=invariant},{}],44:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),keyMirror=function(obj){var key,ret={};invariant(obj instanceof Object&&!Array.isArray(obj));for(key in obj)obj.hasOwnProperty(key)&&(ret[key]=key);return ret};module.exports=keyMirror},{"./invariant":43}],45:[function(_dereq_,module){"use strict";var mergeInto=_dereq_("./mergeInto"),merge=function(one,two){var result={};return mergeInto(result,one),mergeInto(result,two),result};module.exports=merge},{"./mergeInto":47}],46:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),keyMirror=_dereq_("./keyMirror"),MAX_MERGE_DEPTH=36,isTerminal=function(o){return"object"!=typeof o||null===o},mergeHelpers={MAX_MERGE_DEPTH:MAX_MERGE_DEPTH,isTerminal:isTerminal,normalizeMergeArg:function(arg){return void 0===arg||null===arg?{}:arg},checkMergeArrayArgs:function(one,two){invariant(Array.isArray(one)&&Array.isArray(two))},checkMergeObjectArgs:function(one,two){mergeHelpers.checkMergeObjectArg(one),mergeHelpers.checkMergeObjectArg(two)},checkMergeObjectArg:function(arg){invariant(!isTerminal(arg)&&!Array.isArray(arg))},checkMergeIntoObjectArg:function(arg){invariant(!(isTerminal(arg)&&"function"!=typeof arg||Array.isArray(arg)))},checkMergeLevel:function(level){invariant(MAX_MERGE_DEPTH>level)},checkArrayStrategy:function(strategy){invariant(void 0===strategy||strategy in mergeHelpers.ArrayStrategies)},ArrayStrategies:keyMirror({Clobber:!0,IndexByIndex:!0})};module.exports=mergeHelpers},{"./invariant":43,"./keyMirror":44}],47:[function(_dereq_,module){"use strict";function mergeInto(one,two){if(checkMergeIntoObjectArg(one),null!=two){checkMergeObjectArg(two);for(var key in two)two.hasOwnProperty(key)&&(one[key]=two[key])}}var mergeHelpers=_dereq_("./mergeHelpers"),checkMergeObjectArg=mergeHelpers.checkMergeObjectArg,checkMergeIntoObjectArg=mergeHelpers.checkMergeIntoObjectArg;module.exports=mergeInto},{"./mergeHelpers":46}],48:[function(_dereq_,module){"use strict";var mixInto=function(constructor,methodBag){var methodName;for(methodName in methodBag)methodBag.hasOwnProperty(methodName)&&(constructor.prototype[methodName]=methodBag[methodName])};module.exports=mixInto},{}],49:[function(_dereq_,module){"use strict";var emptyFunction=_dereq_("./emptyFunction"),warning=emptyFunction;module.exports=warning},{"./emptyFunction":42}],50:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var makePromise=_dereq_("./makePromise"),Scheduler=_dereq_("./Scheduler"),async=_dereq_("./async");return makePromise({scheduler:new Scheduler(async)})})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Scheduler":52,"./async":53,"./makePromise":54}],51:[function(_dereq_,module){!function(define){"use strict";define(function(){function Queue(capacityPow2){this.head=this.tail=this.length=0,this.buffer=new Array(1<<capacityPow2)}return Queue.prototype.push=function(x){return this.length===this.buffer.length&&this._ensureCapacity(2*this.length),this.buffer[this.tail]=x,this.tail=this.tail+1&this.buffer.length-1,++this.length,this.length},Queue.prototype.shift=function(){var x=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=this.head+1&this.buffer.length-1,--this.length,x},Queue.prototype._ensureCapacity=function(capacity){var len,head=this.head,buffer=this.buffer,newBuffer=new Array(capacity),i=0;if(0===head)for(len=this.length;len>i;++i)newBuffer[i]=buffer[i];else{for(capacity=buffer.length,len=this.tail;capacity>head;++i,++head)newBuffer[i]=buffer[head];for(head=0;len>head;++i,++head)newBuffer[i]=buffer[head]}this.buffer=newBuffer,this.head=0,this.tail=this.length},Queue})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}],52:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){function Scheduler(async){this._async=async,this._queue=new Queue(15),this._afterQueue=new Queue(5),this._running=!1;var self=this;this.drain=function(){self._drain()}}function runQueue(queue){for(;queue.length>0;)queue.shift().run()}var Queue=_dereq_("./Queue");return Scheduler.prototype.enqueue=function(task){this._add(this._queue,task)},Scheduler.prototype.afterQueue=function(task){this._add(this._afterQueue,task)},Scheduler.prototype._drain=function(){runQueue(this._queue),this._running=!1,runQueue(this._afterQueue)},Scheduler.prototype._add=function(queue,task){queue.push(task),this._running||(this._running=!0,this._async(this.drain))},Scheduler})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Queue":51}],53:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var nextTick,MutationObs;return nextTick="undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick?function(f){process.nextTick(f)}:(MutationObs="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)?function(document,MutationObserver){function run(){var f=scheduled;scheduled=void 0,f()}var scheduled,el=document.createElement("div"),o=new MutationObserver(run);return o.observe(el,{attributes:!0}),function(f){scheduled=f,el.setAttribute("class","x")}}(document,MutationObs):function(cjsRequire){var vertx;try{vertx=cjsRequire("vertx")}catch(ignore){}if(vertx){if("function"==typeof vertx.runOnLoop)return vertx.runOnLoop;if("function"==typeof vertx.runOnContext)return vertx.runOnContext}var capturedSetTimeout=setTimeout;return function(t){capturedSetTimeout(t,0)}}(_dereq_)})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{}],54:[function(_dereq_,module){!function(define){"use strict";define(function(){return function(environment){function Promise(resolver,handler){this._handler=resolver===Handler?handler:init(resolver)}function init(resolver){function promiseResolve(x){handler.resolve(x)}function promiseReject(reason){handler.reject(reason)}function promiseNotify(x){handler.notify(x)}var handler=new Pending;try{resolver(promiseResolve,promiseReject,promiseNotify)}catch(e){promiseReject(e)}return handler}function resolve(x){return isPromise(x)?x:new Promise(Handler,new Async(getHandler(x)))}function reject(x){return new Promise(Handler,new Async(new Rejected(x)))}function never(){return foreverPendingPromise}function defer(){return new Promise(Handler,new Pending)}function all(promises){function settleAt(i,x,resolver){this[i]=x,0===--pending&&resolver.become(new Fulfilled(this))}var i,h,x,s,resolver=new Pending,pending=promises.length>>>0,results=new Array(pending);for(i=0;i<promises.length;++i)if(x=promises[i],void 0!==x||i in promises)if(maybeThenable(x))if(h=getHandlerMaybeThenable(x),s=h.state(),0===s)h.fold(settleAt,i,results,resolver);else{if(!(s>0)){unreportRemaining(promises,i+1,h),resolver.become(h);break}results[i]=h.value,--pending}else results[i]=x,--pending;else--pending;return 0===pending&&resolver.become(new Fulfilled(results)),new Promise(Handler,resolver)}function unreportRemaining(promises,start,rejectedHandler){var i,h,x;for(i=start;i<promises.length;++i)x=promises[i],maybeThenable(x)&&(h=getHandlerMaybeThenable(x),h!==rejectedHandler&&h.visit(h,void 0,h._unreport))}function race(promises){if(Object(promises)===promises&&0===promises.length)return never();var i,x,h=new Pending;for(i=0;i<promises.length;++i)x=promises[i],void 0!==x&&i in promises&&getHandler(x).visit(h,h.resolve,h.reject);return new Promise(Handler,h)}function getHandler(x){return isPromise(x)?x._handler.join():maybeThenable(x)?getHandlerUntrusted(x):new Fulfilled(x)}function getHandlerMaybeThenable(x){return isPromise(x)?x._handler.join():getHandlerUntrusted(x)}function getHandlerUntrusted(x){try{var untrustedThen=x.then;return"function"==typeof untrustedThen?new Thenable(untrustedThen,x):new Fulfilled(x)}catch(e){return new Rejected(e)}}function Handler(){}function FailIfRejected(){}function Pending(receiver,inheritedContext){Promise.createContext(this,inheritedContext),this.consumers=void 0,this.receiver=receiver,this.handler=void 0,this.resolved=!1}function Async(handler){this.handler=handler}function Thenable(then,thenable){Pending.call(this),tasks.enqueue(new AssimilateTask(then,thenable,this))}function Fulfilled(x){Promise.createContext(this),this.value=x}function Rejected(x){Promise.createContext(this),this.id=++errorId,this.value=x,this.handled=!1,this.reported=!1,this._report()}function ReportTask(rejection,context){this.rejection=rejection,this.context=context}function UnreportTask(rejection){this.rejection=rejection}function cycle(){return new Rejected(new TypeError("Promise cycle"))}function ContinuationTask(continuation,handler){this.continuation=continuation,this.handler=handler}function ProgressTask(value,handler){this.handler=handler,this.value=value}function AssimilateTask(then,thenable,resolver){this._then=then,this.thenable=thenable,this.resolver=resolver}function tryAssimilate(then,thenable,resolve,reject,notify){try{then.call(thenable,resolve,reject,notify)}catch(e){reject(e)}}function isPromise(x){return x instanceof Promise}function maybeThenable(x){return("object"==typeof x||"function"==typeof x)&&null!==x}function runContinuation1(f,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject(f,h.value,receiver,next),void Promise.exitContext())}function runContinuation3(f,x,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject3(f,x,h.value,receiver,next),void Promise.exitContext())}function runNotify(f,x,h,receiver,next){return"function"!=typeof f?next.notify(x):(Promise.enterContext(h),tryCatchReturn(f,x,receiver,next),void Promise.exitContext())}function tryCatchReject(f,x,thisArg,next){try{next.become(getHandler(f.call(thisArg,x)))}catch(e){next.become(new Rejected(e))}}function tryCatchReject3(f,x,y,thisArg,next){try{f.call(thisArg,x,y,next)}catch(e){next.become(new Rejected(e))}}function tryCatchReturn(f,x,thisArg,next){try{next.notify(f.call(thisArg,x))}catch(e){next.notify(e)}}function inherit(Parent,Child){Child.prototype=objectCreate(Parent.prototype),Child.prototype.constructor=Child}function noop(){}var tasks=environment.scheduler,objectCreate=Object.create||function(proto){function Child(){}return Child.prototype=proto,new Child};Promise.resolve=resolve,Promise.reject=reject,Promise.never=never,Promise._defer=defer,Promise._handler=getHandler,Promise.prototype.then=function(onFulfilled,onRejected){var parent=this._handler,state=parent.join().state();if("function"!=typeof onFulfilled&&state>0||"function"!=typeof onRejected&&0>state)return new this.constructor(Handler,parent);var p=this._beget(),child=p._handler;return parent.chain(child,parent.receiver,onFulfilled,onRejected,arguments.length>2?arguments[2]:void 0),p},Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)},Promise.prototype._beget=function(){var parent=this._handler,child=new Pending(parent.receiver,parent.join().context);return new this.constructor(Handler,child)},Promise.all=all,Promise.race=race,Handler.prototype.when=Handler.prototype.become=Handler.prototype.notify=Handler.prototype.fail=Handler.prototype._unreport=Handler.prototype._report=noop,Handler.prototype._state=0,Handler.prototype.state=function(){return this._state},Handler.prototype.join=function(){for(var h=this;void 0!==h.handler;)h=h.handler;return h},Handler.prototype.chain=function(to,receiver,fulfilled,rejected,progress){this.when({resolver:to,receiver:receiver,fulfilled:fulfilled,rejected:rejected,progress:progress})},Handler.prototype.visit=function(receiver,fulfilled,rejected,progress){this.chain(failIfRejected,receiver,fulfilled,rejected,progress)},Handler.prototype.fold=function(f,z,c,to){this.visit(to,function(x){f.call(c,z,x,this)},to.reject,to.notify)},inherit(Handler,FailIfRejected),FailIfRejected.prototype.become=function(h){h.fail()};var failIfRejected=new FailIfRejected;inherit(Handler,Pending),Pending.prototype._state=0,Pending.prototype.resolve=function(x){this.become(getHandler(x))},Pending.prototype.reject=function(x){this.resolved||this.become(new Rejected(x))},Pending.prototype.join=function(){if(!this.resolved)return this;for(var h=this;void 0!==h.handler;)if(h=h.handler,h===this)return this.handler=cycle();return h},Pending.prototype.run=function(){var q=this.consumers,handler=this.join();this.consumers=void 0;for(var i=0;i<q.length;++i)handler.when(q[i])},Pending.prototype.become=function(handler){this.resolved||(this.resolved=!0,this.handler=handler,void 0!==this.consumers&&tasks.enqueue(this),void 0!==this.context&&handler._report(this.context))},Pending.prototype.when=function(continuation){this.resolved?tasks.enqueue(new ContinuationTask(continuation,this.handler)):void 0===this.consumers?this.consumers=[continuation]:this.consumers.push(continuation)},Pending.prototype.notify=function(x){this.resolved||tasks.enqueue(new ProgressTask(x,this))},Pending.prototype.fail=function(context){var c="undefined"==typeof context?this.context:context;this.resolved&&this.handler.join().fail(c)},Pending.prototype._report=function(context){this.resolved&&this.handler.join()._report(context)},Pending.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},inherit(Handler,Async),Async.prototype.when=function(continuation){tasks.enqueue(new ContinuationTask(continuation,this))},Async.prototype._report=function(context){this.join()._report(context)},Async.prototype._unreport=function(){this.join()._unreport()},inherit(Pending,Thenable),inherit(Handler,Fulfilled),Fulfilled.prototype._state=1,Fulfilled.prototype.fold=function(f,z,c,to){runContinuation3(f,z,this,c,to)},Fulfilled.prototype.when=function(cont){runContinuation1(cont.fulfilled,this,cont.receiver,cont.resolver)};var errorId=0;inherit(Handler,Rejected),Rejected.prototype._state=-1,Rejected.prototype.fold=function(f,z,c,to){to.become(this)},Rejected.prototype.when=function(cont){"function"==typeof cont.rejected&&this._unreport(),runContinuation1(cont.rejected,this,cont.receiver,cont.resolver)},Rejected.prototype._report=function(context){tasks.afterQueue(new ReportTask(this,context))},Rejected.prototype._unreport=function(){this.handled=!0,tasks.afterQueue(new UnreportTask(this))},Rejected.prototype.fail=function(context){Promise.onFatalRejection(this,void 0===context?this.context:context)},ReportTask.prototype.run=function(){this.rejection.handled||(this.rejection.reported=!0,Promise.onPotentiallyUnhandledRejection(this.rejection,this.context))},UnreportTask.prototype.run=function(){this.rejection.reported&&Promise.onPotentiallyUnhandledRejectionHandled(this.rejection)},Promise.createContext=Promise.enterContext=Promise.exitContext=Promise.onPotentiallyUnhandledRejection=Promise.onPotentiallyUnhandledRejectionHandled=Promise.onFatalRejection=noop;var foreverPendingHandler=new Handler,foreverPendingPromise=new Promise(Handler,foreverPendingHandler);return ContinuationTask.prototype.run=function(){this.handler.join().when(this.continuation)},ProgressTask.prototype.run=function(){var q=this.handler.consumers;if(void 0!==q)for(var c,i=0;i<q.length;++i)c=q[i],runNotify(c.progress,this.value,this.handler,c.receiver,c.resolver)},AssimilateTask.prototype.run=function(){function _resolve(x){h.resolve(x)}function _reject(x){h.reject(x)}function _notify(x){h.notify(x)}var h=this.resolver;tryAssimilate(this._then,this.thenable,_resolve,_reject,_notify)},Promise}})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}]},{},[11])(11)}); |
ajax/libs/jquery.fancytree/2.8.1/jquery.fancytree-all.js | maruilian11/cdnjs | /*!
* jquery.fancytree.js
* Dynamic tree view control, with support for lazy loading of branches.
* https://github.com/mar10/fancytree/
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
/** Core Fancytree module.
*/
// Start of local namespace
;(function($, window, document, undefined) {
"use strict";
// prevent duplicate loading
if ( $.ui && $.ui.fancytree ) {
$.ui.fancytree.warn("Fancytree: ignored duplicate include");
return;
}
/* *****************************************************************************
* Private functions and variables
*/
function _assert(cond, msg){
// TODO: see qunit.js extractStacktrace()
if(!cond){
msg = msg ? ": " + msg : "";
// consoleApply("assert", [!!cond, msg]);
$.error("Fancytree assertion failed" + msg);
}
}
_assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)");
function consoleApply(method, args){
var i, s,
fn = window.console ? window.console[method] : null;
if(fn){
try{
fn.apply(window.console, args);
} catch(e) {
// IE 8?
s = "";
for( i=0; i<args.length; i++){
s += args[i];
}
fn(s);
}
}
}
/*Return true if x is a FancytreeNode.*/
function _isNode(x){
return !!(x.tree && x.statusNodeType !== undefined);
}
/** Return true if dotted version string is equal or higher than requested version.
*
* See http://jsfiddle.net/mar10/FjSAN/
*/
function isVersionAtLeast(dottedVersion, major, minor, patch){
var i, v, t,
verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }),
testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); });
for( i = 0; i < testParts.length; i++ ){
v = verParts[i] || 0;
t = testParts[i] || 0;
if( v !== t ){
return ( v > t );
}
}
return true;
}
/** Return a wrapper that calls sub.methodName() and exposes
* this : tree
* this._local : tree.ext.EXTNAME
* this._super : base.methodName()
*/
function _makeVirtualFunction(methodName, tree, base, extension, extName){
// $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName);
// if(rexTestSuper && !rexTestSuper.test(func)){
// // extension.methodName() doesn't call _super(), so no wrapper required
// return func;
// }
// Use an immediate function as closure
var proxy = (function(){
var prevFunc = tree[methodName], // org. tree method or prev. proxy
baseFunc = extension[methodName], //
_local = tree.ext[extName],
_super = function(){
return prevFunc.apply(tree, arguments);
},
_superApply = function(args){
return prevFunc.apply(tree, args);
};
// Return the wrapper function
return function(){
var prevLocal = tree._local,
prevSuper = tree._super,
prevSuperApply = tree._superApply;
try{
tree._local = _local;
tree._super = _super;
tree._superApply = _superApply;
return baseFunc.apply(tree, arguments);
}finally{
tree._local = prevLocal;
tree._super = prevSuper;
tree._superApply = prevSuperApply;
}
};
})(); // end of Immediate Function
return proxy;
}
/**
* Subclass `base` by creating proxy functions
*/
function _subclassObject(tree, base, extension, extName){
// $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
for(var attrName in extension){
if(typeof extension[attrName] === "function"){
if(typeof tree[attrName] === "function"){
// override existing method
tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
}else if(attrName.charAt(0) === "_"){
// Create private methods in tree.ext.EXTENSION namespace
tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
}else{
$.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName);
}
}else{
// Create member variables in tree.ext.EXTENSION namespace
if(attrName !== "options"){
tree.ext[extName][attrName] = extension[attrName];
}
}
}
}
function _getResolvedPromise(context, argArray){
if(context === undefined){
return $.Deferred(function(){this.resolve();}).promise();
}else{
return $.Deferred(function(){this.resolveWith(context, argArray);}).promise();
}
}
function _getRejectedPromise(context, argArray){
if(context === undefined){
return $.Deferred(function(){this.reject();}).promise();
}else{
return $.Deferred(function(){this.rejectWith(context, argArray);}).promise();
}
}
function _makeResolveFunc(deferred, context){
return function(){
deferred.resolveWith(context);
};
}
function _getElementDataAsDict($el){
// Evaluate 'data-NAME' attributes with special treatment for 'data-json'.
var d = $.extend({}, $el.data()),
json = d.json;
delete d.fancytree; // added to container by widget factory
if( json ) {
delete d.json;
// <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5)
d = $.extend(d, json);
}
return d;
}
// TODO: use currying
function _makeNodeTitleMatcher(s){
s = s.toLowerCase();
return function(node){
return node.title.toLowerCase().indexOf(s) >= 0;
};
}
function _makeNodeTitleStartMatcher(s){
var reMatch = new RegExp("^" + s, "i");
return function(node){
return reMatch.test(node.title);
};
}
var i,
FT = null, // initialized below
ENTITY_MAP = {"&": "&", "<": "<", ">": ">", "\"": """, "'": "'", "/": "/"},
IGNORE_KEYCODES = { 16: true, 17: true, 18: true },
SPECIAL_KEYCODES = {
8: "backspace", 9: "tab", 10: "return", 13: "return",
// 16: null, 17: null, 18: null, // ignore shift, ctrl, alt
19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup",
34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up",
39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=",
96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6",
103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".",
111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5",
117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11",
123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=",
188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
221: "]", 222: "'"},
MOUSE_BUTTONS = { 0: "", 1: "left", 2: "middle", 3: "right" },
//boolean attributes that can be set with equivalent class names in the LI tags
CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "),
CLASS_ATTR_MAP = {},
// Top-level Fancytree node attributes, that can be set by dict
NODE_ATTRS = "expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "),
NODE_ATTR_MAP = {},
// Attribute names that should NOT be added to node.data
NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true};
for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; }
for(i=0; i<NODE_ATTRS.length; i++){ NODE_ATTR_MAP[NODE_ATTRS[i]] = true; }
/* *****************************************************************************
* FancytreeNode
*/
/**
* Creates a new FancytreeNode
*
* @class FancytreeNode
* @classdesc A FancytreeNode represents the hierarchical data model and operations.
*
* @param {FancytreeNode} parent
* @param {NodeData} obj
*
* @property {Fancytree} tree The tree instance
* @property {FancytreeNode} parent The parent node
* @property {string} key Node id (must be unique inside the tree)
* @property {string} title Display name (may contain HTML)
* @property {object} data Contains all extra data that was passed on node creation
* @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br>
* For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array
* to define a node that has no children.
* @property {boolean} expanded Use isExpanded(), setExpanded() to access this property.
* @property {string} extraClasses Addtional CSS classes, added to the node's `<span>`
* @property {boolean} folder Folder nodes have different default icons and click behavior.<br>
* Note: Also non-folders may have children.
* @property {string} statusNodeType null or type of temporarily generated system node like 'loading', or 'error'.
* @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion.
* @property {boolean} selected Use isSelected(), setSelected() to access this property.
* @property {string} tooltip Alternative description used as hover banner
*/
function FancytreeNode(parent, obj){
var i, l, name, cl;
this.parent = parent;
this.tree = parent.tree;
this.ul = null;
this.li = null; // <li id='key' ftnode=this> tag
this.statusNodeType = null; // if this is a temp. node to display the status of its parent
this._isLoading = false; // if this node itself is loading
this._error = null; // {message: '...'} if a load error occured
this.data = {};
// TODO: merge this code with node.toDict()
// copy attributes from obj object
for(i=0, l=NODE_ATTRS.length; i<l; i++){
name = NODE_ATTRS[i];
this[name] = obj[name];
}
// node.data += obj.data
if(obj.data){
$.extend(this.data, obj.data);
}
// copy all other attributes to this.data.NAME
for(name in obj){
if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){
// node.data.NAME = obj.NAME
this.data[name] = obj[name];
}
}
// Fix missing key
if( this.key == null ){ // test for null OR undefined
if( this.tree.options.defaultKey ) {
this.key = this.tree.options.defaultKey(this);
_assert(this.key, "defaultKey() must return a unique key");
} else {
this.key = "_" + (FT._nextNodeKey++);
}
} else {
this.key = "" + this.key; // Convert to string (#217)
}
// Fix tree.activeNode
// TODO: not elegant: we use obj.active as marker to set tree.activeNode
// when loading from a dictionary.
if(obj.active){
_assert(this.tree.activeNode === null, "only one active node allowed");
this.tree.activeNode = this;
}
if( obj.selected ){ // #186
this.tree.lastSelectedNode = this;
}
// TODO: handle obj.focus = true
// Create child nodes
this.children = null;
cl = obj.children;
if(cl && cl.length){
this._setChildren(cl);
}
// Add to key/ref map (except for root node)
// if( parent ) {
this.tree._callHook("treeRegisterNode", this.tree, true, this);
// }
}
FancytreeNode.prototype = /** @lends FancytreeNode# */{
/* Return the direct child FancytreeNode with a given key, index. */
_findDirectChild: function(ptr){
var i, l,
cl = this.children;
if(cl){
if(typeof ptr === "string"){
for(i=0, l=cl.length; i<l; i++){
if(cl[i].key === ptr){
return cl[i];
}
}
}else if(typeof ptr === "number"){
return this.children[ptr];
}else if(ptr.parent === this){
return ptr;
}
}
return null;
},
// TODO: activate()
// TODO: activateSilently()
/* Internal helper called in recursive addChildren sequence.*/
_setChildren: function(children){
_assert(children && (!this.children || this.children.length === 0), "only init supported");
this.children = [];
for(var i=0, l=children.length; i<l; i++){
this.children.push(new FancytreeNode(this, children[i]));
}
},
/**
* Append (or insert) a list of child nodes.
*
* @param {NodeData[]} children array of child node definitions (also single child accepted)
* @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such).
* If omitted, the new children are appended.
* @returns {FancytreeNode} first child added
*
* @see FancytreeNode#applyPatch
*/
addChildren: function(children, insertBefore){
var i, l, pos,
firstNode = null,
nodeList = [];
if($.isPlainObject(children) ){
children = [children];
}
if(!this.children){
this.children = [];
}
for(i=0, l=children.length; i<l; i++){
nodeList.push(new FancytreeNode(this, children[i]));
}
firstNode = nodeList[0];
if(insertBefore == null){
this.children = this.children.concat(nodeList);
}else{
insertBefore = this._findDirectChild(insertBefore);
pos = $.inArray(insertBefore, this.children);
_assert(pos >= 0, "insertBefore must be an existing child");
// insert nodeList after children[pos]
this.children.splice.apply(this.children, [pos, 0].concat(nodeList));
}
if( !this.parent || this.parent.ul || this.tr ){
// render if the parent was rendered (or this is a root node)
this.render();
}
if( this.tree.options.selectMode === 3 ){
this.fixSelection3FromEndNodes();
}
return firstNode;
},
/**
* Append or prepend a node, or append a child node.
*
* This a convenience function that calls addChildren()
*
* @param {NodeData} node node definition
* @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child')
* @returns {FancytreeNode} new node
*/
addNode: function(node, mode){
if(mode === undefined || mode === "over"){
mode = "child";
}
switch(mode){
case "after":
return this.getParent().addChildren(node, this.getNextSibling());
case "before":
return this.getParent().addChildren(node, this);
case "firstChild":
// Insert before the first child if any
var insertBefore = (this.children ? this.children[0] : null);
return this.addChildren(node, insertBefore);
case "child":
case "over":
return this.addChildren(node);
}
_assert(false, "Invalid mode: " + mode);
},
/**
* Append new node after this.
*
* This a convenience function that calls addNode(node, 'after')
*
* @param {NodeData} node node definition
* @returns {FancytreeNode} new node
*/
appendSibling: function(node){
return this.addNode(node, "after");
},
/**
* Modify existing child nodes.
*
* @param {NodePatch} patch
* @returns {$.Promise}
* @see FancytreeNode#addChildren
*/
applyPatch: function(patch) {
// patch [key, null] means 'remove'
if(patch === null){
this.remove();
return _getResolvedPromise(this);
}
// TODO: make sure that root node is not collapsed or modified
// copy (most) attributes to node.ATTR or node.data.ATTR
var name, promise, v,
IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global
for(name in patch){
v = patch[name];
if( !IGNORE_MAP[name] && !$.isFunction(v)){
if(NODE_ATTR_MAP[name]){
this[name] = v;
}else{
this.data[name] = v;
}
}
}
// Remove and/or create children
if(patch.hasOwnProperty("children")){
this.removeChildren();
if(patch.children){ // only if not null and not empty list
// TODO: addChildren instead?
this._setChildren(patch.children);
}
// TODO: how can we APPEND or INSERT child nodes?
}
if(this.isVisible()){
this.renderTitle();
this.renderStatus();
}
// Expand collapse (final step, since this may be async)
if(patch.hasOwnProperty("expanded")){
promise = this.setExpanded(patch.expanded);
}else{
promise = _getResolvedPromise(this);
}
return promise;
},
/** Collapse all sibling nodes.
* @returns {$.Promise}
*/
collapseSiblings: function() {
return this.tree._callHook("nodeCollapseSiblings", this);
},
/** Copy this node as sibling or child of `node`.
*
* @param {FancytreeNode} node source node
* @param {string} [mode=child] 'before' | 'after' | 'child'
* @param {Function} [map] callback function(NodeData) that could modify the new node
* @returns {FancytreeNode} new
*/
copyTo: function(node, mode, map) {
return node.addNode(this.toDict(true, map), mode);
},
/** Count direct and indirect children.
*
* @param {boolean} [deep=true] pass 'false' to only count direct children
* @returns {int} number of child nodes
*/
countChildren: function(deep) {
var cl = this.children, i, l, n;
if( !cl ){
return 0;
}
n = cl.length;
if(deep !== false){
for(i=0, l=n; i<l; i++){
n += cl[i].countChildren();
}
}
return n;
},
// TODO: deactivate()
/** Write to browser console if debugLevel >= 2 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.tree.options.debugLevel >= 2 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
/** Deprecated.
* @deprecated since 2014-02-16. Use resetLazy() instead.
*/
discard: function(){
this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead.");
return this.resetLazy();
},
// TODO: expand(flag)
/**Find all nodes that contain `match` in the title.
*
* @param {string | function(node)} match string to search for, of a function that
* returns `true` if a node is matched.
* @returns {FancytreeNode[]} array of nodes (may be empty)
* @see FancytreeNode#findAll
*/
findAll: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = [];
this.visit(function(n){
if(match(n)){
res.push(n);
}
});
return res;
},
/**Find first node that contains `match` in the title (not including self).
*
* @param {string | function(node)} match string to search for, of a function that
* returns `true` if a node is matched.
* @returns {FancytreeNode} matching node or null
* @example
* <b>fat</b> text
*/
findFirst: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = null;
this.visit(function(n){
if(match(n)){
res = n;
return false;
}
});
return res;
},
/* Apply selection state (internal use only) */
_changeSelectStatusAttrs: function (state) {
var changed = false;
switch(state){
case false:
changed = ( this.selected || this.partsel );
this.selected = false;
this.partsel = false;
break;
case true:
changed = ( !this.selected || !this.partsel );
this.selected = true;
this.partsel = true;
break;
case undefined:
changed = ( this.selected || !this.partsel );
this.selected = false;
this.partsel = true;
break;
default:
_assert(false, "invalid state: " + state);
}
// this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed);
if( changed ){
this.renderStatus();
}
return changed;
},
/**
* Fix selection status, after this node was (de)selected in multi-hier mode.
* This includes (de)selecting all children.
*/
fixSelection3AfterClick: function() {
var flag = this.isSelected();
// this.debug("fixSelection3AfterClick()");
this.visit(function(node){
node._changeSelectStatusAttrs(flag);
});
this.fixSelection3FromEndNodes();
},
/**
* Fix selection status for multi-hier mode.
* Only end-nodes are considered to update the descendants branch and parents.
* Should be called after this node has loaded new children or after
* children have been modified using the API.
*/
fixSelection3FromEndNodes: function() {
// this.debug("fixSelection3FromEndNodes()");
_assert(this.tree.options.selectMode === 3, "expected selectMode 3");
// Visit all end nodes and adjust their parent's `selected` and `partsel`
// attributes. Return selection state true, false, or undefined.
function _walk(node){
var i, l, child, s, state, allSelected,someSelected,
children = node.children;
if( children && children.length ){
// check all children recursively
allSelected = true;
someSelected = false;
for( i=0, l=children.length; i<l; i++ ){
child = children[i];
// the selection state of a node is not relevant; we need the end-nodes
s = _walk(child);
if( s !== false ) {
someSelected = true;
}
if( s !== true ) {
allSelected = false;
}
}
state = allSelected ? true : (someSelected ? undefined : false);
}else{
// This is an end-node: simply report the status
// state = ( node.unselectable ) ? undefined : !!node.selected;
state = !!node.selected;
}
node._changeSelectStatusAttrs(state);
return state;
}
_walk(this);
// Update parent's state
this.visitParents(function(node){
var i, l, child, state,
children = node.children,
allSelected = true,
someSelected = false;
for( i=0, l=children.length; i<l; i++ ){
child = children[i];
// When fixing the parents, we trust the sibling status (i.e.
// we don't recurse)
if( child.selected || child.partsel ) {
someSelected = true;
}
if( !child.unselectable && !child.selected ) {
allSelected = false;
}
}
state = allSelected ? true : (someSelected ? undefined : false);
node._changeSelectStatusAttrs(state);
});
},
// TODO: focus()
/**
* Update node data. If dict contains 'children', then also replace
* the hole sub tree.
* @param {NodeData} dict
*
* @see FancytreeNode#addChildren
* @see FancytreeNode#applyPatch
*/
fromDict: function(dict) {
// copy all other attributes to this.data.xxx
for(var name in dict){
if(NODE_ATTR_MAP[name]){
// node.NAME = dict.NAME
this[name] = dict[name];
}else if(name === "data"){
// node.data += dict.data
$.extend(this.data, dict.data);
}else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){
// node.data.NAME = dict.NAME
this.data[name] = dict[name];
}
}
if(dict.children){
// recursively set children and render
this.removeChildren();
this.addChildren(dict.children);
}
this.renderTitle();
/*
var children = dict.children;
if(children === undefined){
this.data = $.extend(this.data, dict);
this.render();
return;
}
dict = $.extend({}, dict);
dict.children = undefined;
this.data = $.extend(this.data, dict);
this.removeChildren();
this.addChild(children);
*/
},
/** Return the list of child nodes (undefined for unexpanded lazy nodes).
* @returns {FancytreeNode[] | undefined}
*/
getChildren: function() {
if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes?
return undefined; // Lazy node: unloaded, currently loading, or load error
}
return this.children;
},
/** Return the first child node or null.
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.children ? this.children[0] : null;
},
/** Return the 0-based child index.
* @returns {int}
*/
getIndex: function() {
// return this.parent.children.indexOf(this);
return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7
},
/** Return the hierarchical child index (1-based, e.g. '3.2.4').
* @returns {string}
*/
getIndexHier: function(separator) {
separator = separator || ".";
var res = [];
$.each(this.getParentList(false, true), function(i, o){
res.push(o.getIndex() + 1);
});
return res.join(separator);
},
/** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32".
* @param {boolean} [excludeSelf=false]
* @returns {string}
*/
getKeyPath: function(excludeSelf) {
var path = [],
sep = this.tree.options.keyPathSeparator;
this.visitParents(function(n){
if(n.parent){
path.unshift(n.key);
}
}, !excludeSelf);
return sep + path.join(sep);
},
/** Return the last child of this node or null.
* @returns {FancytreeNode | null}
*/
getLastChild: function() {
return this.children ? this.children[this.children.length - 1] : null;
},
/** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... .
* @returns {int}
*/
getLevel: function() {
var level = 0,
dtn = this.parent;
while( dtn ) {
level++;
dtn = dtn.parent;
}
return level;
},
/** Return the successor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getNextSibling: function() {
// TODO: use indexOf, if available: (not in IE6)
if( this.parent ){
var i, l,
ac = this.parent.children;
for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null
if( ac[i] === this ){
return ac[i+1];
}
}
}
return null;
},
/** Return the parent node (null for the system root node).
* @returns {FancytreeNode | null}
*/
getParent: function() {
// TODO: return null for top-level nodes?
return this.parent;
},
/** Return an array of all parent nodes (top-down).
* @param {boolean} [includeRoot=false] Include the invisible system root node.
* @param {boolean} [includeSelf=false] Include the node itself.
* @returns {FancytreeNode[]}
*/
getParentList: function(includeRoot, includeSelf) {
var l = [],
dtn = includeSelf ? this : this.parent;
while( dtn ) {
if( includeRoot || dtn.parent ){
l.unshift(dtn);
}
dtn = dtn.parent;
}
return l;
},
/** Return the predecessor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getPrevSibling: function() {
if( this.parent ){
var i, l,
ac = this.parent.children;
for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null
if( ac[i] === this ){
return ac[i-1];
}
}
}
return null;
},
/** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded).
* @returns {boolean | undefined}
*/
hasChildren: function() {
if(this.lazy){
if(this.children == null ){
// null or undefined: Not yet loaded
return undefined;
}else if(this.children.length === 0){
// Loaded, but response was empty
return false;
}else if(this.children.length === 1 && this.children[0].isStatusNode() ){
// Currently loading or load error
return undefined;
}
return true;
}
return !!( this.children && this.children.length );
},
/** Return true if node has keyboard focus.
* @returns {boolean}
*/
hasFocus: function() {
return (this.tree.hasFocus() && this.tree.focusNode === this);
},
/** Write to browser console if debugLevel >= 1 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.tree.options.debugLevel >= 1 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/** Return true if node is active (see also FancytreeNode#isSelected).
* @returns {boolean}
*/
isActive: function() {
return (this.tree.activeNode === this);
},
/** Return true if node is a direct child of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isChildOf: function(otherNode) {
return (this.parent && this.parent === otherNode);
},
/** Return true, if node is a direct or indirect sub node of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isDescendantOf: function(otherNode) {
if(!otherNode || otherNode.tree !== this.tree){
return false;
}
var p = this.parent;
while( p ) {
if( p === otherNode ){
return true;
}
p = p.parent;
}
return false;
},
/** Return true if node is expanded.
* @returns {boolean}
*/
isExpanded: function() {
return !!this.expanded;
},
/** Return true if node is the first node of its parent's children.
* @returns {boolean}
*/
isFirstSibling: function() {
var p = this.parent;
return !p || p.children[0] === this;
},
/** Return true if node is a folder, i.e. has the node.folder attribute set.
* @returns {boolean}
*/
isFolder: function() {
return !!this.folder;
},
/** Return true if node is the last node of its parent's children.
* @returns {boolean}
*/
isLastSibling: function() {
var p = this.parent;
return !p || p.children[p.children.length-1] === this;
},
/** Return true if node is lazy (even if data was already loaded)
* @returns {boolean}
*/
isLazy: function() {
return !!this.lazy;
},
/** Return true if node is lazy and loaded. For non-lazy nodes always return true.
* @returns {boolean}
*/
isLoaded: function() {
return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node
},
/** Return true if children are currently beeing loaded, i.e. a Ajax request is pending.
* @returns {boolean}
*/
isLoading: function() {
return !!this._isLoading;
},
/**
* @deprecated since v2.4.0: Use isRootNode() instead
*/
isRoot: function() {
return this.isRootNode();
},
/** Return true if this is the (invisible) system root node.
* @returns {boolean}
*/
isRootNode: function() {
return (this.tree.rootNode === this);
},
/** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive).
* @returns {boolean}
*/
isSelected: function() {
return !!this.selected;
},
/** Return true if this node is a temporarily generated system node like
* 'loading', or 'error' (node.statusNodeType contains the type).
* @returns {boolean}
*/
isStatusNode: function() {
return !!this.statusNodeType;
},
/** Return true if this a top level node, i.e. a direct child of the (invisible) system root node.
* @returns {boolean}
*/
isTopLevel: function() {
return (this.tree.rootNode === this.parent);
},
/** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false.
* @returns {boolean}
*/
isUndefined: function() {
return this.hasChildren() === undefined; // also checks if the only child is a status node
},
/** Return true if all parent nodes are expanded. Note: this does not check
* whether the node is scrolled into the visible part of the screen.
* @returns {boolean}
*/
isVisible: function() {
var i, l,
parents = this.getParentList(false, false);
for(i=0, l=parents.length; i<l; i++){
if( ! parents[i].expanded ){ return false; }
}
return true;
},
/** Deprecated.
* @deprecated since 2014-02-16: use load() instead.
*/
lazyLoad: function(discard) {
this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead.");
return this.load(discard);
},
/**
* Load all children of a lazy node if neccessary. The *expanded* state is maintained.
* @param {boolean} [forceReload=false] Pass true to discard any existing nodes before.
* @returns {$.Promise}
*/
load: function(forceReload) {
var res, source,
that = this;
_assert( this.isLazy(), "load() requires a lazy node" );
// _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" );
if( !forceReload && !this.isUndefined() ) {
return _getResolvedPromise(this);
}
if( this.isLoaded() ){
this.resetLazy(); // also collapses
}
// This method is also called by setExpanded() and loadKeyPath(), so we
// have to avoid recursion.
source = this.tree._triggerNodeEvent("lazyLoad", this);
if( source === false ) { // #69
return _getResolvedPromise(this);
}
_assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
res = this.tree._callHook("nodeLoadChildren", this, source);
if( this.expanded ) {
res.always(function(){
that.render();
});
}
return res;
},
/** Expand all parents and optionally scroll into visible area as neccessary.
* Promise is resolved, when lazy loading and animations are done.
* @param {object} [opts] passed to `setExpanded()`.
* Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true}
* @returns {$.Promise}
*/
makeVisible: function(opts) {
var i,
that = this,
deferreds = [],
dfd = new $.Deferred(),
parents = this.getParentList(false, false),
len = parents.length,
effects = !(opts && opts.noAnimation === true),
scroll = !(opts && opts.scrollIntoView === false);
// Expand bottom-up, so only the top node is animated
for(i = len - 1; i >= 0; i--){
// that.debug("pushexpand" + parents[i]);
deferreds.push(parents[i].setExpanded(true, opts));
}
$.when.apply($, deferreds).done(function(){
// All expands have finished
// that.debug("expand DONE", scroll);
if( scroll ){
that.scrollIntoView(effects).done(function(){
// that.debug("scroll DONE");
dfd.resolve();
});
} else {
dfd.resolve();
}
});
return dfd.promise();
},
/** Move this node to targetNode.
* @param {FancytreeNode} targetNode
* @param {string} mode <pre>
* 'child': append this node as last child of targetNode.
* This is the default. To be compatble with the D'n'd
* hitMode, we also accept 'over'.
* 'before': add this node as sibling before targetNode.
* 'after': add this node as sibling after targetNode.</pre>
* @param {function} [map] optional callback(FancytreeNode) to allow modifcations
*/
moveTo: function(targetNode, mode, map) {
if(mode === undefined || mode === "over"){
mode = "child";
}
var pos,
prevParent = this.parent,
targetParent = (mode === "child") ? targetNode : targetNode.parent;
if(this === targetNode){
return;
}else if( !this.parent ){
throw "Cannot move system root";
}else if( targetParent.isDescendantOf(this) ){
throw "Cannot move a node to its own descendant";
}
// Unlink this node from current parent
if( this.parent.children.length === 1 ) {
if( this.parent === targetParent ){
return; // #258
}
this.parent.children = this.parent.lazy ? [] : null;
this.parent.expanded = false;
} else {
pos = $.inArray(this, this.parent.children);
_assert(pos >= 0);
this.parent.children.splice(pos, 1);
}
// Remove from source DOM parent
// if(this.parent.ul){
// this.parent.ul.removeChild(this.li);
// }
// Insert this node to target parent's child list
this.parent = targetParent;
if( targetParent.hasChildren() ) {
switch(mode) {
case "child":
// Append to existing target children
targetParent.children.push(this);
break;
case "before":
// Insert this node before target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0);
targetParent.children.splice(pos, 0, this);
break;
case "after":
// Insert this node after target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0);
targetParent.children.splice(pos+1, 0, this);
break;
default:
throw "Invalid mode " + mode;
}
} else {
targetParent.children = [ this ];
}
// Parent has no <ul> tag yet:
// if( !targetParent.ul ) {
// // This is the parent's first child: create UL tag
// // (Hidden, because it will be
// targetParent.ul = document.createElement("ul");
// targetParent.ul.style.display = "none";
// targetParent.li.appendChild(targetParent.ul);
// }
// // Issue 319: Add to target DOM parent (only if node was already rendered(expanded))
// if(this.li){
// targetParent.ul.appendChild(this.li);
// }^
// Let caller modify the nodes
if( map ){
targetNode.visit(map, true);
}
// Handle cross-tree moves
if( this.tree !== targetNode.tree ) {
// Fix node.tree for all source nodes
// _assert(false, "Cross-tree move is not yet implemented.");
this.warn("Cross-tree moveTo is experimantal!");
this.visit(function(n){
// TODO: fix selection state and activation, ...
n.tree = targetNode.tree;
}, true);
}
// A collaposed node won't re-render children, so we have to remove it manually
// if( !targetParent.expanded ){
// prevParent.ul.removeChild(this.li);
// }
// Update HTML markup
if( !prevParent.isDescendantOf(targetParent)) {
prevParent.render();
}
if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) {
targetParent.render();
}
// TODO: fix selection state
// TODO: fix active state
/*
var tree = this.tree;
var opts = tree.options;
var pers = tree.persistence;
// Always expand, if it's below minExpandLevel
// tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel());
if ( opts.minExpandLevel >= ftnode.getLevel() ) {
// tree.logDebug ("Force expand for %o", ftnode);
this.bExpanded = true;
}
// In multi-hier mode, update the parents selection state
// DT issue #82: only if not initializing, because the children may not exist yet
// if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing )
// ftnode._fixSelectionState();
// In multi-hier mode, update the parents selection state
if( ftnode.bSelected && opts.selectMode==3 ) {
var p = this;
while( p ) {
if( !p.hasSubSel )
p._setSubSel(true);
p = p.parent;
}
}
// render this node and the new child
if ( tree.bEnableUpdate )
this.render();
return ftnode;
*/
},
/** Set focus relative to this node and optionally activate.
*
* @param {number} where The keyCode that would normally trigger this move,
* e.g. `$.ui.keyCode.LEFT` would collapse the node if it
* is expanded or move to the parent oterwise.
* @param {boolean} [activate=true]
* @returns {$.Promise}
*/
// navigate: function(where, activate) {
// console.time("navigate")
// this._navigate(where, activate)
// console.timeEnd("navigate")
// },
navigate: function(where, activate) {
var i, parents,
handled = true,
KC = $.ui.keyCode,
sib = null;
// Navigate to node
function _goto(n){
if( n ){
try { n.makeVisible(); } catch(e) {} // #272
// Node may still be hidden by a filter
if( ! $(n.span).is(":visible") ) {
n.debug("Navigate: skipping hidden node");
n.navigate(where, activate);
return;
}
return activate === false ? n.setFocus() : n.setActive();
}
}
switch( where ) {
case KC.BACKSPACE:
if( this.parent && this.parent.parent ) {
_goto(this.parent);
}
break;
case KC.LEFT:
if( this.expanded ) {
this.setExpanded(false);
_goto(this);
} else if( this.parent && this.parent.parent ) {
_goto(this.parent);
}
break;
case KC.RIGHT:
if( !this.expanded && (this.children || this.lazy) ) {
this.setExpanded();
_goto(this);
} else if( this.children && this.children.length ) {
_goto(this.children[0]);
}
break;
case KC.UP:
sib = this.getPrevSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getPrevSibling();
}
while( sib && sib.expanded && sib.children && sib.children.length ) {
sib = sib.children[sib.children.length - 1];
}
if( !sib && this.parent && this.parent.parent ){
sib = this.parent;
}
_goto(sib);
break;
case KC.DOWN:
if( this.expanded && this.children && this.children.length ) {
sib = this.children[0];
} else {
parents = this.getParentList(false, true);
for(i=parents.length-1; i>=0; i--) {
sib = parents[i].getNextSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getNextSibling();
}
if( sib ){ break; }
}
}
_goto(sib);
break;
default:
handled = false;
}
},
/**
* Remove this node (not allowed for system root).
*/
remove: function() {
return this.parent.removeChild(this);
},
/**
* Remove childNode from list of direct children.
* @param {FancytreeNode} childNode
*/
removeChild: function(childNode) {
return this.tree._callHook("nodeRemoveChild", this, childNode);
},
/**
* Remove all child nodes and descendents. This converts the node into a leaf.<br>
* If this was a lazy node, it is still considered 'loaded'; call node.resetLazy()
* in order to trigger lazyLoad on next expand.
*/
removeChildren: function() {
return this.tree._callHook("nodeRemoveChildren", this);
},
/**
* This method renders and updates all HTML markup that is required
* to display this node in its current state.<br>
* Note:
* <ul>
* <li>It should only be neccessary to call this method after the node object
* was modified by direct access to its properties, because the common
* API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...)
* already handle this.
* <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus}
* are implied. If changes are more local, calling only renderTitle() or
* renderStatus() may be sufficient and faster.
* <li>If a node was created/removed, node.render() must be called <i>on the parent</i>.
* </ul>
*
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
*/
render: function(force, deep) {
return this.tree._callHook("nodeRender", this, force, deep);
},
/** Create HTML markup for the node's outer <span> (expander, checkbox, icon, and title).
* @see Fancytree_Hooks#nodeRenderTitle
*/
renderTitle: function() {
return this.tree._callHook("nodeRenderTitle", this);
},
/** Update element's CSS classes according to node state.
* @see Fancytree_Hooks#nodeRenderStatus
*/
renderStatus: function() {
return this.tree._callHook("nodeRenderStatus", this);
},
/**
* Remove all children, collapse, and set the lazy-flag, so that the lazyLoad
* event is triggered on next expand.
*/
resetLazy: function() {
this.removeChildren();
this.expanded = false;
this.lazy = true;
this.children = undefined;
this.renderStatus();
},
/** Schedule activity for delayed execution (cancel any pending request).
* scheduleAction('cancel') will only cancel a pending request (if any).
* @param {string} mode
* @param {number} ms
*/
scheduleAction: function(mode, ms) {
if( this.tree.timer ) {
clearTimeout(this.tree.timer);
// this.tree.debug("clearTimeout(%o)", this.tree.timer);
}
this.tree.timer = null;
var self = this; // required for closures
switch (mode) {
case "cancel":
// Simply made sure that timer was cleared
break;
case "expand":
this.tree.timer = setTimeout(function(){
self.tree.debug("setTimeout: trigger expand");
self.setExpanded(true);
}, ms);
break;
case "activate":
this.tree.timer = setTimeout(function(){
self.tree.debug("setTimeout: trigger activate");
self.setActive(true);
}, ms);
break;
default:
throw "Invalid mode " + mode;
}
// this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer);
},
/**
*
* @param {boolean | PlainObject} [effects=false] animation options.
* @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in
* any case, even if `this` is outside the scroll pane.
* @returns {$.Promise}
*/
scrollIntoView: function(effects, options) {
if( options !== undefined && _isNode(options) ) {
this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead.");
options = {topNode: options};
}
// this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent);
// this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container;
var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop,
opts = $.extend({
effects: (effects === true) ? {duration: 200, queue: false} : effects,
scrollOfs: this.tree.options.scrollOfs,
scrollParent: this.tree.options.scrollParent || this.tree.$container,
topNode: null
}, options),
dfd = new $.Deferred(),
that = this,
nodeHeight = $(this.span).height(),
$container = $(opts.scrollParent),
topOfs = opts.scrollOfs.top || 0,
bottomOfs = opts.scrollOfs.bottom || 0,
containerHeight = $container.height(),// - topOfs - bottomOfs,
scrollTop = $container.scrollTop(),
$animateTarget = $container,
isParentWindow = $container[0] === window,
topNode = opts.topNode || null,
newScrollTop = null;
// this.debug("scrollIntoView(), scrollTop=", scrollTop, opts.scrollOfs);
// _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets
if( !$(this.span).is(":visible") ) {
// We cannot calc offsets for hidden elements
this.warn("scrollIntoView(): node is invisible.");
return _getResolvedPromise();
}
if( isParentWindow ) {
nodeY = $(this.span).offset().top;
topNodeY = (topNode && topNode.span) ? $(topNode.span).offset().top : 0;
$animateTarget = $("html,body");
} else {
_assert($container[0] !== document && $container[0] !== document.body, "scrollParent should be an simple element or `window`, not document or body.");
containerOffsetTop = $container.offset().top,
nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent
topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0;
horzScrollbarHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight));
containerHeight -= horzScrollbarHeight;
}
// this.debug(" scrollIntoView(), nodeY=", nodeY, "containerHeight=", containerHeight);
if( nodeY < (scrollTop + topOfs) ){
// Node is above visible container area
newScrollTop = nodeY - topOfs;
// this.debug(" scrollIntoView(), UPPER newScrollTop=", newScrollTop);
}else if((nodeY + nodeHeight) > (scrollTop + containerHeight - bottomOfs)){
newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs;
// this.debug(" scrollIntoView(), LOWER newScrollTop=", newScrollTop);
// If a topNode was passed, make sure that it is never scrolled
// outside the upper border
if(topNode){
_assert(topNode.isRoot() || $(topNode.span).is(":visible"), "topNode must be visible");
if( topNodeY < newScrollTop ){
newScrollTop = topNodeY - topOfs;
// this.debug(" scrollIntoView(), TOP newScrollTop=", newScrollTop);
}
}
}
if(newScrollTop !== null){
// this.debug(" scrollIntoView(), SET newScrollTop=", newScrollTop);
if(opts.effects){
opts.effects.complete = function(){
dfd.resolveWith(that);
};
$animateTarget.stop(true).animate({
scrollTop: newScrollTop
}, opts.effects);
}else{
$animateTarget[0].scrollTop = newScrollTop;
dfd.resolveWith(this);
}
}else{
dfd.resolveWith(this);
}
return dfd.promise();
},
/**Activate this node.
* @param {boolean} [flag=true] pass false to deactivate
* @param {object} [opts] additional options. Defaults to {noEvents: false}
* @returns {$.Promise}
*/
setActive: function(flag, opts){
return this.tree._callHook("nodeSetActive", this, flag, opts);
},
/**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done.
* @param {boolean} [flag=true] pass false to collapse
* @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
* @returns {$.Promise}
*/
setExpanded: function(flag, opts){
return this.tree._callHook("nodeSetExpanded", this, flag, opts);
},
/**Set keyboard focus to this node.
* @param {boolean} [flag=true] pass false to blur
* @see Fancytree#setFocus
*/
setFocus: function(flag){
return this.tree._callHook("nodeSetFocus", this, flag);
},
/**Select this node, i.e. check the checkbox.
* @param {boolean} [flag=true] pass false to deselect
*/
setSelected: function(flag){
return this.tree._callHook("nodeSetSelected", this, flag);
},
/**Mark a lazy node as 'error', 'loading', or 'ok'.
* @param {string} status 'error', 'ok'
* @param {string} [message]
* @param {string} [details]
*/
setStatus: function(status, message, details){
return this.tree._callHook("nodeSetStatus", this, status, message, details);
},
/**Rename this node.
* @param {string} title
*/
setTitle: function(title){
this.title = title;
this.renderTitle();
},
/**Sort child list by title.
* @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title).
* @param {boolean} [deep=false] pass true to sort all descendant nodes
*/
sortChildren: function(cmp, deep) {
var i,l,
cl = this.children;
if( !cl ){
return;
}
cmp = cmp || function(a, b) {
var x = a.title.toLowerCase(),
y = b.title.toLowerCase();
return x === y ? 0 : x > y ? 1 : -1;
};
cl.sort(cmp);
if( deep ){
for(i=0, l=cl.length; i<l; i++){
if( cl[i].children ){
cl[i].sortChildren(cmp, "$norender$");
}
}
}
if( deep !== "$norender$" ){
this.render();
}
},
/** Convert node (or whole branch) into a plain object.
*
* The result is compatible with node.addChildren().
*
* @param {boolean} [recursive=false] include child nodes
* @param {function} [callback] callback(dict) is called for every node, in order to allow modifications
* @returns {NodeData}
*/
toDict: function(recursive, callback) {
var i, l, node,
dict = {},
self = this;
$.each(NODE_ATTRS, function(i, a){
if(self[a] || self[a] === false){
dict[a] = self[a];
}
});
if(!$.isEmptyObject(this.data)){
dict.data = $.extend({}, this.data);
if($.isEmptyObject(dict.data)){
delete dict.data;
}
}
if( callback ){
callback(dict);
}
if( recursive ) {
if(this.hasChildren()){
dict.children = [];
for(i=0, l=this.children.length; i<l; i++ ){
node = this.children[i];
if( !node.isStatusNode() ){
dict.children.push(node.toDict(true, callback));
}
}
}else{
// dict.children = null;
}
}
return dict;
},
/** Flip expanded status. */
toggleExpanded: function(){
return this.tree._callHook("nodeToggleExpanded", this);
},
/** Flip selection status. */
toggleSelected: function(){
return this.tree._callHook("nodeToggleSelected", this);
},
toString: function() {
return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>";
},
/** Call fn(node) for all child nodes.<br>
* Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visit: function(fn, includeSelf) {
var i, l,
res = true,
children = this.children;
if( includeSelf === true ) {
res = fn(this);
if( res === false || res === "skip" ){
return res;
}
}
if(children){
for(i=0, l=children.length; i<l; i++){
res = children[i].visit(fn, true);
if( res === false ){
break;
}
}
}
return res;
},
/** Call fn(node) for all child nodes and recursively load lazy children.<br>
* <b>Note:</b> If you need this method, you probably should consider to review
* your architecture! Recursivley loading nodes is a perfect way for lazy
* programmers to flood the server with requests ;-)
*
* @param {function} [fn] optional callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {$.Promise}
*/
visitAndLoad: function(fn, includeSelf, _recursion) {
var dfd, res, loaders,
node = this;
// node.debug("visitAndLoad");
if( fn && includeSelf === true ) {
res = fn(node);
if( res === false || res === "skip" ) {
return _recursion ? res : _getResolvedPromise();
}
}
if( !node.children && !node.lazy ) {
return _getResolvedPromise();
}
dfd = new $.Deferred();
loaders = [];
// node.debug("load()...");
node.load().done(function(){
// node.debug("load()... done.");
for(var i=0, l=node.children.length; i<l; i++){
res = node.children[i].visitAndLoad(fn, true, true);
if( res === false ) {
dfd.reject();
break;
} else if ( res !== "skip" ) {
loaders.push(res); // Add promise to the list
}
}
$.when.apply(this, loaders).then(function(){
dfd.resolve();
});
});
return dfd.promise();
},
/** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br>
* Stop iteration, if fn() returns false.<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visitParents: function(fn, includeSelf) {
// Visit parent nodes (bottom up)
if(includeSelf && fn(this) === false){
return false;
}
var p = this.parent;
while( p ) {
if(fn(p) === false){
return false;
}
p = p.parent;
}
return true;
},
/** Write warning to browser console (prepending node info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
};
/* *****************************************************************************
* Fancytree
*/
/**
* Construct a new tree object.
*
* @class Fancytree
* @classdesc The controller behind a fancytree.
* This class also contains 'hook methods': see {@link Fancytree_Hooks}.
*
* @param {Widget} widget
*
* @property {FancytreeOptions} options
* @property {FancytreeNode} rootNode
* @property {FancytreeNode} activeNode
* @property {FancytreeNode} focusNode
* @property {jQueryObject} $div
* @property {object} widget
* @property {object} ext
* @property {object} data
* @property {object} options
* @property {string} _id
* @property {string} statusClassPropName
* @property {string} ariaPropName
* @property {string} nodeContainerAttrName
* @property {string} $container
* @property {FancytreeNode} lastSelectedNode
*/
function Fancytree(widget) {
this.widget = widget;
this.$div = widget.element;
this.options = widget.options;
if( this.options ) {
if( $.isFunction(this.options.lazyload ) && !$.isFunction(this.options.lazyLoad) ) {
this.options.lazyLoad = function() {
FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead.");
return widget.options.lazyload.apply(this, arguments);
};
}
if( $.isFunction(this.options.loaderror) ) {
$.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead.");
}
if( this.options.fx !== undefined ) {
FT.warn("The 'fx' options was replaced by 'toggleEffect' since 2014-11-30.");
}
}
this.ext = {}; // Active extension instances
// allow to init tree.data.foo from <div data-foo=''>
this.data = _getElementDataAsDict(this.$div);
this._id = $.ui.fancytree._nextId++;
this._ns = ".fancytree-" + this._id; // append for namespaced events
this.activeNode = null;
this.focusNode = null;
this._hasFocus = null;
this.lastSelectedNode = null;
this.systemFocusElement = null;
this.lastQuicksearchTerm = "";
this.lastQuicksearchTime = 0;
this.statusClassPropName = "span";
this.ariaPropName = "li";
this.nodeContainerAttrName = "li";
// Remove previous markup if any
this.$div.find(">ul.fancytree-container").remove();
// Create a node without parent.
var fakeParent = { tree: this },
$ul;
this.rootNode = new FancytreeNode(fakeParent, {
title: "root",
key: "root_" + this._id,
children: null,
expanded: true
});
this.rootNode.parent = null;
// Create root markup
$ul = $("<ul>", {
"class": "ui-fancytree fancytree-container"
}).appendTo(this.$div);
this.$container = $ul;
this.rootNode.ul = $ul[0];
if(this.options.debugLevel == null){
this.options.debugLevel = FT.debugLevel;
}
// Add container to the TAB chain
// See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
if(this.options.aria){
this.$container
.attr("role", "tree")
.attr("aria-multiselectable", true);
}
}
Fancytree.prototype = /** @lends Fancytree# */{
/* Return a context object that can be re-used for _callHook().
* @param {Fancytree | FancytreeNode | EventData} obj
* @param {Event} originalEvent
* @param {Object} extra
* @returns {EventData}
*/
_makeHookContext: function(obj, originalEvent, extra) {
var ctx, tree;
if(obj.node !== undefined){
// obj is already a context object
if(originalEvent && obj.originalEvent !== originalEvent){
$.error("invalid args");
}
ctx = obj;
}else if(obj.tree){
// obj is a FancytreeNode
tree = obj.tree;
ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent };
}else if(obj.widget){
// obj is a Fancytree
ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent };
}else{
$.error("invalid args");
}
if(extra){
$.extend(ctx, extra);
}
return ctx;
},
/* Trigger a hook function: funcName(ctx, [...]).
*
* @param {string} funcName
* @param {Fancytree|FancytreeNode|EventData} contextObject
* @param {any} [_extraArgs] optional additional arguments
* @returns {any}
*/
_callHook: function(funcName, contextObject, _extraArgs) {
var ctx = this._makeHookContext(contextObject),
fn = this[funcName],
args = Array.prototype.slice.call(arguments, 2);
if(!$.isFunction(fn)){
$.error("_callHook('" + funcName + "') is not a function");
}
args.unshift(ctx);
// this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args);
return fn.apply(this, args);
},
/* Check if current extensions dependencies are met and throw an error if not.
*
* This method may be called inside the `treeInit` hook for custom extensions.
*
* @param {string} extension name of the required extension
* @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present
* @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter)
* @param {string} [message] optional error message (defaults to a descriptve error message)
*/
_requireExtension: function(name, required, before, message) {
before = !!before;
var thisName = this._local.name,
extList = this.options.extensions,
isBefore = $.inArray(name, extList) < $.inArray(thisName, extList),
isMissing = required && this.ext[name] == null,
badOrder = !isMissing && before != null && (before !== isBefore);
_assert(thisName && thisName !== name);
if( isMissing || badOrder ){
if( !message ){
if( isMissing || required ){
message = "'" + thisName + "' extension requires '" + name + "'";
if( badOrder ){
message += " to be registered " + (before ? "before" : "after") + " itself";
}
}else{
message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`";
}
}
$.error(message);
return false;
}
return true;
},
/** Activate node with a given key and fire focus and activate events.
*
* A prevously activated node will be deactivated.
* If activeVisible option is set, all parents will be expanded as necessary.
* Pass key = false, to deactivate the current node only.
* @param {string} key
* @returns {FancytreeNode} activated node (null, if not found)
*/
activateKey: function(key) {
var node = this.getNodeByKey(key);
if(node){
node.setActive();
}else if(this.activeNode){
this.activeNode.setActive(false);
}
return node;
},
/** (experimental)
*
* @param {Array} patchList array of [key, NodePatch] arrays
* @returns {$.Promise} resolved, when all patches have been applied
* @see TreePatch
*/
applyPatch: function(patchList) {
var dfd, i, p2, key, patch, node,
patchCount = patchList.length,
deferredList = [];
for(i=0; i<patchCount; i++){
p2 = patchList[i];
_assert(p2.length === 2, "patchList must be an array of length-2-arrays");
key = p2[0];
patch = p2[1];
node = (key === null) ? this.rootNode : this.getNodeByKey(key);
if(node){
dfd = new $.Deferred();
deferredList.push(dfd);
node.applyPatch(patch).always(_makeResolveFunc(dfd, node));
}else{
this.warn("could not find node with key '" + key + "'");
}
}
// Return a promise that is resolved, when ALL patches were applied
return $.when.apply($, deferredList).promise();
},
/* TODO: implement in dnd extension
cancelDrag: function() {
var dd = $.ui.ddmanager.current;
if(dd){
dd.cancel();
}
},
*/
/** Return the number of nodes.
* @returns {integer}
*/
count: function() {
return this.rootNode.countChildren();
},
/** Write to browser console if debugLevel >= 2 (prepending tree name)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.options.debugLevel >= 2 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
// TODO: disable()
// TODO: enable()
// TODO: enableUpdate()
/** Find the next visible node that starts with `match`, starting at `startNode`
* and wrap-around at the end.
*
* @param {string|function} match
* @param {FancytreeNode} [startNode] defaults to first node
* @returns {FancytreeNode} matching node or null
*/
findNextNode: function(match, startNode, visibleOnly) {
var stopNode = null,
parentChildren = startNode.parent.children,
matchingNode = null,
walkVisible = function(parent, idx, fn) {
var i, grandParent,
parentChildren = parent.children,
siblingCount = parentChildren.length,
node = parentChildren[idx];
// visit node itself
if( node && fn(node) === false ) {
return false;
}
// visit descendants
if( node && node.children && node.expanded ) {
if( walkVisible(node, 0, fn) === false ) {
return false;
}
}
// visit subsequent siblings
for( i = idx + 1; i < siblingCount; i++ ) {
if( walkVisible(parent, i, fn) === false ) {
return false;
}
}
// visit parent's subsequent siblings
grandParent = parent.parent;
if( grandParent ) {
return walkVisible(grandParent, grandParent.children.indexOf(parent) + 1, fn);
} else {
// wrap-around: restart with first node
return walkVisible(parent, 0, fn);
}
};
match = (typeof match === "string") ? _makeNodeTitleStartMatcher(match) : match;
startNode = startNode || this.getFirstChild();
walkVisible(startNode.parent, parentChildren.indexOf(startNode), function(node){
// Stop iteration if we see the start node a second time
if( node === stopNode ) {
return false;
}
stopNode = stopNode || node;
// Ignore nodes hidden by a filter
if( ! $(node.span).is(":visible") ) {
node.debug("quicksearch: skipping hidden node");
return;
}
// Test if we found a match, but search for a second match if this
// was the currently active node
if( match(node) ) {
// node.debug("quicksearch match " + node.title, startNode);
matchingNode = node;
if( matchingNode !== startNode ) {
return false;
}
}
});
return matchingNode;
},
// TODO: fromDict
/**
* Generate INPUT elements that can be submitted with html forms.
*
* In selectMode 3 only the topmost selected nodes are considered, unless
* `opts.stopOnParents: false` is passed.
*
* @param {boolean | string} [selected=true] Pass false to disable, pass a string to overide the field name (default: 'ft_ID[]')
* @param {boolean | string} [active=true] Pass false to disable, pass a string to overide the field name (default: 'ft_ID_active')
* @param {object} [opts] default { stopOnParents: true }
*/
generateFormElements: function(selected, active, opts) {
// TODO: test case
opts = opts || {};
var nodeList,
selectedName = (typeof selected === "string") ? selected : "ft_" + this._id + "[]",
activeName = (typeof active === "string") ? active : "ft_" + this._id + "_active",
id = "fancytree_result_" + this._id,
$result = $("#" + id),
stopOnParents = this.options.selectMode === 3 && opts.stopOnParents !== false;
if($result.length){
$result.empty();
}else{
$result = $("<div>", {
id: id
}).hide().insertAfter(this.$container);
}
if(selected !== false){
nodeList = this.getSelectedNodes(stopOnParents);
$.each(nodeList, function(idx, node){
$result.append($("<input>", {
type: "checkbox",
name: selectedName,
value: node.key,
checked: true
}));
});
}
if(active !== false && this.activeNode){
$result.append($("<input>", {
type: "radio",
name: activeName,
value: this.activeNode.key,
checked: true
}));
}
},
/**
* Return the currently active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.activeNode;
},
/** Return the first top level node if any (not the invisible root node).
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.rootNode.getFirstChild();
},
/**
* Return node that has keyboard focus or null.
* @returns {FancytreeNode}
*/
getFocusNode: function() {
return this.focusNode;
},
/**
* Return node with a given key or null if not found.
* @param {string} key
* @param {FancytreeNode} [searchRoot] only search below this node
* @returns {FancytreeNode | null}
*/
getNodeByKey: function(key, searchRoot) {
// Search the DOM by element ID (assuming this is faster than traversing all nodes).
// $("#...") has problems, if the key contains '.', so we use getElementById()
var el, match;
if(!searchRoot){
el = document.getElementById(this.options.idPrefix + key);
if( el ){
return el.ftnode ? el.ftnode : null;
}
}
// Not found in the DOM, but still may be in an unrendered part of tree
// TODO: optimize with specialized loop
// TODO: consider keyMap?
searchRoot = searchRoot || this.rootNode;
match = null;
searchRoot.visit(function(node){
// window.console.log("getNodeByKey(" + key + "): ", node.key);
if(node.key === key) {
match = node;
return false;
}
}, true);
return match;
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.rootNode;
},
/**
* Return an array of selected nodes.
* @param {boolean} [stopOnParents=false] only return the topmost selected
* node (useful with selectMode 3)
* @returns {FancytreeNode[]}
*/
getSelectedNodes: function(stopOnParents) {
var nodeList = [];
this.rootNode.visit(function(node){
if( node.selected ) {
nodeList.push(node);
if( stopOnParents === true ){
return "skip"; // stop processing this branch
}
}
});
return nodeList;
},
/** Return true if the tree control has keyboard focus
* @returns {boolean}
*/
hasFocus: function(){
return !!this._hasFocus;
},
/** Write to browser console if debugLevel >= 1 (prepending tree name)
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.options.debugLevel >= 1 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/*
TODO: isInitializing: function() {
return ( this.phase=="init" || this.phase=="postInit" );
},
TODO: isReloading: function() {
return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound;
},
TODO: isUserEvent: function() {
return ( this.phase=="userEvent" );
},
*/
/**
* Make sure that a node with a given ID is loaded, by traversing - and
* loading - its parents. This method is ment for lazy hierarchies.
* A callback is executed for every node as we go.
* @example
* tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
* if(status === "loaded") {
* console.log("loaded intermiediate node " + node);
* }else if(status === "ok") {
* node.activate();
* }
* });
*
* @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7')
* @param {function} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error')
* @returns {$.Promise}
*/
loadKeyPath: function(keyPathList, callback, _rootNode) {
var deferredList, dfd, i, path, key, loadMap, node, root, segList,
sep = this.options.keyPathSeparator,
self = this;
if(!$.isArray(keyPathList)){
keyPathList = [keyPathList];
}
// Pass 1: handle all path segments for nodes that are already loaded
// Collect distinct top-most lazy nodes in a map
loadMap = {};
for(i=0; i<keyPathList.length; i++){
root = _rootNode || this.rootNode;
path = keyPathList[i];
// strip leading slash
if(path.charAt(0) === sep){
path = path.substr(1);
}
// traverse and strip keys, until we hit a lazy, unloaded node
segList = path.split(sep);
while(segList.length){
key = segList.shift();
// node = _findDirectChild(root, key);
node = root._findDirectChild(key);
if(!node){
this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")");
callback.call(this, key, "error");
break;
}else if(segList.length === 0){
callback.call(this, node, "ok");
break;
}else if(!node.lazy || (node.hasChildren() !== undefined )){
callback.call(this, node, "loaded");
root = node;
}else{
callback.call(this, node, "loaded");
// segList.unshift(key);
if(loadMap[key]){
loadMap[key].push(segList.join(sep));
}else{
loadMap[key] = [segList.join(sep)];
}
break;
}
}
}
// alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap));
// Now load all lazy nodes and continue itearation for remaining paths
deferredList = [];
// Avoid jshint warning 'Don't make functions within a loop.':
function __lazyload(key, node, dfd){
callback.call(self, node, "loading");
node.load().done(function(){
self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self));
}).fail(function(errMsg){
self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")");
callback.call(self, node, "error");
dfd.reject();
});
}
for(key in loadMap){
node = root._findDirectChild(key);
// alert("loadKeyPath: lazy node(" + key + ") = " + node);
dfd = new $.Deferred();
deferredList.push(dfd);
__lazyload(key, node, dfd);
}
// Return a promise that is resolved, when ALL paths were loaded
return $.when.apply($, deferredList).promise();
},
/** Re-fire beforeActivate and activate events. */
reactivate: function(setFocus) {
var res,
node = this.activeNode;
if( !node ) {
return _getResolvedPromise();
}
this.activeNode = null; // Force re-activating
res = node.setActive();
if( setFocus ){
node.setFocus();
}
return res;
},
/** Reload tree from source and return a promise.
* @param [source] optional new source (defaults to initial source data)
* @returns {$.Promise}
*/
reload: function(source) {
this._callHook("treeClear", this);
return this._callHook("treeLoad", this, source);
},
/**Render tree (i.e. create DOM elements for all top-level nodes).
* @param {boolean} [force=false] create DOM elemnts, even is parent is collapsed
* @param {boolean} [deep=false]
*/
render: function(force, deep) {
return this.rootNode.render(force, deep);
},
// TODO: selectKey: function(key, select)
// TODO: serializeArray: function(stopOnParents)
/**
* @param {boolean} [flag=true]
*/
setFocus: function(flag) {
return this._callHook("treeSetFocus", this, flag);
},
/**
* Return all nodes as nested list of {@link NodeData}.
*
* @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children)
* @param {function} [callback(node)] Called for every node
* @returns {Array | object}
* @see FancytreeNode#toDict
*/
toDict: function(includeRoot, callback){
var res = this.rootNode.toDict(true, callback);
return includeRoot ? res : res.children;
},
/* Implicitly called for string conversions.
* @returns {string}
*/
toString: function(){
return "<Fancytree(#" + this._id + ")>";
},
/* _trigger a widget event with additional node ctx.
* @see EventData
*/
_triggerNodeEvent: function(type, node, originalEvent, extra) {
// this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx);
var ctx = this._makeHookContext(node, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if(res !== false && ctx.result !== undefined){
return ctx.result;
}
return res;
},
/* _trigger a widget event with additional tree data. */
_triggerTreeEvent: function(type, originalEvent, extra) {
// this.debug("_trigger(" + type + ")", ctx);
var ctx = this._makeHookContext(this, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if(res !== false && ctx.result !== undefined){
return ctx.result;
}
return res;
},
/** Call fn(node) for all nodes.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @returns {boolean} false, if the iterator was stopped.
*/
visit: function(fn) {
return this.rootNode.visit(fn, false);
},
/** Write warning to browser console (prepending tree info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
};
/**
* These additional methods of the {@link Fancytree} class are 'hook functions'
* that can be used and overloaded by extensions.
* (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.)
* @mixin Fancytree_Hooks
*/
$.extend(Fancytree.prototype,
/** @lends Fancytree_Hooks# */
{
/** Default handling for mouse click events.
*
* @param {EventData} ctx
*/
nodeClick: function(ctx) {
// this.tree.logDebug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which);
var activate, expand,
// event = ctx.originalEvent,
targetType = ctx.targetType,
node = ctx.node;
// TODO: use switch
// TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample)
if( targetType === "expander" ) {
// Clicking the expander icon always expands/collapses
this._callHook("nodeToggleExpanded", ctx);
} else if( targetType === "checkbox" ) {
// Clicking the checkbox always (de)selects
this._callHook("nodeToggleSelected", ctx);
if( ctx.options.focusOnSelect ) { // #358
this._callHook("nodeSetFocus", ctx, true);
}
} else {
// Honor `clickFolderMode` for
expand = false;
activate = true;
if( node.folder ) {
switch( ctx.options.clickFolderMode ) {
case 2: // expand only
expand = true;
activate = false;
break;
case 3: // expand and activate
activate = true;
expand = true; //!node.isExpanded();
break;
// else 1 or 4: just activate
}
}
if( activate ) {
this.nodeSetFocus(ctx);
this._callHook("nodeSetActive", ctx, true);
}
if( expand ) {
if(!activate){
// this._callHook("nodeSetFocus", ctx);
}
// this._callHook("nodeSetExpanded", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
}
// Make sure that clicks stop, otherwise <a href='#'> jumps to the top
// if(event.target.localName === "a" && event.target.className === "fancytree-title"){
// event.preventDefault();
// }
// TODO: return promise?
},
/** Collapse all other children of same parent.
*
* @param {EventData} ctx
* @param {object} callOpts
*/
nodeCollapseSiblings: function(ctx, callOpts) {
// TODO: return promise?
var ac, i, l,
node = ctx.node;
if( node.parent ){
ac = node.parent.children;
for (i=0, l=ac.length; i<l; i++) {
if ( ac[i] !== node && ac[i].expanded ){
this._callHook("nodeSetExpanded", ac[i], false, callOpts);
}
}
}
},
/** Default handling for mouse douleclick events.
* @param {EventData} ctx
*/
nodeDblclick: function(ctx) {
// TODO: return promise?
if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) {
// this.nodeSetFocus(ctx);
// this._callHook("nodeSetActive", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
// TODO: prevent text selection on dblclicks
if( ctx.targetType === "title" ) {
ctx.originalEvent.preventDefault();
}
},
/** Default handling for mouse keydown events.
*
* NOTE: this may be called with node == null if tree (but no node) has focus.
* @param {EventData} ctx
*/
nodeKeydown: function(ctx) {
// TODO: return promise?
var matchNode, stamp, res,
event = ctx.originalEvent,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
which = event.which,
whichChar = String.fromCharCode(which),
clean = !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey),
$target = $(event.target),
handled = true,
activate = !(event.ctrlKey || !opts.autoActivate );
// (node || FT).debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
// FT.debug("eventToString", which, '"' + String.fromCharCode(which) + '"', '"' + FT.eventToString(event) + '"');
// Set focus to active (or first node) if no other node has the focus yet
if( !node ){
(this.getActiveNode() || this.getFirstChild()).setFocus();
node = ctx.node = this.focusNode;
node.debug("Keydown force focus on active node");
}
if( opts.quicksearch && clean && /\w/.test(whichChar) && !$target.is(":input:enabled") ) {
// Allow to search for longer streaks if typed in quickly
stamp = new Date().getTime();
if( stamp - tree.lastQuicksearchTime > 500 ) {
tree.lastQuicksearchTerm = "";
}
tree.lastQuicksearchTime = stamp;
tree.lastQuicksearchTerm += whichChar;
// tree.debug("quicksearch find", tree.lastQuicksearchTerm);
matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode());
if( matchNode ) {
matchNode.setActive();
}
event.preventDefault();
return;
}
switch( FT.eventToString(event) ) {
case "+":
case "=": // 187: '+' @ Chrome, Safari
tree.nodeSetExpanded(ctx, true);
break;
case "-":
tree.nodeSetExpanded(ctx, false);
break;
case "space":
if(opts.checkbox){
tree.nodeToggleSelected(ctx);
}else{
tree.nodeSetActive(ctx, true);
}
break;
case "enter":
tree.nodeSetActive(ctx, true);
break;
case "backspace":
case "left":
case "right":
case "up":
case "down":
res = node.navigate(event.which, activate);
break;
default:
handled = false;
}
if(handled){
event.preventDefault();
}
},
// /** Default handling for mouse keypress events. */
// nodeKeypress: function(ctx) {
// var event = ctx.originalEvent;
// },
// /** Trigger lazyLoad event (async). */
// nodeLazyLoad: function(ctx) {
// var node = ctx.node;
// if(this._triggerNodeEvent())
// },
/** Load child nodes (async).
*
* @param {EventData} ctx
* @param {object[]|object|string|$.Promise|function} source
* @returns {$.Promise} The deferred will be resolved as soon as the (ajax)
* data was rendered.
*/
nodeLoadChildren: function(ctx, source) {
var ajax, delay, dfd,
tree = ctx.tree,
node = ctx.node;
if($.isFunction(source)){
source = source();
}
// TOTHINK: move to 'ajax' extension?
if(source.url){
// `source` is an Ajax options object
ajax = $.extend({}, ctx.options.ajax, source);
if(ajax.debugDelay){
// simulate a slow server
delay = ajax.debugDelay;
if($.isArray(delay)){ // random delay range [min..max]
delay = delay[0] + Math.random() * (delay[1] - delay[0]);
}
node.debug("nodeLoadChildren waiting debug delay " + Math.round(delay) + "ms");
ajax.debugDelay = false;
dfd = $.Deferred(function (dfd) {
setTimeout(function () {
$.ajax(ajax)
.done(function () { dfd.resolveWith(this, arguments); })
.fail(function () { dfd.rejectWith(this, arguments); });
}, delay);
});
}else{
dfd = $.ajax(ajax);
}
// Defer the deferred: we want to be able to reject, even if ajax
// resolved ok.
source = new $.Deferred();
dfd.done(function (data, textStatus, jqXHR) {
var errorObj, res;
if(typeof data === "string"){
$.error("Ajax request returned a string (did you get the JSON dataType wrong?).");
}
// postProcess is similar to the standard ajax dataFilter hook,
// but it is also called for JSONP
if( ctx.options.postProcess ){
res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {response: data, error: null, dataType: this.dataType});
if( res.error ) {
errorObj = $.isPlainObject(res.error) ? res.error : {message: res.error};
errorObj = tree._makeHookContext(node, null, errorObj);
source.rejectWith(this, [errorObj]);
return;
}
data = $.isArray(res) ? res : data;
} else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) {
// Process ASPX WebMethod JSON object inside "d" property
data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d;
}
source.resolveWith(this, [data]);
}).fail(function (jqXHR, textStatus, errorThrown) {
var errorObj = tree._makeHookContext(node, null, {
error: jqXHR,
args: Array.prototype.slice.call(arguments),
message: errorThrown,
details: jqXHR.status + ": " + errorThrown
});
source.rejectWith(this, [errorObj]);
});
}
// #383: accept and convert ECMAScript 6 Promise
if( $.isFunction(source.then) && $.isFunction(source["catch"]) ) {
dfd = source;
source = new $.Deferred();
dfd.then(function(value){
source.resolve(value);
}, function(reason){
source.reject(reason);
});
}
if($.isFunction(source.promise)){
// `source` is a deferred, i.e. ajax request
_assert(!node.isLoading());
// node._isLoading = true;
tree.nodeSetStatus(ctx, "loading");
source.done(function (children) {
tree.nodeSetStatus(ctx, "ok");
}).fail(function(error){
var ctxErr;
if (error.node && error.error && error.message) {
// error is already a context object
ctxErr = error;
} else {
ctxErr = tree._makeHookContext(node, null, {
error: error, // it can be jqXHR or any custom error
args: Array.prototype.slice.call(arguments),
message: error ? (error.message || error.toString()) : ""
});
}
if( tree._triggerNodeEvent("loadError", ctxErr, null) !== false ) {
tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details);
}
});
}
// $.when(source) resolves also for non-deferreds
return $.when(source).done(function(children){
var metaData;
if( $.isPlainObject(children) ){
// We got {foo: 'abc', children: [...]}
// Copy extra properties to tree.data.foo
_assert($.isArray(children.children), "source must contain (or be) an array of children");
_assert(node.isRoot(), "source may only be an object for root nodes");
metaData = children;
children = children.children;
delete metaData.children;
$.extend(tree.data, metaData);
}
_assert($.isArray(children), "expected array of children");
node._setChildren(children);
// trigger fancytreeloadchildren
tree._triggerNodeEvent("loadChildren", node);
// }).always(function(){
// node._isLoading = false;
});
},
/** [Not Implemented] */
nodeLoadKeyPath: function(ctx, keyPathList) {
// TODO: implement and improve
// http://code.google.com/p/dynatree/issues/detail?id=222
},
/**
* Remove a single direct child of ctx.node.
* @param {EventData} ctx
* @param {FancytreeNode} childNode dircect child of ctx.node
*/
nodeRemoveChild: function(ctx, childNode) {
var idx,
node = ctx.node,
opts = ctx.options,
subCtx = $.extend({}, ctx, {node: childNode}),
children = node.children;
// FT.debug("nodeRemoveChild()", node.toString(), childNode.toString());
if( children.length === 1 ) {
_assert(childNode === children[0]);
return this.nodeRemoveChildren(ctx);
}
if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){
this.activeNode.setActive(false); // TODO: don't fire events
}
if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveMarkup(subCtx);
this.nodeRemoveChildren(subCtx);
idx = $.inArray(childNode, children);
_assert(idx >= 0);
// Unlink to support GC
childNode.visit(function(n){
n.parent = null;
}, true);
this._callHook("treeRegisterNode", this, false, childNode);
if ( opts.removeNode ){
opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
}
// remove from child list
children.splice(idx, 1);
},
/**Remove HTML markup for all descendents of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveChildMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if(node.ul){
if( node.isRoot() ) {
$(node.ul).empty();
} else {
$(node.ul).remove();
node.ul = null;
}
node.visit(function(n){
n.li = n.ul = null;
});
}
},
/**Remove all descendants of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildren: function(ctx) {
var subCtx,
tree = ctx.tree,
node = ctx.node,
children = node.children,
opts = ctx.options;
// FT.debug("nodeRemoveChildren()", node.toString());
if(!children){
return;
}
if( this.activeNode && this.activeNode.isDescendantOf(node)){
this.activeNode.setActive(false); // TODO: don't fire events
}
if( this.focusNode && this.focusNode.isDescendantOf(node)){
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveChildMarkup(ctx);
// Unlink children to support GC
// TODO: also delete this.children (not possible using visit())
subCtx = $.extend({}, ctx);
node.visit(function(n){
n.parent = null;
tree._callHook("treeRegisterNode", tree, false, n);
if ( opts.removeNode ){
subCtx.node = n;
opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
}
});
if( node.lazy ){
// 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
node.children = [];
} else{
node.children = null;
}
this.nodeRenderStatus(ctx);
},
/**Remove HTML markup for ctx.node and all its descendents.
* @param {EventData} ctx
*/
nodeRemoveMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if(node.li){
$(node.li).remove();
node.li = null;
}
this.nodeRemoveChildMarkup(ctx);
},
/**
* Create `<li><span>..</span> .. </li>` tags for this node.
*
* This method takes care that all HTML markup is created that is required
* to display this node in it's current state.
*
* Call this method to create new nodes, or after the strucuture
* was changed (e.g. after moving this node or adding/removing children)
* nodeRenderTitle() and nodeRenderStatus() are implied.
*
* Note: if a node was created/removed, nodeRender() must be called for the
* parent.
* <code>
* <li id='KEY' ftnode=NODE>
* <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'>
* <span class="fancytree-expander"></span>
* <span class="fancytree-checkbox"></span> // only present in checkbox mode
* <span class="fancytree-icon"></span>
* <a href="#" class="fancytree-title"> Node 1 </a>
* </span>
* <ul> // only present if node has children
* <li id='KEY' ftnode=NODE> child1 ... </li>
* <li id='KEY' ftnode=NODE> child2 ... </li>
* </ul>
* </li>
* </code>
*
* @param {EventData} ctx
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
* @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later
*/
nodeRender: function(ctx, force, deep, collapsed, _recursive) {
/* This method must take care of all cases where the current data mode
* (i.e. node hierarchy) does not match the current markup.
*
* - node was not yet rendered:
* create markup
* - node was rendered: exit fast
* - children have been added
* - childern have been removed
*/
var childLI, childNode1, childNode2, i, l, next, subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
firstTime = false,
parent = node.parent,
isRootNode = !parent,
children = node.children;
// FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString());
if( ! isRootNode && ! parent.ul ) {
// Calling node.collapse on a deep, unrendered node
return;
}
_assert(isRootNode || parent.ul, "parent UL must exist");
// Render the node
if( !isRootNode ){
// Discard markup on force-mode, or if it is not linked to parent <ul>
if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){
if(node.li.parentNode !== node.parent.ul){
// May happen, when a top-level node was dropped over another
this.debug("Unlinking " + node + " (must be child of " + node.parent + ")");
}
// this.debug("nodeRemoveMarkup...");
this.nodeRemoveMarkup(ctx);
}
// Create <li><span /> </li>
// node.debug("render...");
if( !node.li ) {
// node.debug("render... really");
firstTime = true;
node.li = document.createElement("li");
node.li.ftnode = node;
if(aria){
// TODO: why doesn't this work:
// node.li.role = "treeitem";
// $(node.li).attr("role", "treeitem")
// .attr("aria-labelledby", "ftal_" + node.key);
}
if( node.key && opts.generateIds ){
node.li.id = opts.idPrefix + node.key;
}
node.span = document.createElement("span");
node.span.className = "fancytree-node";
if(aria){
$(node.span).attr("aria-labelledby", "ftal_" + node.key);
}
node.li.appendChild(node.span);
// Create inner HTML for the <span> (expander, checkbox, icon, and title)
this.nodeRenderTitle(ctx);
// Allow tweaking and binding, after node was created for the first time
if ( opts.createNode ){
opts.createNode.call(tree, {type: "createNode"}, ctx);
}
}else{
// this.nodeRenderTitle(ctx);
this.nodeRenderStatus(ctx);
}
// Allow tweaking after node state was rendered
if ( opts.renderNode ){
opts.renderNode.call(tree, {type: "renderNode"}, ctx);
}
}
// Visit child nodes
if( children ){
if( isRootNode || node.expanded || deep === true ) {
// Create a UL to hold the children
if( !node.ul ){
node.ul = document.createElement("ul");
if((collapsed === true && !_recursive) || !node.expanded){
// hide top UL, so we can use an animation to show it later
node.ul.style.display = "none";
}
if(aria){
$(node.ul).attr("role", "group");
}
if ( node.li ) { // issue #67
node.li.appendChild(node.ul);
} else {
node.tree.$div.append(node.ul);
}
}
// Add child markup
for(i=0, l=children.length; i<l; i++) {
subCtx = $.extend({}, ctx, {node: children[i]});
this.nodeRender(subCtx, force, deep, false, true);
}
// Remove <li> if nodes have moved to another parent
childLI = node.ul.firstChild;
while( childLI ){
childNode2 = childLI.ftnode;
if( childNode2 && childNode2.parent !== node ) {
node.debug("_fixParent: remove missing " + childNode2, childLI);
next = childLI.nextSibling;
childLI.parentNode.removeChild(childLI);
childLI = next;
}else{
childLI = childLI.nextSibling;
}
}
// Make sure, that <li> order matches node.children order.
childLI = node.ul.firstChild;
for(i=0, l=children.length-1; i<l; i++) {
childNode1 = children[i];
childNode2 = childLI.ftnode;
if( childNode1 !== childNode2 ) {
// node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
node.ul.insertBefore(childNode1.li, childNode2.li);
} else {
childLI = childLI.nextSibling;
}
}
}
}else{
// No children: remove markup if any
if( node.ul ){
// alert("remove child markup for " + node);
this.warn("remove child markup for " + node);
this.nodeRemoveChildMarkup(ctx);
}
}
if( !isRootNode ){
// Update element classes according to node state
// this.nodeRenderStatus(ctx);
// Finally add the whole structure to the DOM, so the browser can render
if(firstTime){
parent.ul.appendChild(node.li);
}
}
},
/** Create HTML for the node's outer <span> (expander, checkbox, icon, and title).
*
* nodeRenderStatus() is implied.
* @param {EventData} ctx
* @param {string} [title] optinal new title
*/
nodeRenderTitle: function(ctx, title) {
// set node connector images, links and text
var id, iconSpanClass, nodeTitle, role, tabindex, tooltip,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
level = node.getLevel(),
ares = [],
iconSrc = node.data.icon;
if(title !== undefined){
node.title = title;
}
if(!node.span){
// Silently bail out if node was not rendered yet, assuming
// node.render() will be called as the node becomes visible
return;
}
// connector (expanded, expandable or simple)
// TODO: optimize this if clause
if( level < opts.minExpandLevel ) {
if( !node.lazy ) {
node.expanded = true;
}
if(level > 1){
if(aria){
ares.push("<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>");
}else{
ares.push("<span class='fancytree-expander fancytree-expander-fixed''></span>");
}
}
// .. else (i.e. for root level) skip expander/connector alltogether
} else {
if(aria){
ares.push("<span role='button' class='fancytree-expander'></span>");
}else{
ares.push("<span class='fancytree-expander'></span>");
}
}
// Checkbox mode
if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) {
if(aria){
ares.push("<span role='checkbox' class='fancytree-checkbox'></span>");
}else{
ares.push("<span class='fancytree-checkbox'></span>");
}
}
// folder or doctype icon
role = aria ? " role='img'" : "";
if( iconSrc === true || (iconSrc !== false && opts.icons !== false) ) {
// opts.icons defines the default behavior, node.icon == true/false can override this
if ( iconSrc && typeof iconSrc === "string" ) {
// node.icon is an image url
iconSrc = (iconSrc.charAt(0) === "/") ? iconSrc : ((opts.imagePath || "") + iconSrc);
ares.push("<img src='" + iconSrc + "' class='fancytree-icon' alt='' />");
} else {
// See if node.iconClass or opts.iconClass() define a class name
iconSpanClass = (opts.iconClass && opts.iconClass.call(tree, node, ctx)) || node.data.iconclass || null;
if( iconSpanClass ) {
ares.push("<span " + role + " class='fancytree-custom-icon " + iconSpanClass + "'></span>");
} else {
ares.push("<span " + role + " class='fancytree-icon'></span>");
}
}
}
// node title
nodeTitle = "";
if ( opts.renderTitle ){
nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || "";
}
if(!nodeTitle){
tooltip = node.tooltip ? " title='" + FT.escapeHtml(node.tooltip) + "'" : "";
id = aria ? " id='ftal_" + node.key + "'" : "";
role = aria ? " role='treeitem'" : "";
tabindex = opts.titlesTabbable ? " tabindex='0'" : "";
nodeTitle = "<span " + role + " class='fancytree-title'" + id + tooltip + tabindex + ">" + node.title + "</span>";
}
ares.push(nodeTitle);
// Note: this will trigger focusout, if node had the focus
//$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly
node.span.innerHTML = ares.join("");
// Update CSS classes
this.nodeRenderStatus(ctx);
},
/** Update element classes according to node state.
* @param {EventData} ctx
*/
nodeRenderStatus: function(ctx) {
// Set classes for current status
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
// nodeContainer = node[tree.nodeContainerAttrName],
hasChildren = node.hasChildren(),
isLastSib = node.isLastSibling(),
aria = opts.aria,
// $ariaElem = aria ? $(node[tree.ariaPropName]) : null,
$ariaElem = $(node.span).find(".fancytree-title"),
cn = opts._classNames,
cnList = [],
statusElem = node[tree.statusClassPropName];
if( !statusElem ){
// if this function is called for an unrendered node, ignore it (will be updated on nect render anyway)
return;
}
// Build a list of class names that we will add to the node <span>
cnList.push(cn.node);
if( tree.activeNode === node ){
cnList.push(cn.active);
// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
// tree.$container.removeAttr("tabindex");
// }else{
// $(">span.fancytree-title", statusElem).removeAttr("tabindex");
// tree.$container.attr("tabindex", "0");
}
if( tree.focusNode === node ){
cnList.push(cn.focused);
if(aria){
// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
// TODO: is this the right element for this attribute?
$ariaElem
.attr("aria-activedescendant", true);
// .attr("tabindex", "-1");
}
}else if(aria){
// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
$ariaElem
.removeAttr("aria-activedescendant");
// .removeAttr("tabindex");
}
if( node.expanded ){
cnList.push(cn.expanded);
if(aria){
$ariaElem.attr("aria-expanded", true);
}
}else if(aria){
$ariaElem.removeAttr("aria-expanded");
}
if( node.folder ){
cnList.push(cn.folder);
}
if( hasChildren !== false ){
cnList.push(cn.hasChildren);
}
// TODO: required?
if( isLastSib ){
cnList.push(cn.lastsib);
}
if( node.lazy && node.children == null ){
cnList.push(cn.lazy);
}
if( node.partsel ){
cnList.push(cn.partsel);
}
if( node.unselectable ){
cnList.push(cn.unselectable);
}
if( node._isLoading ){
cnList.push(cn.loading);
}
if( node._error ){
cnList.push(cn.error);
}
if( node.selected ){
cnList.push(cn.selected);
if(aria){
$ariaElem.attr("aria-selected", true);
}
}else if(aria){
$ariaElem.attr("aria-selected", false);
}
if( node.extraClasses ){
cnList.push(node.extraClasses);
}
// IE6 doesn't correctly evaluate multiple class names,
// so we create combined class names that can be used in the CSS
if( hasChildren === false ){
cnList.push(cn.combinedExpanderPrefix + "n" +
(isLastSib ? "l" : "")
);
}else{
cnList.push(cn.combinedExpanderPrefix +
(node.expanded ? "e" : "c") +
(node.lazy && node.children == null ? "d" : "") +
(isLastSib ? "l" : "")
);
}
cnList.push(cn.combinedIconPrefix +
(node.expanded ? "e" : "c") +
(node.folder ? "f" : "")
);
// node.span.className = cnList.join(" ");
statusElem.className = cnList.join(" ");
// TODO: we should not set this in the <span> tag also, if we set it here:
// Maybe most (all) of the classes should be set in LI instead of SPAN?
if(node.li){
node.li.className = isLastSib ? cn.lastsib : "";
}
},
/** Activate node.
* flag defaults to true.
* If flag is true, the node is activated (must be a synchronous operation)
* If flag is false, the node is deactivated (must be a synchronous operation)
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false}
* @returns {$.Promise}
*/
nodeSetActive: function(ctx, flag, callOpts) {
// Handle user click / [space] / [enter], according to clickFolderMode.
callOpts = callOpts || {};
var subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noEvents = (callOpts.noEvents === true),
noFocus = (callOpts.noFocus === true),
isActive = (node === tree.activeNode);
// flag defaults to true
flag = (flag !== false);
// node.debug("nodeSetActive", flag);
if(isActive === flag){
// Nothing to do
return _getResolvedPromise(node);
}else if(flag && !noEvents && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
if(flag){
if(tree.activeNode){
_assert(tree.activeNode !== node, "node was active (inconsistency)");
subCtx = $.extend({}, ctx, {node: tree.activeNode});
tree.nodeSetActive(subCtx, false);
_assert(tree.activeNode === null, "deactivate was out of sync?");
}
if(opts.activeVisible){
// tree.nodeMakeVisible(ctx);
node.makeVisible({scrollIntoView: false}); // nodeSetFocus will scroll
}
tree.activeNode = node;
tree.nodeRenderStatus(ctx);
if( !noFocus ) {
tree.nodeSetFocus(ctx);
}
if( !noEvents ) {
tree._triggerNodeEvent("activate", node, ctx.originalEvent);
}
}else{
_assert(tree.activeNode === node, "node was not active (inconsistency)");
tree.activeNode = null;
this.nodeRenderStatus(ctx);
if( !noEvents ) {
ctx.tree._triggerNodeEvent("deactivate", node, ctx.originalEvent);
}
}
},
/** Expand or collapse node, return Deferred.promise.
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
* @returns {$.Promise} The deferred will be resolved as soon as the (lazy)
* data was retrieved, rendered, and the expand animation finshed.
*/
nodeSetExpanded: function(ctx, flag, callOpts) {
callOpts = callOpts || {};
var _afterLoad, dfd, i, l, parents, prevAC,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noAnimation = (callOpts.noAnimation === true),
noEvents = (callOpts.noEvents === true);
// flag defaults to true
flag = (flag !== false);
// node.debug("nodeSetExpanded(" + flag + ")");
if((node.expanded && flag) || (!node.expanded && !flag)){
// Nothing to do
// node.debug("nodeSetExpanded(" + flag + "): nothing to do");
return _getResolvedPromise(node);
}else if(flag && !node.lazy && !node.hasChildren() ){
// Prevent expanding of empty nodes
// return _getRejectedPromise(node, ["empty"]);
return _getResolvedPromise(node);
}else if( !flag && node.getLevel() < opts.minExpandLevel ) {
// Prevent collapsing locked levels
return _getRejectedPromise(node, ["locked"]);
}else if ( !noEvents && this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
// If this node inside a collpased node, no animation and scrolling is needed
if( !noAnimation && !node.isVisible() ) {
noAnimation = callOpts.noAnimation = true;
}
dfd = new $.Deferred();
// Auto-collapse mode: collapse all siblings
if( flag && !node.expanded && opts.autoCollapse ) {
parents = node.getParentList(false, true);
prevAC = opts.autoCollapse;
try{
opts.autoCollapse = false;
for(i=0, l=parents.length; i<l; i++){
// TODO: should return promise?
this._callHook("nodeCollapseSiblings", parents[i], callOpts);
}
}finally{
opts.autoCollapse = prevAC;
}
}
// Trigger expand/collapse after expanding
dfd.done(function(){
if( flag && opts.autoScroll && !noAnimation ) {
// Scroll down to last child, but keep current node visible
node.getLastChild().scrollIntoView(true, {topNode: node}).always(function(){
if( !noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
});
} else {
if( !noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
}
});
// vvv Code below is executed after loading finished:
_afterLoad = function(callback){
var isVisible, isExpanded,
effect = opts.toggleEffect;
node.expanded = flag;
// Create required markup, but make sure the top UL is hidden, so we
// can animate later
tree._callHook("nodeRender", ctx, false, false, true);
// If the currently active node is now hidden, deactivate it
// if( opts.activeVisible && this.activeNode && ! this.activeNode.isVisible() ) {
// this.activeNode.deactivate();
// }
// Expanding a lazy node: set 'loading...' and call callback
// if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) {
// this._loadContent();
// return;
// }
// Hide children, if node is collapsed
if( node.ul ) {
isVisible = (node.ul.style.display !== "none");
isExpanded = !!node.expanded;
if ( isVisible === isExpanded ) {
node.warn("nodeSetExpanded: UL.style.display already set");
} else if ( !effect || noAnimation ) {
node.ul.style.display = ( node.expanded || !parent ) ? "" : "none";
} else {
// The UI toggle() effect works with the ext-wide extension,
// while jQuery.animate() has problems when the title span
// has positon: absolute
// duration = opts.fx.duration || 200;
// easing = opts.fx.easing;
// $(node.ul).animate(opts.fx, duration, easing, function(){
// node.debug("nodeSetExpanded: animate start...");
$(node.ul).toggle(effect.effect, effect.options, effect.duration, function(){
// node.debug("nodeSetExpanded: animate done");
callback();
});
return;
}
}
callback();
};
// ^^^ Code above is executed after loading finshed.
// Load lazy nodes, if any. Then continue with _afterLoad()
if(flag && node.lazy && node.hasChildren() === undefined){
// node.debug("nodeSetExpanded: load start...");
node.load().done(function(){
// node.debug("nodeSetExpanded: load done");
if(dfd.notifyWith){ // requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad(function () { dfd.resolveWith(node); });
}).fail(function(errMsg){
_afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); });
});
/*
var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent);
_assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
node.debug("nodeSetExpanded: load start...");
this._callHook("nodeLoadChildren", ctx, source).done(function(){
node.debug("nodeSetExpanded: load done");
if(dfd.notifyWith){ // requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad.call(tree);
}).fail(function(errMsg){
dfd.rejectWith(node, ["load failed (" + errMsg + ")"]);
});
*/
}else{
_afterLoad(function () { dfd.resolveWith(node); });
}
// node.debug("nodeSetExpanded: returns");
return dfd.promise();
},
/** Focus or blur this node.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetFocus: function(ctx, flag) {
// ctx.node.debug("nodeSetFocus(" + flag + ")");
var ctx2,
tree = ctx.tree,
node = ctx.node;
flag = (flag !== false);
// Blur previous node if any
if(tree.focusNode){
if(tree.focusNode === node && flag){
// node.debug("nodeSetFocus(" + flag + "): nothing to do");
return;
}
ctx2 = $.extend({}, ctx, {node: tree.focusNode});
tree.focusNode = null;
this._triggerNodeEvent("blur", ctx2);
this._callHook("nodeRenderStatus", ctx2);
}
// Set focus to container and node
if(flag){
if( !this.hasFocus() ){
node.debug("nodeSetFocus: forcing container focus");
this._callHook("treeSetFocus", ctx, true, {calledByNode: true});
}
node.makeVisible({scrollIntoView: false});
tree.focusNode = node;
// node.debug("FOCUS...");
// $(node.span).find(".fancytree-title").focus();
this._triggerNodeEvent("focus", ctx);
// if(ctx.options.autoActivate){
// tree.nodeSetActive(ctx, true);
// }
if(ctx.options.autoScroll){
node.scrollIntoView();
}
this._callHook("nodeRenderStatus", ctx);
}
},
/** (De)Select node, return new status (sync).
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetSelected: function(ctx, flag) {
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options;
// flag defaults to true
flag = (flag !== false);
node.debug("nodeSetSelected(" + flag + ")", ctx);
if( node.unselectable){
return;
}
// TODO: !!node.expanded is nicer, but doesn't pass jshint
// https://github.com/jshint/jshint/issues/455
// if( !!node.expanded === !!flag){
if((node.selected && flag) || (!node.selected && !flag)){
return !!node.selected;
}else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){
return !!node.selected;
}
if(flag && opts.selectMode === 1){
// single selection mode
if(tree.lastSelectedNode){
tree.lastSelectedNode.setSelected(false);
}
}else if(opts.selectMode === 3){
// multi.hier selection mode
node.selected = flag;
// this._fixSelectionState(node);
node.fixSelection3AfterClick();
}
node.selected = flag;
this.nodeRenderStatus(ctx);
tree.lastSelectedNode = flag ? node : null;
tree._triggerNodeEvent("select", ctx);
},
/** Show node status (ok, loading, error) using styles and a dummy child node.
*
* @param {EventData} ctx
* @param status
* @param message
* @param details
*/
nodeSetStatus: function(ctx, status, message, details) {
var node = ctx.node,
tree = ctx.tree;
// cn = ctx.options._classNames;
function _clearStatusNode() {
// Remove dedicated dummy node, if any
var firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
try{
// I've seen exceptions here with loadKeyPath...
if(node.ul){
node.ul.removeChild(firstChild.li);
firstChild.li = null; // avoid leaks (DT issue 215)
}
}catch(e){}
if( node.children.length === 1 ){
node.children = [];
}else{
node.children.shift();
}
}
}
function _setStatusNode(data, type) {
// Create/modify the dedicated dummy node for 'loading...' or
// 'error!' status. (only called for direct child of the invisible
// system root)
var firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
$.extend(firstChild, data);
// tree._callHook("nodeRender", firstChild);
tree._callHook("nodeRenderTitle", firstChild);
} else {
data.key = "_statusNode";
node._setChildren([data]);
node.children[0].statusNodeType = type;
tree.render();
}
return node.children[0];
}
switch( status ){
case "ok":
_clearStatusNode();
// $(node.span).removeClass(cn.loading).removeClass(cn.error);
node._isLoading = false;
node._error = null;
node.renderStatus();
break;
case "loading":
// $(node.span).removeClass(cn.error).addClass(cn.loading);
if( !node.parent ) {
_setStatusNode({
title: tree.options.strings.loading + (message ? " (" + message + ") " : ""),
tooltip: details,
extraClasses: "fancytree-statusnode-wait"
}, status);
}
node._isLoading = true;
node._error = null;
node.renderStatus();
break;
case "error":
// $(node.span).removeClass(cn.loading).addClass(cn.error);
_setStatusNode({
title: tree.options.strings.loadError + (message ? " (" + message + ") " : ""),
tooltip: details,
extraClasses: "fancytree-statusnode-error"
}, status);
node._isLoading = false;
node._error = { message: message, details: details };
node.renderStatus();
break;
default:
$.error("invalid node status " + status);
}
},
/**
*
* @param {EventData} ctx
*/
nodeToggleExpanded: function(ctx) {
return this.nodeSetExpanded(ctx, !ctx.node.expanded);
},
/**
* @param {EventData} ctx
*/
nodeToggleSelected: function(ctx) {
return this.nodeSetSelected(ctx, !ctx.node.selected);
},
/** Remove all nodes.
* @param {EventData} ctx
*/
treeClear: function(ctx) {
var tree = ctx.tree;
tree.activeNode = null;
tree.focusNode = null;
tree.$div.find(">ul.fancytree-container").empty();
// TODO: call destructors and remove reference loops
tree.rootNode.children = null;
},
/** Widget was created (called only once, even it re-initialized).
* @param {EventData} ctx
*/
treeCreate: function(ctx) {
},
/** Widget was destroyed.
* @param {EventData} ctx
*/
treeDestroy: function(ctx) {
},
/** Widget was (re-)initialized.
* @param {EventData} ctx
*/
treeInit: function(ctx) {
//this.debug("Fancytree.treeInit()");
this.treeLoad(ctx);
},
/** Parse Fancytree from source, as configured in the options.
* @param {EventData} ctx
* @param {object} [source] optional new source (use last data otherwise)
*/
treeLoad: function(ctx, source) {
var type, $ul,
tree = ctx.tree,
$container = ctx.widget.element,
dfd,
// calling context for root node
rootCtx = $.extend({}, ctx, {node: this.rootNode});
if(tree.rootNode.children){
this.treeClear(ctx);
}
source = source || this.options.source;
if(!source){
type = $container.data("type") || "html";
switch(type){
case "html":
$ul = $container.find(">ul:first");
$ul.addClass("ui-fancytree-source ui-helper-hidden");
source = $.ui.fancytree.parseHtml($ul);
// allow to init tree.data.foo from <ul data-foo=''>
this.data = $.extend(this.data, _getElementDataAsDict($ul));
break;
case "json":
// $().addClass("ui-helper-hidden");
source = $.parseJSON($container.text());
if(source.children){
if(source.title){tree.title = source.title;}
source = source.children;
}
break;
default:
$.error("Invalid data-type: " + type);
}
}else if(typeof source === "string"){
// TODO: source is an element ID
$.error("Not implemented");
}
// $container.addClass("ui-widget ui-widget-content ui-corner-all");
// Trigger fancytreeinit after nodes have been loaded
dfd = this.nodeLoadChildren(rootCtx, source).done(function(){
tree.render();
if( ctx.options.selectMode === 3 ){
tree.rootNode.fixSelection3FromEndNodes();
}
tree._triggerTreeEvent("init", null, { status: true });
}).fail(function(){
tree.render();
tree._triggerTreeEvent("init", null, { status: false });
});
return dfd;
},
/** Node was inserted into or removed from the tree.
* @param {EventData} ctx
* @param {boolean} add
* @param {FancytreeNode} node
*/
treeRegisterNode: function(ctx, add, node) {
},
/** Widget got focus.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
treeSetFocus: function(ctx, flag, callOpts) {
flag = (flag !== false);
// this.debug("treeSetFocus(" + flag + "), callOpts: " + callOpts);
// this.debug(" focusNode: " + this.focusNode);
// this.debug(" activeNode: " + this.activeNode);
if( flag !== this.hasFocus() ){
this._hasFocus = flag;
if( !flag && this.focusNode ) {
// Node also looses focus if widget blurs
this.focusNode.setFocus(false);
}
this.$container.toggleClass("fancytree-treefocus", flag);
this._triggerTreeEvent(flag ? "focusTree" : "blurTree");
}
}
});
/* ******************************************************************************
* jQuery UI widget boilerplate
*/
/**
* The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br>
* This constructor is not called directly. Use `$(selector).fancytree({})`
* to initialize the plugin instead.<br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members:
* var tree = $("#tree").fancytree("getTree");
* var node = $("#tree").fancytree("getActiveNode", "1234");
* </pre>
*
* @mixin Fancytree_Widget
*/
$.widget("ui.fancytree",
/** @lends Fancytree_Widget# */
{
/**These options will be used as defaults
* @type {FancytreeOptions}
*/
options:
{
activeVisible: true,
ajax: {
type: "GET",
cache: false, // false: Append random '_' argument to the request url to prevent caching.
// timeout: 0, // >0: Make sure we get an ajax error if server is unreachable
dataType: "json" // Expect json format and pass json object to callbacks.
}, //
aria: false, // TODO: default to true
autoActivate: true,
autoCollapse: false,
// autoFocus: false,
autoScroll: false,
checkbox: false,
/**defines click behavior*/
clickFolderMode: 4,
debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo)
disabled: false, // TODO: required anymore?
enableAspx: true, // TODO: document
extensions: [],
// fx: { height: "toggle", duration: 200 },
// toggleEffect: { effect: "drop", options: {direction: "left"}, duration: 200 },
// toggleEffect: { effect: "slide", options: {direction: "up"}, duration: 200 },
toggleEffect: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 },
generateIds: false,
icons: true,
idPrefix: "ft_",
focusOnSelect: false,
keyboard: true,
keyPathSeparator: "/",
minExpandLevel: 1,
quicksearch: false,
scrollOfs: {top: 0, bottom: 0},
scrollParent: null,
selectMode: 2,
strings: {
loading: "Loading…",
loadError: "Load error!"
},
tabbable: true,
titlesTabbable: false,
_classNames: {
node: "fancytree-node",
folder: "fancytree-folder",
combinedExpanderPrefix: "fancytree-exp-",
combinedIconPrefix: "fancytree-ico-",
hasChildren: "fancytree-has-children",
active: "fancytree-active",
selected: "fancytree-selected",
expanded: "fancytree-expanded",
lazy: "fancytree-lazy",
focused: "fancytree-focused",
partsel: "fancytree-partsel",
unselectable: "fancytree-unselectable",
lastsib: "fancytree-lastsib",
loading: "fancytree-loading",
error: "fancytree-error"
},
// events
lazyLoad: null,
postProcess: null
},
/* Set up the widget, Called on first $().fancytree() */
_create: function() {
this.tree = new Fancytree(this);
this.$source = this.source || this.element.data("type") === "json" ? this.element
: this.element.find(">ul:first");
// Subclass Fancytree instance with all enabled extensions
var extension, extName, i,
extensions = this.options.extensions,
base = this.tree;
for(i=0; i<extensions.length; i++){
extName = extensions[i];
extension = $.ui.fancytree._extensions[extName];
if(!extension){
$.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)");
}
// Add extension options as tree.options.EXTENSION
// _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName);
this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]);
// Add a namespace tree.ext.EXTENSION, to hold instance data
_assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'");
// this.tree[extName] = extension;
this.tree.ext[extName] = {};
// Subclass Fancytree methods using proxies.
_subclassObject(this.tree, base, extension, extName);
// current extension becomes base for the next extension
base = extension;
}
//
this.tree._callHook("treeCreate", this.tree);
// Note: 'fancytreecreate' event is fired by widget base class
// this.tree._triggerTreeEvent("create");
},
/* Called on every $().fancytree() */
_init: function() {
this.tree._callHook("treeInit", this.tree);
// TODO: currently we call bind after treeInit, because treeInit
// might change tree.$container.
// It would be better, to move ebent binding into hooks altogether
this._bind();
},
/* Use the _setOption method to respond to changes to options */
_setOption: function(key, value) {
var callDefault = true,
rerender = false;
switch( key ) {
case "aria":
case "checkbox":
case "icons":
case "minExpandLevel":
case "tabbable":
// case "nolink":
this.tree._callHook("treeCreate", this.tree);
rerender = true;
break;
case "source":
callDefault = false;
this.tree._callHook("treeLoad", this.tree, value);
break;
}
this.tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">");
if(callDefault){
// In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget
$.Widget.prototype._setOption.apply(this, arguments);
// TODO: In jQuery UI 1.9 and above, you use the _super method instead
// this._super( "_setOption", key, value );
}
if(rerender){
this.tree.render(true, false); // force, not-deep
}
},
/** Use the destroy method to clean up any modifications your widget has made to the DOM */
destroy: function() {
this._unbind();
this.tree._callHook("treeDestroy", this.tree);
// this.element.removeClass("ui-widget ui-widget-content ui-corner-all");
this.tree.$div.find(">ul.fancytree-container").remove();
this.$source && this.$source.removeClass("ui-helper-hidden");
// In jQuery UI 1.8, you must invoke the destroy method from the base widget
$.Widget.prototype.destroy.call(this);
// TODO: delete tree and nodes to make garbage collect easier?
// TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
},
// -------------------------------------------------------------------------
/* Remove all event handlers for our namespace */
_unbind: function() {
var ns = this.tree._ns;
this.element.unbind(ns);
this.tree.$container.unbind(ns);
$(document).unbind(ns);
},
/* Add mouse and kyboard handlers to the container */
_bind: function() {
var that = this,
opts = this.options,
tree = this.tree,
ns = tree._ns
// selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" )
;
// Remove all previuous handlers for this tree
this._unbind();
//alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container);
// tree.debug("bind events; container: ", tree.$container);
tree.$container.on("focusin" + ns + " focusout" + ns, function(event){
var node = FT.getNode(event),
flag = (event.type === "focusin");
// tree.debug("Tree container got event " + event.type, node, event);
// tree.treeOnFocusInOut.call(tree, event);
if(node){
// For example clicking into an <input> that is part of a node
tree._callHook("nodeSetFocus", node, flag);
}else{
tree._callHook("treeSetFocus", tree, flag);
}
}).on("selectstart" + ns, "span.fancytree-title", function(event){
// prevent mouse-drags to select text ranges
// tree.debug("<span title> got event " + event.type);
event.preventDefault();
}).on("keydown" + ns, function(event){
// TODO: also bind keyup and keypress
// tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus());
// if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){
if(opts.disabled || opts.keyboard === false ){
return true;
}
var res,
node = tree.focusNode, // node may be null
ctx = tree._makeHookContext(node || tree, event),
prevPhase = tree.phase;
try {
tree.phase = "userEvent";
// If a 'fancytreekeydown' handler returns false, skip the default
// handling (implemented by tree.nodeKeydown()).
if(node){
res = tree._triggerNodeEvent("keydown", node, event);
}else{
res = tree._triggerTreeEvent("keydown", event);
}
if ( res === "preventNav" ){
res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls
} else if ( res !== false ){
res = tree._callHook("nodeKeydown", ctx);
}
return res;
} finally {
tree.phase = prevPhase;
}
}).on("click" + ns + " dblclick" + ns, function(event){
if(opts.disabled){
return true;
}
var ctx,
et = FT.getEventTarget(event),
node = et.node,
tree = that.tree,
prevPhase = tree.phase;
if( !node ){
return true; // Allow bubbling of other events
}
ctx = tree._makeHookContext(node, event);
// that.tree.debug("event(" + event.type + "): node: ", node);
try {
tree.phase = "userEvent";
switch(event.type) {
case "click":
ctx.targetType = et.type;
return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx);
case "dblclick":
ctx.targetType = et.type;
return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx);
}
// } catch(e) {
// // var _ = null; // DT issue 117 // TODO
// $.error(e);
} finally {
tree.phase = prevPhase;
}
});
},
/** Return the active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.tree.activeNode;
},
/** Return the matching node or null.
* @param {string} key
* @returns {FancytreeNode}
*/
getNodeByKey: function(key) {
return this.tree.getNodeByKey(key);
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.tree.rootNode;
},
/** Return the current tree instance.
* @returns {Fancytree}
*/
getTree: function() {
return this.tree;
}
});
// $.ui.fancytree was created by the widget factory. Create a local shortcut:
FT = $.ui.fancytree;
/**
* Static members in the `$.ui.fancytree` namespace.<br>
* <br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access static members:
* var node = $.ui.fancytree.getNode(element);
* alert($.ui.fancytree.version);
* </pre>
*
* @mixin Fancytree_Static
*/
$.extend($.ui.fancytree,
/** @lends Fancytree_Static# */
{
/** @type {string} */
version: "2.8.1", // Set to semver by 'grunt release'
/** @type {string} */
buildType: "production", // Set to 'production' by 'grunt build'
/** @type {int} */
debugLevel: 1, // Set to 1 by 'grunt build'
// Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel
_nextId: 1,
_nextNodeKey: 1,
_extensions: {},
// focusTree: null,
/** Expose class object as $.ui.fancytree._FancytreeClass */
_FancytreeClass: Fancytree,
/** Expose class object as $.ui.fancytree._FancytreeNodeClass */
_FancytreeNodeClass: FancytreeNode,
/* Feature checks to provide backwards compatibility */
jquerySupports: {
// http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
positionMyOfs: isVersionAtLeast($.ui.version, 1, 9)
},
/** Throw an error if condition fails (debug method).
* @param {boolean} cond
* @param {string} msg
*/
assert: function(cond, msg){
return _assert(cond, msg);
},
/** Return a function that executes *fn* at most every *timeout* ms.
* @param {integer} timeout
* @param {function} fn
* @param {boolean} [invokeAsap=false]
* @param {any} [ctx]
*/
debounce: function(timeout, fn, invokeAsap, ctx) {
var timer;
if(arguments.length === 3 && typeof invokeAsap !== "boolean") {
ctx = invokeAsap;
invokeAsap = false;
}
return function() {
var args = arguments;
ctx = ctx || this;
invokeAsap && !timer && fn.apply(ctx, args);
clearTimeout(timer);
timer = setTimeout(function() {
invokeAsap || fn.apply(ctx, args);
timer = null;
}, timeout);
};
},
/** Write message to console if debugLevel >= 2
* @param {string} msg
*/
debug: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments);
},
/** Write error message to console.
* @param {string} msg
*/
error: function(msg){
consoleApply("error", arguments);
},
/** Convert <, >, &, ", ', / to the equivalent entitites.
*
* @param {string} s
* @returns {string}
*/
escapeHtml: function(s){
return ("" + s).replace(/[&<>"'\/]/g, function (s) {
return ENTITY_MAP[s];
});
},
/** Make jQuery.position() arguments backwards compatible, i.e. if
* jQuery UI version <= 1.8, convert
* { my: "left+3 center", at: "left bottom", of: $target }
* to
* { my: "left center", at: "left bottom", of: $target, offset: "3 0" }
*
* See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
* and http://jsfiddle.net/mar10/6xtu9a4e/
*/
fixPositionOptions: function(opts) {
if( opts.offset || ("" + opts.my + opts.at ).indexOf("%") >= 0 ) {
$.error("expected new position syntax (but '%' is not supported)");
}
if( ! $.ui.fancytree.jquerySupports.positionMyOfs ) {
var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined]
myParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.my),
atParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.at),
// convert to numbers
dx = (myParts[2] ? (+myParts[2]) : 0) + (atParts[2] ? (+atParts[2]) : 0),
dy = (myParts[4] ? (+myParts[4]) : 0) + (atParts[4] ? (+atParts[4]) : 0);
opts = $.extend({}, opts, { // make a copy and overwrite
my: myParts[1] + " " + myParts[3],
at: atParts[1] + " " + atParts[3]
});
if( dx || dy ) {
opts.offset = "" + dx + " " + dy;
}
}
return opts;
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTargetType: function(event){
return this.getEventTarget(event).type;
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {object} Return a {node: FancytreeNode, type: TYPE} object
* TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTarget: function(event){
var tcn = event && event.target ? event.target.className : "",
res = {node: this.getNode(event.target), type: undefined};
// We use a fast version of $(res.node).hasClass()
// See http://jsperf.com/test-for-classname/2
if( /\bfancytree-title\b/.test(tcn) ){
res.type = "title";
}else if( /\bfancytree-expander\b/.test(tcn) ){
res.type = (res.node.hasChildren() === false ? "prefix" : "expander");
}else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){
res.type = "checkbox";
}else if( /\bfancytree-icon\b/.test(tcn) ){
res.type = "icon";
}else if( /\bfancytree-node\b/.test(tcn) ){
// Somewhere near the title
res.type = "title";
}else if( event && event.target && $(event.target).closest(".fancytree-title").length ) {
// #228: clicking an embedded element inside a title
res.type = "title";
}
return res;
},
/** Return a FancytreeNode instance from element.
*
* @param {Element | jQueryObject | Event} el
* @returns {FancytreeNode} matching node or null
*/
getNode: function(el){
if(el instanceof FancytreeNode){
return el; // el already was a FancytreeNode
}else if(el.selector !== undefined){
el = el[0]; // el was a jQuery object: use the DOM element
}else if(el.originalEvent !== undefined){
el = el.target; // el was an Event
}
while( el ) {
if(el.ftnode) {
return el.ftnode;
}
el = el.parentNode;
}
return null;
},
/* Return a Fancytree instance from element.
* TODO: this function could help to get around the data('fancytree') / data('ui-fancytree') problem
* @param {Element | jQueryObject | Event} el
* @returns {Fancytree} matching tree or null
* /
getTree: function(el){
if(el instanceof Fancytree){
return el; // el already was a Fancytree
}else if(el.selector !== undefined){
el = el[0]; // el was a jQuery object: use the DOM element
}else if(el.originalEvent !== undefined){
el = el.target; // el was an Event
}
...
return null;
},
*/
/** Write message to console if debugLevel >= 1
* @param {string} msg
*/
info: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments);
},
/** Convert a keydown or mouse event to a canonical string like 'ctrl+a', 'ctrl+shift+f2', 'shift+leftdblclick'.
* This is especially handy for switch-statements in event handlers.
* @param {event}
* @returns {string}
*/
eventToString: function(event) {
// Poor-man's hotkeys. See here for a complete implementation:
// https://github.com/jeresig/jquery.hotkeys
var which = event.which,
et = event.type,
s = [];
if( event.altKey ) { s.push("alt"); }
if( event.ctrlKey ) { s.push("ctrl"); }
if( event.metaKey ) { s.push("meta"); }
if( event.shiftKey ) { s.push("shift"); }
if( et === "click" || et === "dblclick" ) {
s.push(MOUSE_BUTTONS[event.button] + et);
} else {
if( !IGNORE_KEYCODES[which] ) {
s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() );
}
}
return s.join("+");
},
/* @deprecated: use eventToString(event) instead.
*/
keyEventToString: function(event) {
this.warn("keyEventToString() is deprecated: use eventToString()");
return this.eventToString(event);
},
/**
* Parse tree data from HTML <ul> markup
*
* @param {jQueryObject} $ul
* @returns {NodeData[]}
*/
parseHtml: function($ul) {
// TODO: understand this:
/*jshint validthis:true */
var extraClasses, i, l, iPos, tmp, tmp2, classes, className,
$children = $ul.find(">li"),
children = [];
$children.each(function() {
var allData,
$li = $(this),
$liSpan = $li.find(">span:first", this),
$liA = $liSpan.length ? null : $li.find(">a:first"),
d = { tooltip: null, data: {} };
if( $liSpan.length ) {
d.title = $liSpan.html();
} else if( $liA && $liA.length ) {
// If a <li><a> tag is specified, use it literally and extract href/target.
d.title = $liA.html();
d.data.href = $liA.attr("href");
d.data.target = $liA.attr("target");
d.tooltip = $liA.attr("title");
} else {
// If only a <li> tag is specified, use the trimmed string up to
// the next child <ul> tag.
d.title = $li.html();
iPos = d.title.search(/<ul/i);
if( iPos >= 0 ){
d.title = d.title.substring(0, iPos);
}
}
d.title = $.trim(d.title);
// Make sure all fields exist
for(i=0, l=CLASS_ATTRS.length; i<l; i++){
d[CLASS_ATTRS[i]] = undefined;
}
// Initialize to `true`, if class is set and collect extraClasses
classes = this.className.split(" ");
extraClasses = [];
for(i=0, l=classes.length; i<l; i++){
className = classes[i];
if(CLASS_ATTR_MAP[className]){
d[className] = true;
}else{
extraClasses.push(className);
}
}
d.extraClasses = extraClasses.join(" ");
// Parse node options from ID, title and class attributes
tmp = $li.attr("title");
if( tmp ){
d.tooltip = tmp; // overrides <a title='...'>
}
tmp = $li.attr("id");
if( tmp ){
d.key = tmp;
}
// Add <li data-NAME='...'> as node.data.NAME
allData = _getElementDataAsDict($li);
if(allData && !$.isEmptyObject(allData)) {
// #56: Allow to set special node.attributes from data-...
for(i=0, l=NODE_ATTRS.length; i<l; i++){
tmp = NODE_ATTRS[i];
tmp2 = allData[tmp];
if( tmp2 != null ) {
delete allData[tmp];
d[tmp] = tmp2;
}
}
// All other data-... goes to node.data...
$.extend(d.data, allData);
}
// Recursive reading of child nodes, if LI tag contains an UL tag
$ul = $li.find(">ul:first");
if( $ul.length ) {
d.children = $.ui.fancytree.parseHtml($ul);
}else{
d.children = d.lazy ? undefined : null;
}
children.push(d);
// FT.debug("parse ", d, children);
});
return children;
},
/** Add Fancytree extension definition to the list of globally available extensions.
*
* @param {object} definition
*/
registerExtension: function(definition){
_assert(definition.name != null, "extensions must have a `name` property.");
_assert(definition.version != null, "extensions must have a `version` property.");
$.ui.fancytree._extensions[definition.name] = definition;
},
/** Inverse of escapeHtml().
*
* @param {string} s
* @returns {string}
*/
unescapeHtml: function(s){
var e = document.createElement("div");
e.innerHTML = s;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
},
/** Write warning message to console.
* @param {string} msg
*/
warn: function(msg){
consoleApply("warn", arguments);
}
});
}(jQuery, window, document));
// Extending Fancytree
// ===================
//
// See also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code.
//
// Every extension should have a comment header containing some information
// about the author, copyright and licensing. Also a pointer to the latest
// source code.
// Prefix with `/*!` so the comment is not removed by the minifier.
/*!
* jquery.fancytree.childcounter.js
*
* Add a child counter bubble to tree nodes.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
// To keep the global namespace clean, we wrap everything in a closure
;(function($, undefined) {
// Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)
"use strict";
// The [coding guidelines](http://contribute.jquery.org/style-guide/js/)
// require jshint compliance.
// But for this sample, we want to allow unused variables for demonstration purpose.
/*jshint unused:false */
// Adding methods
// --------------
// New member functions can be added to the `Fancytree` class.
// This function will be available for every tree instance.
//
// var tree = $("#tree").fancytree("getTree");
// tree.countSelected(false);
$.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly){
var tree = this,
treeOptions = tree.options;
return tree.getSelectedNodes(topOnly).length;
};
// The `FancytreeNode` class can also be easily extended. This would be called
// like
//
// node.toUpper();
$.ui.fancytree._FancytreeNodeClass.prototype.toUpper = function(){
var node = this;
return node.setTitle(node.title.toUpperCase());
};
// Finally, we can extend the widget API and create functions that are called
// like so:
//
// $("#tree").fancytree("widgetMethod1", "abc");
$.ui.fancytree.prototype.widgetMethod1 = function(arg1){
var tree = this.tree;
return arg1;
};
// Register a Fancytree extension
// ------------------------------
// A full blown extension, extension is available for all trees and can be
// enabled like so (see also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html)):
//
// <script src="../src/jquery.fancytree.js" type="text/javascript"></script>
// <script src="../src/jquery.fancytree.childcounter.js" type="text/javascript"></script>
// ...
//
// $("#tree").fancytree({
// extensions: ["childcounter"],
// childcounter: {
// hideExpanded: true
// },
// ...
// });
//
/* 'childcounter' extension */
$.ui.fancytree.registerExtension({
// Every extension must be registered by a unique name.
name: "childcounter",
// Version information should be compliant with [semver](http://semver.org)
version: "1.0.0",
// Extension specific options and their defaults.
// This options will be available as `tree.options.childcounter.hideExpanded`
options: {
deep: true,
hideZeros: true,
hideExpanded: false
},
// Attributes other than `options` (or functions) can be defined here, and
// will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`.
// They can also be accessed as `this._local.foo` from within the extension
// methods.
foo: 42,
// Local functions are prefixed with an underscore '_'.
// Callable as `this._local._appendCounter()`.
_appendCounter: function(bar){
var tree = this;
},
// **Override virtual methods for this extension.**
//
// Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'.
// with a `ctx` argument (see [EventData](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/global.html#EventData)
// for details) and an extended calling context:<br>
// `this` : the Fancytree instance<br>
// `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br>
// `this._super`: the virtual function that was overridden (member of previous extension or Fancytree)
//
// See also the [complete list of available hook functions](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html).
/* Init */
// `treeInit` is triggered when a tree is initalized. We can set up classes or
// bind event handlers here...
treeInit: function(ctx){
var tree = this, // same as ctx.tree,
opts = ctx.options,
extOpts = ctx.options.childcounter;
// Optionally check for dependencies with other extensions
/* this._requireExtension("glyph", false, false); */
// Call the base implementation
this._superApply(arguments);
// Add a class to the tree container
this.$container.addClass("fancytree-ext-childcounter");
},
// Destroy this tree instance (we only call the default implementation, so
// this method could as well be omitted).
treeDestroy: function(ctx){
this._superApply(arguments);
},
// Overload the `renderTitle` hook, to append a counter badge
nodeRenderTitle: function(ctx, title) {
var node = ctx.node,
extOpts = ctx.options.childcounter,
count = (node.data.childCounter == null) ? node.countChildren(extOpts.deep) : +node.data.childCounter;
// Let the base implementation render the title
this._superApply(arguments);
// Append a counter badge
if( (count || ! extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ){
$("span.fancytree-icon", node.span).append($("<span class='fancytree-childcounter'/>").text(count));
}
},
// Overload the `setExpanded` hook, so the counters are updated
nodeSetExpanded: function(ctx, flag, opts) {
var tree = ctx.tree,
node = ctx.node;
// Let the base implementation expand/collapse the node, then redraw the title
// after the animation has finished
return this._superApply(arguments).always(function(){
tree.nodeRenderTitle(ctx);
});
}
// End of extension definition
});
// End of namespace closure
}(jQuery));
/*!
*
* jquery.fancytree.clones.js
* Support faster lookup of nodes by key and shared ref-ids.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
function _assert(cond, msg){
// TODO: see qunit.js extractStacktrace()
if(!cond){
msg = msg ? ": " + msg : "";
$.error("Assertion failed" + msg);
}
}
/* Return first occurrence of member from array. */
function _removeArrayMember(arr, elem) {
// TODO: use Array.indexOf for IE >= 9
var i;
for (i = arr.length - 1; i >= 0; i--) {
if (arr[i] === elem) {
arr.splice(i, 1);
return true;
}
}
return false;
}
// /**
// * Calculate a 32 bit FNV-1a hash
// * Found here: https://gist.github.com/vaiorabbit/5657561
// * Ref.: http://isthe.com/chongo/tech/comp/fnv/
// *
// * @param {string} str the input value
// * @param {boolean} [asString=false] set to true to return the hash value as
// * 8-digit hex string instead of an integer
// * @param {integer} [seed] optionally pass the hash of the previous chunk
// * @returns {integer | string}
// */
// function hashFnv32a(str, asString, seed) {
// /*jshint bitwise:false */
// var i, l,
// hval = (seed === undefined) ? 0x811c9dc5 : seed;
// for (i = 0, l = str.length; i < l; i++) {
// hval ^= str.charCodeAt(i);
// hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
// }
// if( asString ){
// // Convert to 8 digit hex string
// return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
// }
// return hval >>> 0;
// }
/**
* JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
*
* @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
* @see http://github.com/garycourt/murmurhash-js
* @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} key ASCII only
* @param {boolean} [asString=false]
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function hashMurmur3(key, asString, seed) {
/*jshint bitwise:false */
var h1b, k1,
remainder = key.length & 3,
bytes = key.length - remainder,
h1 = seed,
c1 = 0xcc9e2d51,
c2 = 0x1b873593,
i = 0;
while (i < bytes) {
k1 =
((key.charCodeAt(i) & 0xff)) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
}
k1 = 0;
switch (remainder) {
/*jshint -W086:true */
case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
case 1: k1 ^= (key.charCodeAt(i) & 0xff);
k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
h1 ^= h1 >>> 16;
if( asString ){
// Convert to 8 digit hex string
return ("0000000" + (h1 >>> 0).toString(16)).substr(-8);
}
return h1 >>> 0;
}
// console.info(hashMurmur3("costarring"));
// console.info(hashMurmur3("costarring", true));
// console.info(hashMurmur3("liquid"));
// console.info(hashMurmur3("liquid", true));
/*
* Return a unique key for node by calculationg the hash of the parents refKey-list
*/
function calcUniqueKey(node) {
var key,
path = $.map(node.getParentList(false, true), function(e){ return e.refKey || e.key; });
path = path.join("/");
key = "id_" + hashMurmur3(path, true);
// node.debug(path + " -> " + key);
return key;
}
/**
* [ext-clones] Return a list of clone-nodes or null.
* @param {boolean} [includeSelf=false]
* @returns {FancytreeNode[] | null}
*
* @alias FancytreeNode#getCloneList
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function(includeSelf){
var key,
tree = this.tree,
refList = tree.refMap[this.refKey] || null,
keyMap = tree.keyMap;
if( refList ) {
key = this.key;
// Convert key list to node list
if( includeSelf ) {
refList = $.map(refList, function(val){ return keyMap[val]; });
} else {
refList = $.map(refList, function(val){ return val === key ? null : keyMap[val]; });
if( refList.length < 1 ) {
refList = null;
}
}
}
return refList;
};
/**
* [ext-clones] Return true if this node has at least another clone with same refKey.
* @returns {boolean}
*
* @alias FancytreeNode#isClone
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isClone = function(){
var refKey = this.refKey || null,
refList = refKey && this.tree.refMap[refKey] || null;
return !!(refList && refList.length > 1);
};
/**
* [ext-clones] Update key and/or refKey for an existing node.
* @param {string} key
* @param {string} refKey
* @returns {boolean}
*
* @alias FancytreeNode#reRegister
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function(key, refKey){
key = (key == null) ? null : "" + key;
refKey = (refKey == null) ? null : "" + refKey;
// this.debug("reRegister", key, refKey);
var tree = this.tree,
prevKey = this.key,
prevRefKey = this.refKey,
keyMap = tree.keyMap,
refMap = tree.refMap,
refList = refMap[prevRefKey] || null,
// curCloneKeys = refList ? node.getCloneList(true),
modified = false;
// Key has changed: update all references
if( key != null && key !== this.key ) {
if( keyMap[key] ) {
$.error("[ext-clones] reRegister(" + key + "): already exists: " + this);
}
// Update keyMap
delete keyMap[prevKey];
keyMap[key] = this;
// Update refMap
if( refList ) {
refMap[prevRefKey] = $.map(refList, function(e){
return e === prevKey ? key : e;
});
}
this.key = key;
modified = true;
}
// refKey has changed
if( refKey != null && refKey !== this.refKey ) {
// Remove previous refKeys
if( refList ){
if( refList.length === 1 ){
delete refMap[prevRefKey];
}else{
refMap[prevRefKey] = $.map(refList, function(e){
return e === prevKey ? null : e;
});
}
}
// Add refKey
if( refMap[refKey] ) {
refMap[refKey].append(key);
}else{
refMap[refKey] = [ this.key ];
}
this.refKey = refKey;
modified = true;
}
return modified;
};
/**
* [ext-clones] Return all nodes with a given refKey (null if not found).
* @param {string} refKey
* @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node
* @returns {FancytreeNode[] | null}
* @alias Fancytree#getNodesByRef
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function(refKey, rootNode){
var keyMap = this.keyMap,
refList = this.refMap[refKey] || null;
if( refList ) {
// Convert key list to node list
if( rootNode ) {
refList = $.map(refList, function(val){
var node = keyMap[val];
return node.isDescendantOf(rootNode) ? node : null;
});
}else{
refList = $.map(refList, function(val){ return keyMap[val]; });
}
if( refList.length < 1 ) {
refList = null;
}
}
return refList;
};
/**
* [ext-clones] Replace a refKey with a new one.
* @param {string} oldRefKey
* @param {string} newRefKey
* @alias Fancytree#changeRefKey
* @requires jquery.fancytree.clones.js
*/
$.ui.fancytree._FancytreeClass.prototype.changeRefKey = function(oldRefKey, newRefKey) {
var i, node,
keyMap = this.keyMap,
refList = this.refMap[oldRefKey] || null;
if (refList) {
for (i = 0; i < refList.length; i++) {
node = keyMap[refList[i]];
node.refKey = newRefKey;
}
delete this.refMap[oldRefKey];
this.refMap[newRefKey] = refList;
}
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "clones",
version: "0.0.3",
// Default options for this extension.
options: {
highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers
highlightClones: false // set 'fancytree-clone' class on any node that has at least one clone
},
treeCreate: function(ctx){
this._superApply(arguments);
ctx.tree.refMap = {};
ctx.tree.keyMap = {};
},
treeInit: function(ctx){
this.$container.addClass("fancytree-ext-clones");
_assert(ctx.options.defaultKey == null);
// Generate unique / reproducible default keys
ctx.options.defaultKey = function(node){
return calcUniqueKey(node);
};
// The default implementation loads initial data
this._superApply(arguments);
},
treeClear: function(ctx){
ctx.tree.refMap = {};
ctx.tree.keyMap = {};
return this._superApply(arguments);
},
treeRegisterNode: function(ctx, add, node) {
var refList, len,
tree = ctx.tree,
keyMap = tree.keyMap,
refMap = tree.refMap,
key = node.key,
refKey = (node && node.refKey != null) ? "" + node.refKey : null;
// ctx.tree.debug("clones.treeRegisterNode", add, node);
if( key === "_statusNode" ){
return this._superApply(arguments);
}
if( add ) {
if( keyMap[node.key] != null ) {
$.error("clones.treeRegisterNode: node.key already exists: " + node);
}
keyMap[key] = node;
if( refKey ) {
refList = refMap[refKey];
if( refList ) {
refList.push(key);
if( refList.length === 2 && ctx.options.clones.highlightClones ) {
// Mark peer node, if it just became a clone (no need to
// mark current node, since it will be rendered later anyway)
keyMap[refList[0]].renderStatus();
}
} else {
refMap[refKey] = [key];
}
// node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]);
}
}else {
if( keyMap[key] == null ) {
$.error("clones.treeRegisterNode: node.key not registered: " + node.key);
}
delete keyMap[key];
if( refKey ) {
refList = refMap[refKey];
// node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]);
if( refList ) {
len = refList.length;
if( len <= 1 ){
_assert(len === 1);
_assert(refList[0] === key);
delete refMap[refKey];
}else{
_removeArrayMember(refList, key);
// Unmark peer node, if this was the only clone
if( len === 2 && ctx.options.clones.highlightClones ) {
// node.debug("clones.treeRegisterNode: last =>", node.getCloneList());
keyMap[refList[0]].renderStatus();
}
}
// node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]);
}
}
}
return this._superApply(arguments);
},
nodeRenderStatus: function(ctx) {
var $span, res,
node = ctx.node;
res = this._superApply(arguments);
if( ctx.options.clones.highlightClones ) {
$span = $(node[ctx.tree.statusClassPropName]);
// Only if span already exists
if( $span.length && node.isClone() ){
// node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones);
$span.addClass("fancytree-clone");
}
}
return res;
},
nodeSetActive: function(ctx, flag) {
var res,
scpn = ctx.tree.statusClassPropName,
node = ctx.node;
res = this._superApply(arguments);
if( ctx.options.clones.highlightActiveClones && node.isClone() ) {
$.each(node.getCloneList(true), function(idx, n){
// n.debug("clones.nodeSetActive: ", flag !== false);
$(n[scpn]).toggleClass("fancytree-active-clone", flag !== false);
});
}
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.dnd.js
*
* Drag-and-drop support.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
var didRegisterDnd = false;
/* Convert number to string and prepend +/-; return empty string for 0.*/
function offsetString(n){
return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n));
}
/* *****************************************************************************
* Drag and drop support
*/
function _initDragAndDrop(tree) {
var dnd = tree.options.dnd || null;
// Register 'connectToFancytree' option with ui.draggable
if( dnd ) {
_registerDnd();
}
// Attach ui.draggable to this Fancytree instance
if(dnd && dnd.dragStart ) {
tree.widget.element.draggable($.extend({
addClasses: false,
// DT issue 244: helper should be child of scrollParent:
appendTo: tree.$container,
// appendTo: "body",
containment: false,
delay: 0,
distance: 4,
revert: false,
scroll: true, // to disable, also set css 'position: inherit' on ul.fancytree-container
scrollSpeed: 7,
scrollSensitivity: 10,
// Delegate draggable.start, drag, and stop events to our handler
connectToFancytree: true,
// Let source tree create the helper element
helper: function(event) {
var $helper,
sourceNode = $.ui.fancytree.getNode(event.target),
$nodeTag = $(sourceNode.span);
if(!sourceNode){
// DT issue 211: might happen, if dragging a table *header*
return "<div>ERROR?: helper requested but sourceNode not found</div>";
}
// Only event and node argument is available
$helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>")
.css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar
.append($nodeTag.find("span.fancytree-title").clone());
// Attach node reference to helper object
$helper.data("ftSourceNode", sourceNode);
// we return an unconnected element, so `draggable` will add this
// to the parent specified as `appendTo` option
return $helper;
},
start: function(event, ui) {
var sourceNode = ui.helper.data("ftSourceNode");
return !!sourceNode; // Abort dragging if no node could be found
}
}, tree.options.dnd.draggable));
}
// Attach ui.droppable to this Fancytree instance
if(dnd && dnd.dragDrop) {
tree.widget.element.droppable($.extend({
addClasses: false,
tolerance: "intersect",
greedy: false
/*
activate: function(event, ui) {
tree.debug("droppable - activate", event, ui, this);
},
create: function(event, ui) {
tree.debug("droppable - create", event, ui);
},
deactivate: function(event, ui) {
tree.debug("droppable - deactivate", event, ui);
},
drop: function(event, ui) {
tree.debug("droppable - drop", event, ui);
},
out: function(event, ui) {
tree.debug("droppable - out", event, ui);
},
over: function(event, ui) {
tree.debug("droppable - over", event, ui);
}
*/
}, tree.options.dnd.droppable));
}
}
//--- Extend ui.draggable event handling --------------------------------------
function _registerDnd() {
if(didRegisterDnd){
return;
}
// Register proxy-functions for draggable.start/drag/stop
$.ui.plugin.add("draggable", "connectToFancytree", {
start: function(event, ui) {
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null;
if(sourceNode) {
// Adjust helper offset, so cursor is slightly outside top/left corner
draggable.offset.click.top = -2;
draggable.offset.click.left = + 16;
// Trigger dragStart event
// TODO: when called as connectTo..., the return value is ignored(?)
return sourceNode.tree.ext.dnd._onDragEvent("start", sourceNode, null, event, ui, draggable);
}
},
drag: function(event, ui) {
var isHelper, logObject,
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null,
prevTargetNode = ui.helper.data("ftTargetNode") || null,
targetNode = $.ui.fancytree.getNode(event.target);
if(event.target && !targetNode){
// We got a drag event, but the targetNode could not be found
// at the event location. This may happen,
// 1. if the mouse jumped over the drag helper,
// 2. or if a non-fancytree element is dragged
// We ignore it:
isHelper = $(event.target).closest("div.fancytree-drag-helper,#fancytree-drop-marker").length > 0;
if(isHelper){
logObject = sourceNode || prevTargetNode || $.ui.fancytree;
logObject.debug("Drag event over helper: ignored.");
return;
}
}
ui.helper.data("ftTargetNode", targetNode);
// Leaving a tree node
if(prevTargetNode && prevTargetNode !== targetNode ) {
prevTargetNode.tree.ext.dnd._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
}
if(targetNode){
if(!targetNode.tree.options.dnd.dragDrop) {
// not enabled as drop target
} else if(targetNode === prevTargetNode) {
// Moving over same node
targetNode.tree.ext.dnd._onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
}else{
// Entering this node first time
targetNode.tree.ext.dnd._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
}
}
// else go ahead with standard event handling
},
stop: function(event, ui) {
// 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
var logObject,
draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
sourceNode = ui.helper.data("ftSourceNode") || null,
targetNode = ui.helper.data("ftTargetNode") || null,
// mouseDownEvent = draggable._mouseDownEvent,
eventType = event.type,
dropped = (eventType === "mouseup" && event.which === 1);
if(!dropped){
logObject = sourceNode || targetNode || $.ui.fancytree;
logObject.debug("Drag was cancelled");
}
if(targetNode) {
if(dropped){
targetNode.tree.ext.dnd._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
}
targetNode.tree.ext.dnd._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
}
if(sourceNode){
sourceNode.tree.ext.dnd._onDragEvent("stop", sourceNode, null, event, ui, draggable);
}
}
});
didRegisterDnd = true;
}
/* *****************************************************************************
*
*/
$.ui.fancytree.registerExtension({
name: "dnd",
version: "0.1.0",
// Default options for this extension.
options: {
// Make tree nodes accept draggables
autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
draggable: null, // Additional options passed to jQuery draggable
droppable: null, // Additional options passed to jQuery droppable
focusOnClick: false, // Focus, although draggable cancels mousedown event (#270)
// helper: null, // Callback
// helperParent: null, // jQuery object (defaults to Fancytree container)
preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
// Events (drag support)
dragStart: null, // Callback(sourceNode, data), return true, to enable dnd
dragStop: null, // Callback(sourceNode, data)
// Events (drop support)
dragEnter: null, // Callback(targetNode, data)
dragOver: null, // Callback(targetNode, data)
dragDrop: null, // Callback(targetNode, data)
dragLeave: null // Callback(targetNode, data)
},
treeInit: function(ctx){
var tree = ctx.tree;
this._superApply(arguments);
// issue #270: draggable eats mousedown events
if( tree.options.dnd.dragStart ){
tree.$container.on("mousedown", function(event){
if( !tree.hasFocus() && ctx.options.dnd.focusOnClick ) {
var node = $.ui.fancytree.getNode(event);
node.debug("Re-enable focus that was prevented by jQuery UI draggable.");
// node.setFocus();
// $(node.span).closest(":tabbable").focus();
// $(event.target).trigger("focus");
// $(event.target).closest(":tabbable").trigger("focus");
setTimeout(function() { // #300
$(event.target).closest(":tabbable").focus();
}, 10);
}
});
}
_initDragAndDrop(tree);
},
/* Override key handler in order to cancel dnd on escape.*/
nodeKeydown: function(ctx) {
var event = ctx.originalEvent;
if( event.which === $.ui.keyCode.ESCAPE) {
this._local._cancelDrag();
}
return this._superApply(arguments);
},
nodeClick: function(ctx) {
// if( ctx.options.dnd.dragStart ){
// ctx.tree.$container.focus();
// }
return this._superApply(arguments);
},
/* Display drop marker according to hitMode ('after', 'before', 'over', 'out', 'start', 'stop'). */
_setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) {
var markerOffsetX = 0,
markerAt = "center",
instData = this._local,
$source = sourceNode ? $(sourceNode.span) : null,
$target = $(targetNode.span);
if( !instData.$dropMarker ) {
instData.$dropMarker = $("<div id='fancytree-drop-marker'></div>")
.hide()
.css({"z-index": 1000})
.prependTo($(this.$div).parent());
// .prependTo("body");
}
// this.$dropMarker.attr("class", hitMode);
if(hitMode === "after" || hitMode === "before" || hitMode === "over"){
// $source && $source.addClass("fancytree-drag-source");
// $target.addClass("fancytree-drop-target");
switch(hitMode){
case "before":
instData
.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-over")
.addClass("fancytree-drop-before");
markerAt = "top";
break;
case "after":
instData.$dropMarker.removeClass("fancytree-drop-before fancytree-drop-over")
.addClass("fancytree-drop-after");
markerAt = "bottom";
break;
default:
instData.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-before")
.addClass("fancytree-drop-over");
$target.addClass("fancytree-drop-target");
markerOffsetX = 8;
}
instData.$dropMarker
.show()
.position($.ui.fancytree.fixPositionOptions({
my: "left" + offsetString(markerOffsetX) + " center",
at: "left " + markerAt,
of: $target
}));
// helper.addClass("fancytree-drop-hover");
} else {
// $source && $source.removeClass("fancytree-drag-source");
$target.removeClass("fancytree-drop-target");
instData.$dropMarker.hide();
// helper.removeClass("fancytree-drop-hover");
}
if(hitMode === "after"){
$target.addClass("fancytree-drop-after");
} else {
$target.removeClass("fancytree-drop-after");
}
if(hitMode === "before"){
$target.addClass("fancytree-drop-before");
} else {
$target.removeClass("fancytree-drop-before");
}
if(accept === true){
if($source){
$source.addClass("fancytree-drop-accept");
}
$target.addClass("fancytree-drop-accept");
helper.addClass("fancytree-drop-accept");
}else{
if($source){
$source.removeClass("fancytree-drop-accept");
}
$target.removeClass("fancytree-drop-accept");
helper.removeClass("fancytree-drop-accept");
}
if(accept === false){
if($source){
$source.addClass("fancytree-drop-reject");
}
$target.addClass("fancytree-drop-reject");
helper.addClass("fancytree-drop-reject");
}else{
if($source){
$source.removeClass("fancytree-drop-reject");
}
$target.removeClass("fancytree-drop-reject");
helper.removeClass("fancytree-drop-reject");
}
},
/*
* Handles drag'n'drop functionality.
*
* A standard jQuery drag-and-drop process may generate these calls:
*
* draggable helper():
* _onDragEvent("helper", sourceNode, null, event, null, null);
* start:
* _onDragEvent("start", sourceNode, null, event, ui, draggable);
* drag:
* _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
* _onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
* stop:
* _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
* _onDragEvent("stop", sourceNode, null, event, ui, draggable);
*/
_onDragEvent: function(eventName, node, otherNode, event, ui, draggable) {
if(eventName !== "over"){
this.debug("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this);
}
var /*$helper, $helperParent,*/ nodeOfs, relPos, relPos2,
enterResponse, hitMode, r,
opts = this.options,
dnd = opts.dnd,
ctx = this._makeHookContext(node, event, {otherNode: otherNode, ui: ui, draggable: draggable}),
res = null,
$nodeTag = $(node.span);
switch (eventName) {
// case "helper":
// // Only event and node argument is available
// $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>")
// .css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar
// .append($nodeTag.find("span.fancytree-title").clone());
// // #345: helper parent is now set using draggable.appendTo
// // $helperParent = dnd.helperParent || $("ul.fancytree-container", node.tree.$div);
// // DT issue 244: helper should be child of scrollParent
// // $helperParent.append($helper);
// // Attach node reference to helper object
// $helper.data("ftSourceNode", node);
// // this.debug("helper=%o", $helper);
// // this.debug("helper.sourceNode=%o", $helper.data("ftSourceNode"));
// res = $helper;
// break;
case "start":
if( node.isStatusNode() ) {
res = false;
} else if(dnd.dragStart) {
res = dnd.dragStart(node, ctx);
}
if(res === false) {
this.debug("tree.dragStart() cancelled");
//draggable._clear();
// NOTE: the return value seems to be ignored (drag is not canceled, when false is returned)
// TODO: call this._cancelDrag()?
ui.helper.trigger("mouseup")
.hide();
} else {
$nodeTag.addClass("fancytree-drag-source");
}
break;
case "enter":
if(dnd.preventRecursiveMoves && node.isDescendantOf(otherNode)){
r = false;
}else{
r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null;
}
if(!r){
// convert null, undefined, false to false
res = false;
}else if ( $.isArray(r) ) {
// TODO: also accept passing an object of this format directly
res = {
over: ($.inArray("over", r) >= 0),
before: ($.inArray("before", r) >= 0),
after: ($.inArray("after", r) >= 0)
};
}else{
res = {
over: ((r === true) || (r === "over")),
before: ((r === true) || (r === "before")),
after: ((r === true) || (r === "after"))
};
}
ui.helper.data("enterResponse", res);
this.debug("helper.enterResponse: %o", res);
break;
case "over":
enterResponse = ui.helper.data("enterResponse");
hitMode = null;
if(enterResponse === false){
// Don't call dragOver if onEnter returned false.
// break;
} else if(typeof enterResponse === "string") {
// Use hitMode from onEnter if provided.
hitMode = enterResponse;
} else {
// Calculate hitMode from relative cursor position.
nodeOfs = $nodeTag.offset();
relPos = { x: event.pageX - nodeOfs.left,
y: event.pageY - nodeOfs.top };
relPos2 = { x: relPos.x / $nodeTag.width(),
y: relPos.y / $nodeTag.height() };
if( enterResponse.after && relPos2.y > 0.75 ){
hitMode = "after";
} else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){
hitMode = "after";
} else if(enterResponse.before && relPos2.y <= 0.25) {
hitMode = "before";
} else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) {
hitMode = "before";
} else if(enterResponse.over) {
hitMode = "over";
}
// Prevent no-ops like 'before source node'
// TODO: these are no-ops when moving nodes, but not in copy mode
if( dnd.preventVoidMoves ){
if(node === otherNode){
this.debug(" drop over source node prevented");
hitMode = null;
}else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){
this.debug(" drop after source node prevented");
hitMode = null;
}else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){
this.debug(" drop before source node prevented");
hitMode = null;
}else if(hitMode === "over" && otherNode && otherNode.parent === node && otherNode.isLastSibling() ){
this.debug(" drop last child over own parent prevented");
hitMode = null;
}
}
// this.debug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling());
ui.helper.data("hitMode", hitMode);
}
// Auto-expand node (only when 'over' the node, not 'before', or 'after')
if(hitMode === "over" && dnd.autoExpandMS && node.hasChildren() !== false && !node.expanded) {
node.scheduleAction("expand", dnd.autoExpandMS);
}
if(hitMode && dnd.dragOver){
// TODO: http://code.google.com/p/dynatree/source/detail?r=625
ctx.hitMode = hitMode;
res = dnd.dragOver(node, ctx);
}
// DT issue 332
// this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false);
this._local._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false && hitMode !== null);
break;
case "drop":
hitMode = ui.helper.data("hitMode");
if(hitMode && dnd.dragDrop){
ctx.hitMode = hitMode;
dnd.dragDrop(node, ctx);
}
break;
case "leave":
// Cancel pending expand request
node.scheduleAction("cancel");
ui.helper.data("enterResponse", null);
ui.helper.data("hitMode", null);
this._local._setDndStatus(otherNode, node, ui.helper, "out", undefined);
if(dnd.dragLeave){
dnd.dragLeave(node, ctx);
}
break;
case "stop":
$nodeTag.removeClass("fancytree-drag-source");
if(dnd.dragStop){
dnd.dragStop(node, ctx);
}
break;
default:
$.error("Unsupported drag event: " + eventName);
}
return res;
},
_cancelDrag: function() {
var dd = $.ui.ddmanager.current;
if(dd){
dd.cancel();
}
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.edit.js
*
* Make node titles editable.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
var isMac = /Mac/.test(navigator.platform),
escapeHtml = $.ui.fancytree.escapeHtml,
unescapeHtml = $.ui.fancytree.unescapeHtml;
/**
* [ext-edit] Start inline editing of current node title.
*
* @alias FancytreeNode#editStart
* @requires Fancytree
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){
var $input,
node = this,
tree = this.tree,
local = tree.ext.edit,
instOpts = tree.options.edit,
$title = $(".fancytree-title", node.span),
eventData = {
node: node,
tree: tree,
options: tree.options,
isNew: $(node.span).hasClass("fancytree-edit-new"),
orgTitle: node.title,
input: null,
dirty: false
};
// beforeEdit may want to modify the title before editing
if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false ) {
return false;
}
$.ui.fancytree.assert(!local.currentNode, "recursive edit");
local.currentNode = this;
local.eventData = eventData;
// Disable standard Fancytree mouse- and key handling
tree.widget._unbind();
// #116: ext-dnd prevents the blur event, so we have to catch outer clicks
$(document).on("mousedown.fancytree-edit", function(event){
if( ! $(event.target).hasClass("fancytree-edit-input") ){
node.editEnd(true, event);
}
});
// Replace node with <input>
$input = $("<input />", {
"class": "fancytree-edit-input",
type: "text",
value: unescapeHtml(eventData.orgTitle)
});
local.eventData.input = $input;
if ( instOpts.adjustWidthOfs != null ) {
$input.width($title.width() + instOpts.adjustWidthOfs);
}
if ( instOpts.inputCss != null ) {
$input.css(instOpts.inputCss);
}
$title.html($input);
// Focus <input> and bind keyboard handler
$input
.focus()
.change(function(event){
$input.addClass("fancytree-edit-dirty");
}).keydown(function(event){
switch( event.which ) {
case $.ui.keyCode.ESCAPE:
node.editEnd(false, event);
break;
case $.ui.keyCode.ENTER:
node.editEnd(true, event);
return false; // so we don't start editmode on Mac
}
event.stopPropagation();
}).blur(function(event){
return node.editEnd(true, event);
});
instOpts.edit.call(node, {type: "edit"}, eventData);
};
/**
* [ext-edit] Stop inline editing.
* @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified)
* @alias FancytreeNode#editEnd
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){
var newVal,
node = this,
tree = this.tree,
local = tree.ext.edit,
eventData = local.eventData,
instOpts = tree.options.edit,
$title = $(".fancytree-title", node.span),
$input = $title.find("input.fancytree-edit-input");
// eventData.isNew = $(node.span).hasClass("fancytree-edit-new");
if( instOpts.trim ) {
$input.val($.trim($input.val()));
}
newVal = $input.val();
// eventData.dirty = $input.hasClass("fancytree-edit-dirty") || ;
eventData.dirty = ( newVal !== node.title );
// Find out, if saving is required
if( applyChanges === false ) {
// If true/false was passed, honor this (except in rename mode, if unchanged)
eventData.save = false;
} else if( eventData.isNew ) {
// In create mode, we save everyting, except for empty text
eventData.save = (newVal !== "");
} else {
// In rename mode, we save everyting, except for empty or unchanged text
eventData.save = eventData.dirty && (newVal !== "");
}
// Allow to break (keep editor open), modify input, or re-define data.save
if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){
return false;
}
if( eventData.save && instOpts.save.call(node, {type: "save"}, eventData) === false){
return false;
}
$input
.removeClass("fancytree-edit-dirty")
.unbind();
// Unbind outer-click handler
$(document).off(".fancytree-edit");
if( eventData.save ) {
node.setTitle( escapeHtml(newVal) );
// $(node.span).removeClass("fancytree-edit-new");
node.setFocus();
}else{
if( eventData.isNew ) {
node.remove();
node = eventData.node = null;
local.relatedNode.setFocus();
} else {
node.renderTitle();
node.setFocus();
}
}
local.eventData = null;
local.currentNode = null;
local.relatedNode = null;
// Re-enable mouse and keyboard handling
tree.widget._bind();
// Set keyboard focus, even if setFocus() claims 'nothing to do'
$(tree.$container).focus();
eventData.input = null;
instOpts.close.call(node, {type: "close"}, eventData);
return true;
};
/**
* [ext-edit] Create a new child or sibling node and start edit mode.
*
* @param {String} [mode='child'] 'before', 'after', or 'child'
* @param {Object} [init] NodeData (or simple title string)
* @alias FancytreeNode#editCreateNode
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode, init){
var newNode,
self = this;
mode = mode || "child";
if( init == null ) {
init = { title: "" };
} else if( typeof init === "string" ) {
init = { title: init };
} else {
$.ui.fancytree.assert($.isPlainObject(init));
}
// Make sure node is expanded (and loaded) in 'child' mode
if( mode === "child" && !this.isExpanded() && this.hasChildren() !== false ) {
this.setExpanded().done(function(){
self.editCreateNode(mode, init);
});
return;
}
newNode = this.addNode(init, mode);
newNode.makeVisible(/*{noAnimation: true}*/).done(function(){
$(newNode.span).addClass("fancytree-edit-new");
self.tree.ext.edit.relatedNode = self;
newNode.editStart();
});
};
/**
* [ext-edit] Check if any node in this tree in edit mode.
*
* @returns {FancytreeNode | null}
* @alias Fancytree#isEditing
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeClass.prototype.isEditing = function(){
return this.ext.edit.currentNode;
};
/**
* [ext-edit] Check if this node is in edit mode.
* @returns {Boolean} true if node is currently beeing edited
* @alias FancytreeNode#isEditing
* @requires jquery.fancytree.edit.js
*/
$.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){
return this.tree.ext.edit.currentNode === this;
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "edit",
version: "0.2.0",
// Default options for this extension.
options: {
adjustWidthOfs: 4, // null: don't adjust input size to content
allowEmpty: false, // Prevent empty input
inputCss: {minWidth: "3em"},
triggerCancel: ["esc", "tab", "click"],
// triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"],
triggerStart: ["f2", "shift+click", "mac+enter"],
trim: true, // Trim whitespace before save
// Events:
beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available)
beforeEdit: $.noop, // Return false to prevent edit mode
close: $.noop, // Editor was removed
edit: $.noop, // Editor was opened (available as data.input)
// keypress: $.noop, // Not yet implemented
save: $.noop // Save data.input.val() or return false to keep editor open
},
// Local attributes
currentNode: null,
treeInit: function(ctx){
this._superApply(arguments);
this.$container.addClass("fancytree-ext-edit");
},
nodeClick: function(ctx) {
if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){
if( ctx.originalEvent.shiftKey ){
ctx.node.editStart();
return false;
}
}
return this._superApply(arguments);
},
nodeDblclick: function(ctx) {
if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){
ctx.node.editStart();
return false;
}
return this._superApply(arguments);
},
nodeKeydown: function(ctx) {
switch( ctx.originalEvent.which ) {
case 113: // [F2]
if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){
ctx.node.editStart();
return false;
}
break;
case $.ui.keyCode.ENTER:
if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){
ctx.node.editStart();
return false;
}
break;
}
return this._superApply(arguments);
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.filter.js
*
* Remove or highlight tree nodes, based on a filter.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
function _escapeRegex(str){
/*jshint regexdash:true */
return (str + "").replace(/([.?*+\^\$\[\]\\(){}|-])/g, "\\$1");
}
$.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function(filter, branchMode, leavesOnly){
var match, re,
count = 0,
hideMode = this.options.filter.mode === "hide";
// leavesOnly = !branchMode && this.options.filter.leavesOnly;
leavesOnly = !!leavesOnly && !branchMode;
// Default to 'match title substring (not case sensitive)'
if(typeof filter === "string"){
match = _escapeRegex(filter); // make sure a '.' is treated literally
re = new RegExp(".*" + match + ".*", "i");
filter = function(node){
return !!re.exec(node.title);
};
}
this.enableFilter = true;
this.lastFilterArgs = arguments;
this.$div.addClass("fancytree-ext-filter");
if( hideMode ){
this.$div.addClass("fancytree-ext-filter-hide");
} else {
this.$div.addClass("fancytree-ext-filter-dimm");
}
// Reset current filter
this.visit(function(node){
delete node.match;
delete node.subMatch;
});
// Adjust node.hide, .match, .subMatch flags
this.visit(function(node){
if ((!leavesOnly || node.children == null) && filter(node)) {
count++;
node.match = true;
node.visitParents(function(p){
p.subMatch = true;
});
if( branchMode ) {
node.visit(function(p){
p.match = true;
});
return "skip";
}
}
});
// Redraw
this.render();
return count;
};
/**
* [ext-filter] Dimm or hide nodes.
*
* @param {function | string} filter
* @param {boolean} [leavesOnly=false]
* @returns {integer} count
* @alias Fancytree#filterNodes
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.filterNodes = function(filter, leavesOnly){
return this._applyFilterImpl(filter, false, leavesOnly);
};
/**
* @deprecated
*/
$.ui.fancytree._FancytreeClass.prototype.applyFilter = function(filter){
this.warn("Fancytree.applyFilter() is deprecated since 2014-05-10. Use .filterNodes() instead.");
return this.filterNodes.apply(this, arguments);
};
/**
* [ext-filter] Dimm or hide whole branches.
*
* @param {function | string} filter
* @returns {integer} count
* @alias Fancytree#filterBranches
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.filterBranches = function(filter){
return this._applyFilterImpl(filter, true, null);
};
/**
* [ext-filter] Reset the filter.
*
* @alias Fancytree#clearFilter
* @requires jquery.fancytree.filter.js
*/
$.ui.fancytree._FancytreeClass.prototype.clearFilter = function(){
this.visit(function(node){
delete node.match;
delete node.subMatch;
});
this.enableFilter = false;
this.lastFilterArgs = null;
this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide");
this.render();
};
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "filter",
version: "0.3.0",
// Default options for this extension.
options: {
autoApply: true, // re-apply last filter if lazy data is loaded
mode: "dimm"
},
treeInit: function(ctx){
this._superApply(arguments);
},
nodeLoadChildren: function(ctx, source) {
return this._superApply(arguments).done(function() {
if( ctx.tree.enableFilter && ctx.tree.lastFilterArgs && ctx.options.filter.autoApply ) {
ctx.tree._applyFilterImpl.apply(ctx.tree, ctx.tree.lastFilterArgs);
}
});
},
nodeRenderStatus: function(ctx) {
// Set classes for current status
var res,
node = ctx.node,
tree = ctx.tree,
$span = $(node[tree.statusClassPropName]);
res = this._superApply(arguments);
// nothing to do, if node was not yet rendered
if( !$span.length || !tree.enableFilter ) {
return res;
}
$span
.toggleClass("fancytree-match", !!node.match)
.toggleClass("fancytree-submatch", !!node.subMatch)
.toggleClass("fancytree-hide", !(node.match || node.subMatch));
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.glyph.js
*
* Use glyph fonts as instead of icon sprites.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
function _getIcon(opts, type){
return opts.map[type];
}
$.ui.fancytree.registerExtension({
name: "glyph",
version: "0.2.0",
// Default options for this extension.
options: {
map: {
checkbox: "icon-check-empty",
checkboxSelected: "icon-check",
checkboxUnknown: "icon-check icon-muted",
error: "icon-exclamation-sign",
expanderClosed: "icon-caret-right",
expanderLazy: "icon-angle-right",
expanderOpen: "icon-caret-down",
doc: "icon-file-alt",
noExpander: "",
// Default node icons.
// (Use tree.options.iconClass(node) callback to define custom icons
// based on node data)
docOpen: "icon-file-alt",
loading: "icon-refresh icon-spin",
folder: "icon-folder-close-alt",
folderOpen: "icon-folder-open-alt"
}
},
treeInit: function(ctx){
var tree = ctx.tree;
this._superApply(arguments);
tree.$container.addClass("fancytree-ext-glyph");
},
nodeRenderStatus: function(ctx) {
var icon, span,
node = ctx.node,
$span = $(node.span),
opts = ctx.options.glyph,
// callback = opts.icon,
map = opts.map
// $span = $(node.span)
;
this._superApply(arguments);
if( node.isRoot() ){
return;
}
span = $span.children("span.fancytree-expander").get(0);
if( span ){
if( node.isLoading() ){
icon = "loading";
}else if( node.expanded ){
icon = "expanderOpen";
}else if( node.isUndefined() ){
icon = "expanderLazy";
}else if( node.hasChildren() ){
icon = "expanderClosed";
}else{
icon = "noExpander";
}
span.className = "fancytree-expander " + map[icon];
}
if( node.tr ){
span = $("td", node.tr).children("span.fancytree-checkbox").get(0);
}else{
span = $span.children("span.fancytree-checkbox").get(0);
}
if( span ){
icon = node.selected ? "checkboxSelected" : (node.partsel ? "checkboxUnknown" : "checkbox");
span.className = "fancytree-checkbox " + map[icon];
}
// Icon (note that this does not match .fancytree-custom-icon, that might
// be set by opts.iconClass)
span = $span.children("span.fancytree-icon").get(0);
if( span ){
if( node.folder ){
icon = node.expanded ? _getIcon(opts, "folderOpen") : _getIcon(opts, "folder");
}else{
icon = node.expanded ? _getIcon(opts, "docOpen") : _getIcon(opts, "doc");
}
span.className = "fancytree-icon " + icon;
}
},
nodeSetStatus: function(ctx, status, message, details) {
var span,
opts = ctx.options.glyph,
node = ctx.node;
this._superApply(arguments);
if(node.parent){
span = $("span.fancytree-expander", node.span).get(0);
}else{
span = $(".fancytree-statusnode-wait, .fancytree-statusnode-error", node[this.nodeContainerAttrName])
.find("span.fancytree-expander").get(0);
}
if( status === "loading"){
// $("span.fancytree-expander", ctx.node.span).addClass(_getIcon(opts, "loading"));
span.className = "fancytree-expander " + _getIcon(opts, "loading");
}else if( status === "error"){
span.className = "fancytree-expander " + _getIcon(opts, "error");
}
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.gridnav.js
*
* Support keyboard navigation for trees with embedded input controls.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
// Allow these navigation keys even when input controls are focused
var KC = $.ui.keyCode,
// which keys are *not* handled by embedded control, but passed to tree
// navigation handler:
NAV_KEYS = {
"text": [KC.UP, KC.DOWN],
"checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"select-one": [KC.LEFT, KC.RIGHT],
"select-multiple": [KC.LEFT, KC.RIGHT]
};
/* Calculate TD column index (considering colspans).*/
function getColIdx($tr, $td) {
var colspan,
td = $td.get(0),
idx = 0;
$tr.children().each(function () {
if( this === td ) {
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return idx;
}
/* Find TD at given column index (considering colspans).*/
function findTdAtColIdx($tr, colIdx) {
var colspan,
res = null,
idx = 0;
$tr.children().each(function () {
if( idx >= colIdx ) {
res = $(this);
return false;
}
colspan = $(this).prop("colspan");
idx += colspan ? colspan : 1;
});
return res;
}
/* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */
function findNeighbourTd($target, keyCode){
var $tr, colIdx,
$td = $target.closest("td"),
$tdNext = null;
switch( keyCode ){
case KC.LEFT:
$tdNext = $td.prev();
break;
case KC.RIGHT:
$tdNext = $td.next();
break;
case KC.UP:
case KC.DOWN:
$tr = $td.parent();
colIdx = getColIdx($tr, $td);
while( true ) {
$tr = (keyCode === KC.UP) ? $tr.prev() : $tr.next();
if( !$tr.length ) {
break;
}
// Skip hidden rows
if( $tr.is(":hidden") ) {
continue;
}
// Find adjacent cell in the same column
$tdNext = findTdAtColIdx($tr, colIdx);
// Skip cells that don't conatain a focusable element
if( $tdNext && $tdNext.find(":input").length ) {
break;
}
}
break;
}
return $tdNext;
}
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "gridnav",
version: "0.0.1",
// Default options for this extension.
options: {
autofocusInput: false, // Focus first embedded input if node gets activated
handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node
},
treeInit: function(ctx){
// gridnav requires the table extension to be loaded before itself
this._requireExtension("table", true, true);
this._superApply(arguments);
this.$container.addClass("fancytree-ext-gridnav");
// Activate node if embedded input gets focus (due to a click)
this.$container.on("focusin", function(event){
var ctx2,
node = $.ui.fancytree.getNode(event.target);
if( node && !node.isActive() ){
// Call node.setActive(), but also pass the event
ctx2 = ctx.tree._makeHookContext(node, event);
ctx.tree._callHook("nodeSetActive", ctx2, true);
}
});
},
nodeSetActive: function(ctx, flag) {
var $outer,
opts = ctx.options.gridnav,
node = ctx.node,
event = ctx.originalEvent || {},
triggeredByInput = $(event.target).is(":input");
flag = (flag !== false);
this._superApply(arguments);
if( flag ){
if( ctx.options.titlesTabbable ){
if( !triggeredByInput ) {
$(node.span).find("span.fancytree-title").focus();
node.setFocus();
}
// If one node is tabbable, the container no longer needs to be
ctx.tree.$container.attr("tabindex", "-1");
// ctx.tree.$container.removeAttr("tabindex");
} else if( opts.autofocusInput && !triggeredByInput ){
// Set focus to input sub input (if node was clicked, but not
// when TAB was pressed )
$outer = $(node.tr || node.span);
$outer.find(":input:enabled:first").focus();
}
}
},
nodeKeydown: function(ctx) {
var inputType, handleKeys, $td,
opts = ctx.options.gridnav,
event = ctx.originalEvent,
$target = $(event.target);
// jQuery
inputType = $target.is(":input:enabled") ? $target.prop("type") : null;
// ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType);
if( inputType && opts.handleCursorKeys ){
handleKeys = NAV_KEYS[inputType];
if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){
$td = findNeighbourTd($target, event.which);
// ctx.node.debug("ignore keydown in input", event.which, handleKeys);
if( $td && $td.length ) {
$td.find(":input:enabled").focus();
// Prevent Fancytree default navigation
return false;
}
}
return true;
}
// ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType);
return this._superApply(arguments);
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.persist.js
*
* Persist tree status in cookiesRemove or highlight tree nodes, based on a filter.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* @depends: jquery.cookie.js
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
var _assert = $.ui.fancytree.assert,
ACTIVE = "active",
EXPANDED = "expanded",
FOCUS = "focus",
SELECTED = "selected";
/* Recursively load lazy nodes
* @param {string} mode 'load', 'expand', false
*/
function _loadLazyNodes(tree, local, keyList, mode, dfd) {
var i, key, l, node,
foundOne = false,
deferredList = [],
missingKeyList = [];
keyList = keyList || [];
dfd = dfd || $.Deferred();
for( i=0, l=keyList.length; i<l; i++ ) {
key = keyList[i];
node = tree.getNodeByKey(key);
if( node ) {
if( mode && node.isUndefined() ) {
foundOne = true;
tree.debug("_loadLazyNodes: " + node + " is lazy: loading...");
if( mode === "expand" ) {
deferredList.push(node.setExpanded());
} else {
deferredList.push(node.load());
}
} else {
tree.debug("_loadLazyNodes: " + node + " already loaded.");
node.setExpanded();
}
} else {
missingKeyList.push(key);
tree.debug("_loadLazyNodes: " + node + " was not yet found.");
}
}
$.when.apply($, deferredList).always(function(){
// All lazy-expands have finished
if( foundOne && missingKeyList.length > 0 ) {
// If we read new nodes from server, try to resolve yet-missing keys
_loadLazyNodes(tree, local, missingKeyList, mode, dfd);
} else {
if( missingKeyList.length ) {
tree.warn("_loadLazyNodes: could not load those keys: ", missingKeyList);
for( i=0, l=missingKeyList.length; i<l; i++ ) {
key = keyList[i];
local._appendKey(EXPANDED, keyList[i], false);
}
}
dfd.resolve();
}
});
return dfd;
}
/**
* [ext-persist] Remove persistence cookies of the given type(s).
* Called like
* $("#tree").fancytree("getTree").clearCookies("active expanded focus selected");
*
* @alias Fancytree#clearCookies
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types){
var local = this.ext.persist,
prefix = local.cookiePrefix;
types = types || "active expanded focus selected";
if(types.indexOf(ACTIVE) >= 0){
local._data(prefix + ACTIVE, null);
}
if(types.indexOf(EXPANDED) >= 0){
local._data(prefix + EXPANDED, null);
}
if(types.indexOf(FOCUS) >= 0){
local._data(prefix + FOCUS, null);
}
if(types.indexOf(SELECTED) >= 0){
local._data(prefix + SELECTED, null);
}
};
/**
* [ext-persist] Return persistence information from cookies
*
* Called like
* $("#tree").fancytree("getTree").getPersistData();
*
* @alias Fancytree#getPersistData
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.getPersistData = function(){
var local = this.ext.persist,
prefix = local.cookiePrefix,
delim = local.cookieDelimiter,
res = {};
res[ACTIVE] = local._data(prefix + ACTIVE);
res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim);
res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim);
res[FOCUS] = local._data(prefix + FOCUS);
return res;
};
/* *****************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "persist",
version: "0.3.0",
// Default options for this extension.
options: {
cookieDelimiter: "~",
cookiePrefix: undefined, // 'fancytree-<treeId>-' by default
cookie: {
raw: false,
expires: "",
path: "",
domain: "",
secure: false
},
expandLazy: false, // true: recursively expand and load lazy nodes
overrideSource: true, // true: cookie takes precedence over `source` data attributes.
store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore
types: "active expanded focus selected"
},
/* Generic read/write string data to cookie, sessionStorage or localStorage. */
_data: function(key, value){
var ls = this._local.localStorage; // null, sessionStorage, or localStorage
if( value === undefined ) {
return ls ? ls.getItem(key) : $.cookie(key);
} else if ( value === null ) {
if( ls ) {
ls.removeItem(key);
} else {
$.removeCookie(key);
}
} else {
if( ls ) {
ls.setItem(key, value);
} else {
$.cookie(key, value, this.options.persist.cookie);
}
}
},
/* Append `key` to a cookie. */
_appendKey: function(type, key, flag){
key = "" + key; // #90
var local = this._local,
instOpts = this.options.persist,
delim = instOpts.cookieDelimiter,
cookieName = local.cookiePrefix + type,
data = local._data(cookieName),
keyList = data ? data.split(delim) : [],
idx = $.inArray(key, keyList);
// Remove, even if we add a key, so the key is always the last entry
if(idx >= 0){
keyList.splice(idx, 1);
}
// Append key to cookie
if(flag){
keyList.push(key);
}
local._data(cookieName, keyList.join(delim));
},
treeInit: function(ctx){
var tree = ctx.tree,
opts = ctx.options,
local = this._local,
instOpts = this.options.persist;
// For 'auto' or 'cookie' mode, the cookie plugin must be available
_assert(instOpts.store === "localStore" || $.cookie, "Missing required plugin for 'persist' extension: jquery.cookie.js");
local.cookiePrefix = instOpts.cookiePrefix || ("fancytree-" + tree._id + "-");
local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0;
local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0;
local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0;
local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0;
if( instOpts.store === "cookie" || !window.localStorage ) {
local.localStorage = null;
} else {
local.localStorage = (instOpts.store === "local") ? window.localStorage : window.sessionStorage;
}
// Bind init-handler to apply cookie state
tree.$div.bind("fancytreeinit", function(event){
var cookie, dfd, i, keyList, node,
prevFocus = local._data(local.cookiePrefix + FOCUS); // record this before node.setActive() overrides it;
// tree.debug("document.cookie:", document.cookie);
cookie = local._data(local.cookiePrefix + EXPANDED);
keyList = cookie && cookie.split(instOpts.cookieDelimiter);
if( local.storeExpanded ) {
// Recursively load nested lazy nodes if expandLazy is 'expand' or 'load'
// Also remove expand-cookies for unmatched nodes
dfd = _loadLazyNodes(tree, local, keyList, instOpts.expandLazy ? "expand" : false , null);
} else {
// nothing to do
dfd = new $.Deferred().resolve();
}
dfd.done(function(){
if(local.storeSelected){
cookie = local._data(local.cookiePrefix + SELECTED);
if(cookie){
keyList = cookie.split(instOpts.cookieDelimiter);
for(i=0; i<keyList.length; i++){
node = tree.getNodeByKey(keyList[i]);
if(node){
if(node.selected === undefined || instOpts.overrideSource && (node.selected === false)){
// node.setSelected();
node.selected = true;
node.renderStatus();
}
}else{
// node is no longer member of the tree: remove from cookie also
local._appendKey(SELECTED, keyList[i], false);
}
}
}
// In selectMode 3 we have to fix the child nodes, since we
// only stored the selected *top* nodes
if( tree.options.selectMode === 3 ){
tree.visit(function(n){
if( n.selected ) {
n.fixSelection3AfterClick();
return "skip";
}
});
}
}
if(local.storeActive){
cookie = local._data(local.cookiePrefix + ACTIVE);
if(cookie && (opts.persist.overrideSource || !tree.activeNode)){
node = tree.getNodeByKey(cookie);
if(node){
node.debug("persist: set active", cookie);
// We only want to set the focus if the container
// had the keyboard focus before
node.setActive(true, {noFocus: true});
}
}
}
if(local.storeFocus && prevFocus){
node = tree.getNodeByKey(prevFocus);
if(node){
// node.debug("persist: set focus", cookie);
if( tree.options.titlesTabbable ) {
$(node.span).find(".fancytree-title").focus();
} else {
$(tree.$container).focus();
}
// node.setFocus();
}
}
tree._triggerTreeEvent("restore", null, {});
});
});
// Init the tree
return this._superApply(arguments);
},
nodeSetActive: function(ctx, flag, opts) {
var res,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if(local.storeActive){
local._data(local.cookiePrefix + ACTIVE, this.activeNode ? this.activeNode.key : null);
}
return res;
},
nodeSetExpanded: function(ctx, flag, opts) {
var res,
node = ctx.node,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if(local.storeExpanded){
local._appendKey(EXPANDED, node.key, flag);
}
return res;
},
nodeSetFocus: function(ctx, flag) {
var res,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if( local.storeFocus ) {
local._data(local.cookiePrefix + FOCUS, this.focusNode ? this.focusNode.key : null);
}
return res;
},
nodeSetSelected: function(ctx, flag) {
var res, selNodes,
tree = ctx.tree,
node = ctx.node,
local = this._local;
flag = (flag !== false);
res = this._superApply(arguments);
if(local.storeSelected){
if( tree.options.selectMode === 3 ){
// In selectMode 3 we only store the the selected *top* nodes.
// De-selecting a node may also de-select some parents, so we
// calculate the current status again
selNodes = $.map(tree.getSelectedNodes(true), function(n){
return n.key;
});
selNodes = selNodes.join(ctx.options.persist.cookieDelimiter);
local._data(local.cookiePrefix + SELECTED, selNodes);
} else {
local._appendKey(SELECTED, node.key, flag);
}
}
return res;
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.table.js
*
* Render tree as table (aka 'treegrid', 'tabletree').
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
/* *****************************************************************************
* Private functions and variables
*/
function _assert(cond, msg){
msg = msg || "";
if(!cond){
$.error("Assertion failed " + msg);
}
}
function insertSiblingAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/* Show/hide all rows that are structural descendants of `parent`. */
function setChildRowVisibility(parent, flag) {
parent.visit(function(node){
var tr = node.tr;
// currentFlag = node.hide ? false : flag; // fix for ext-filter
if(tr){
tr.style.display = (node.hide || !flag) ? "none" : "";
}
if(!node.expanded){
return "skip";
}
});
}
/* Find node that is rendered in previous row. */
function findPrevRowNode(node){
var i, last, prev,
parent = node.parent,
siblings = parent ? parent.children : null;
if(siblings && siblings.length > 1 && siblings[0] !== node){
// use the lowest descendant of the preceeding sibling
i = $.inArray(node, siblings);
prev = siblings[i - 1];
_assert(prev.tr);
// descend to lowest child (with a <tr> tag)
while(prev.children){
last = prev.children[prev.children.length - 1];
if(!last.tr){
break;
}
prev = last;
}
}else{
// if there is no preceding sibling, use the direct parent
prev = parent;
}
return prev;
}
$.ui.fancytree.registerExtension({
name: "table",
version: "0.2.1",
// Default options for this extension.
options: {
checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx)
customStatus: false, // true: generate renderColumns events for status nodes
indentation: 16, // indent every node level by 16px
nodeColumnIdx: 0 // render node expander, icon, and title to this column (default: #0)
},
// Overide virtual methods for this extension.
// `this` : is this extension object
// `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
treeInit: function(ctx){
var i, $row, tdRole,
tree = ctx.tree,
$table = tree.widget.element;
$table.addClass("fancytree-container fancytree-ext-table");
tree.tbody = $table.find("> tbody")[0];
tree.columnCount = $("thead >tr >th", $table).length;
$(tree.tbody).empty();
tree.rowFragment = document.createDocumentFragment();
$row = $("<tr />");
tdRole = "";
if(ctx.options.aria){
$row.attr("role", "row");
tdRole = " role='gridcell'";
}
for(i=0; i<tree.columnCount; i++) {
if(ctx.options.table.nodeColumnIdx === i){
$row.append("<td" + tdRole + "><span class='fancytree-node' /></td>");
}else{
$row.append("<td" + tdRole + " />");
}
}
tree.rowFragment.appendChild($row.get(0));
// Make sure that status classes are set on the node's <tr> elements
tree.statusClassPropName = "tr";
tree.ariaPropName = "tr";
this.nodeContainerAttrName = "tr";
this._superApply(arguments);
// standard Fancytree created a root UL
$(tree.rootNode.ul).remove();
tree.rootNode.ul = null;
tree.$container = $table;
// Add container to the TAB chain
this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
if(this.options.aria){
tree.$container
.attr("role", "treegrid")
.attr("aria-readonly", true);
}
},
/* Called by nodeRender to sync node order with tag order.*/
// nodeFixOrder: function(ctx) {
// },
nodeRemoveChildMarkup: function(ctx) {
var node = ctx.node;
// node.debug("nodeRemoveChildMarkup()");
node.visit(function(n){
if(n.tr){
$(n.tr).remove();
n.tr = null;
}
});
},
nodeRemoveMarkup: function(ctx) {
var node = ctx.node;
// node.debug("nodeRemoveMarkup()");
if(node.tr){
$(node.tr).remove();
node.tr = null;
}
this.nodeRemoveChildMarkup(ctx);
},
/* Override standard render. */
nodeRender: function(ctx, force, deep, collapsed, _recursive) {
var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx,
tree = ctx.tree,
node = ctx.node,
opts = ctx.options,
isRootNode = !node.parent;
if( !_recursive ){
ctx.hasCollapsedParents = node.parent && !node.parent.expanded;
}
// $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr));
if( !isRootNode ){
if(!node.tr){
if( ctx.hasCollapsedParents /*&& !node.parent.tr*/ ) {
// #166: we assume that the parent will be (recursively) rendered
// later anyway.
node.debug("nodeRender ignored due to unrendered parent");
return;
}
// Create new <tr> after previous row
newRow = tree.rowFragment.firstChild.cloneNode(true);
prevNode = findPrevRowNode(node);
// $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key);
_assert(prevNode);
if(collapsed === true && _recursive){
// hide all child rows, so we can use an animation to show it later
newRow.style.display = "none";
}else if(deep && ctx.hasCollapsedParents){
// also hide this row if deep === true but any parent is collapsed
newRow.style.display = "none";
// newRow.style.color = "red";
}
if(!prevNode.tr){
_assert(!prevNode.parent, "prev. row must have a tr, or is system root");
tree.tbody.appendChild(newRow);
}else{
insertSiblingAfter(prevNode.tr, newRow);
}
node.tr = newRow;
if( node.key && opts.generateIds ){
node.tr.id = opts.idPrefix + node.key;
}
node.tr.ftnode = node;
if(opts.aria){
// TODO: why doesn't this work:
// node.li.role = "treeitem";
$(node.tr).attr("aria-labelledby", "ftal_" + node.key);
}
node.span = $("span.fancytree-node", node.tr).get(0);
// Set icon, link, and title (normally this is only required on initial render)
this.nodeRenderTitle(ctx);
// Allow tweaking, binding, after node was created for the first time
// tree._triggerNodeEvent("createNode", ctx);
if ( opts.createNode ){
opts.createNode.call(tree, {type: "createNode"}, ctx);
}
} else {
if( force ) {
// Set icon, link, and title (normally this is only required on initial render)
this.nodeRenderTitle(ctx); // triggers renderColumns()
} else {
// Update element classes according to node state
this.nodeRenderStatus(ctx);
}
}
}
// Allow tweaking after node state was rendered
// tree._triggerNodeEvent("renderNode", ctx);
if ( opts.renderNode ){
opts.renderNode.call(tree, {type: "renderNode"}, ctx);
}
// Visit child nodes
// Add child markup
children = node.children;
if(children && (isRootNode || deep || node.expanded)){
for(i=0, l=children.length; i<l; i++) {
subCtx = $.extend({}, ctx, {node: children[i]});
subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded;
this.nodeRender(subCtx, force, deep, collapsed, true);
}
}
// Make sure, that <tr> order matches node.children order.
if(children && !_recursive){ // we only have to do it once, for the root branch
prevTr = node.tr || null;
firstTr = tree.tbody.firstChild;
// Iterate over all descendants
node.visit(function(n){
if(n.tr){
if(!n.parent.expanded && n.tr.style.display !== "none"){
// fix after a node was dropped over a collapsed
n.tr.style.display = "none";
setChildRowVisibility(n, false);
}
if(n.tr.previousSibling !== prevTr){
node.debug("_fixOrder: mismatch at node: " + n);
var nextTr = prevTr ? prevTr.nextSibling : firstTr;
tree.tbody.insertBefore(n.tr, nextTr);
}
prevTr = n.tr;
}
});
}
// Update element classes according to node state
// if(!isRootNode){
// this.nodeRenderStatus(ctx);
// }
},
nodeRenderTitle: function(ctx, title) {
var $cb,
node = ctx.node,
opts = ctx.options;
this._superApply(arguments);
// Move checkbox to custom column
if(opts.checkbox && opts.table.checkboxColumnIdx != null ){
$cb = $("span.fancytree-checkbox", node.span).detach();
$(node.tr).find("td").eq(+opts.table.checkboxColumnIdx).html($cb);
}
// Update element classes according to node state
if( ! node.isRoot() ){
this.nodeRenderStatus(ctx);
}
if( !opts.table.customStatus && node.isStatusNode() ) {
// default rendering for status node: leave other cells empty
} else if ( opts.renderColumns ) {
// Let user code write column content
opts.renderColumns.call(ctx.tree, {type: "renderColumns"}, ctx);
}
},
nodeRenderStatus: function(ctx) {
var indent,
node = ctx.node,
opts = ctx.options;
this._superApply(arguments);
$(node.tr).removeClass("fancytree-node");
// indent
indent = (node.getLevel() - 1) * opts.table.indentation;
$(node.span).css({marginLeft: indent + "px"});
},
/* Expand node, return Deferred.promise. */
nodeSetExpanded: function(ctx, flag, opts) {
var dfd = new $.Deferred(),
subOpts = $.extend({}, opts, {noEvents: true, noAnimation: true});
opts = opts || {};
function _afterExpand(ok) {
flag = (flag !== false);
setChildRowVisibility(ctx.node, flag);
if( ok ) {
if( flag && ctx.options.autoScroll && !opts.noAnimation && ctx.node.hasChildren() ) {
// Scroll down to last child, but keep current node visible
ctx.node.getLastChild().scrollIntoView(true, {topNode: ctx.node}).always(function(){
if( !opts.noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
dfd.resolveWith(ctx.node);
});
} else {
if( !opts.noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
dfd.resolveWith(ctx.node);
}
} else {
if( !opts.noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
dfd.rejectWith(ctx.node);
}
}
// Call base-expand with disabled events and animation
this._super(ctx, flag, subOpts).done(function () {
_afterExpand(true);
}).fail(function () {
_afterExpand(false);
});
return dfd.promise();
},
nodeSetStatus: function(ctx, status, message, details) {
if(status === "ok"){
var node = ctx.node,
firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
$(firstChild.tr).remove();
}
}
return this._superApply(arguments);
},
treeClear: function(ctx) {
this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode));
return this._superApply(arguments);
}
/*,
treeSetFocus: function(ctx, flag) {
// alert("treeSetFocus" + ctx.tree.$container);
ctx.tree.$container.focus();
$.ui.fancytree.focusTree = ctx.tree;
}*/
});
}(jQuery, window, document));
/*!
* jquery.fancytree.themeroller.js
*
* Enable jQuery UI ThemeRoller styles.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* @see http://jqueryui.com/themeroller/
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "themeroller",
version: "0.0.1",
// Default options for this extension.
options: {
activeClass: "ui-state-active",
foccusClass: "ui-state-focus",
hoverClass: "ui-state-hover",
selectedClass: "ui-state-highlight"
},
treeInit: function(ctx){
this._superApply(arguments);
var $el = ctx.widget.element;
if($el[0].nodeName === "TABLE"){
$el.addClass("ui-widget ui-corner-all");
$el.find(">thead tr").addClass("ui-widget-header");
$el.find(">tbody").addClass("ui-widget-conent");
}else{
$el.addClass("ui-widget ui-widget-content ui-corner-all");
}
$el.delegate(".fancytree-node", "mouseenter mouseleave", function(event){
var node = $.ui.fancytree.getNode(event.target),
flag = (event.type === "mouseenter");
node.debug("hover: " + flag);
$(node.span).toggleClass("ui-state-hover ui-corner-all", flag);
});
},
treeDestroy: function(ctx){
this._superApply(arguments);
ctx.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all");
},
nodeRenderStatus: function(ctx){
var node = ctx.node,
$el = $(node.span);
this._superApply(arguments);
/*
.ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons.
.ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons.
.ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons.
.ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons.
.ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
.ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
.ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons.
*/
$el.toggleClass("ui-state-active", node.isActive());
$el.toggleClass("ui-state-focus", node.hasFocus());
$el.toggleClass("ui-state-highlight", node.isSelected());
// node.debug("ext-themeroller.nodeRenderStatus: ", node.span.className);
}
});
}(jQuery, window, document));
/*!
* jquery.fancytree.wide.js
* Support for 100% wide selection bars.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.8.1
* @date 2015-03-01T20:28
*/
;(function($, window, document, undefined) {
"use strict";
var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"]
/*******************************************************************************
* Private functions and variables
*/
// var _assert = $.ui.fancytree.assert;
/* Calculate inner width without scrollbar */
// function realInnerWidth($el) {
// // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/
// // inst.contWidth = parseFloat(this.$container.css("width"), 10);
// // 'Client width without scrollbar' - 'padding'
// return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10));
// }
/* Create a global embedded CSS style for the tree. */
function defineHeadStyleElement(id, cssText) {
id = "fancytree-style-" + id;
var $headStyle = $("#" + id);
if( !cssText ) {
$headStyle.remove();
return null;
}
if( !$headStyle.length ) {
$headStyle = $("<style />")
.attr("id", id)
.addClass("fancytree-style")
.prop("type", "text/css")
.appendTo("head");
}
try {
$headStyle.html(cssText);
} catch ( e ) {
// fix for IE 6-8
$headStyle[0].styleSheet.cssText = cssText;
}
return $headStyle;
}
/* Calculate the CSS rules that indent title spans. */
function renderLevelCss(containerId, depth, levelOfs, lineOfs, measureUnit) {
var i,
prefix = "#" + containerId + " span.fancytree-level-",
rules = [];
for(i = 0; i < depth; i++) {
rules.push(prefix + (i + 1) + " span.fancytree-title { padding-left: " +
(i * levelOfs + lineOfs) + measureUnit + "; }");
}
// Some UI animations wrap the UL inside a DIV and set position:relative on both.
// This breaks the left:0 and padding-left:nn settings of the title
rules.push("#" + containerId +
" div.ui-effects-wrapper ul li span.fancytree-title " +
"{ padding-left: 3px; position: static; width: auto; }");
return rules.join("\n");
}
// /**
// * [ext-wide] Recalculate the width of the selection bar after the tree container
// * was resized.<br>
// * May be called explicitly on container resize, since there is no resize event
// * for DIV tags.
// *
// * @alias Fancytree#wideUpdate
// * @requires jquery.fancytree.wide.js
// */
// $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){
// var inst = this.ext.wide,
// prevCw = inst.contWidth,
// prevLo = inst.lineOfs;
// inst.contWidth = realInnerWidth(this.$container);
// // Each title is precceeded by 2 or 3 icons (16px + 3 margin)
// // + 1px title border and 3px title padding
// // TODO: use code from treeInit() below
// inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19;
// if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) {
// this.debug("wideUpdate: " + inst.contWidth);
// this.visit(function(node){
// node.tree._callHook("nodeRenderTitle", node);
// });
// }
// };
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "wide",
version: "0.0.3",
// Default options for this extension.
options: {
iconWidth: null, // Adjust this if @fancy-icon-width != "16px"
iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px"
levelOfs: null // Adjust this if ul padding != "16px"
},
treeCreate: function(ctx){
this._superApply(arguments);
this.$container.addClass("fancytree-ext-wide");
var containerId, cssText, iconSpacingUnit, iconWidthUnit, levelOfsUnit,
instOpts = ctx.options.wide,
// css sniffing
$dummyLI = $("<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />")
.appendTo(ctx.tree.$container),
$dummyIcon = $dummyLI.find(".fancytree-icon"),
$dummyUL = $dummyLI.find("ul"),
// $dummyTitle = $dummyLI.find(".fancytree-title"),
iconSpacing = instOpts.iconSpacing || $dummyIcon.css("margin-left"),
iconWidth = instOpts.iconWidth || $dummyIcon.css("width"),
levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left");
$dummyLI.remove();
iconSpacingUnit = iconSpacing.match(reNumUnit)[2];
iconSpacing = parseFloat(iconSpacing, 10);
iconWidthUnit = iconWidth.match(reNumUnit)[2];
iconWidth = parseFloat(iconWidth, 10);
levelOfsUnit = levelOfs.match(reNumUnit)[2];
if( iconSpacingUnit !== iconWidthUnit || levelOfsUnit !== iconWidthUnit ) {
$.error("iconWidth, iconSpacing, and levelOfs must have the same css measure unit");
}
this._local.measureUnit = iconWidthUnit;
this._local.levelOfs = parseFloat(levelOfs);
this._local.lineOfs = (ctx.options.checkbox ? 3 : 2) * (iconWidth + iconSpacing) + iconSpacing;
this._local.maxDepth = 10;
// Get/Set a unique Id on the container (if not already exists)
containerId = this.$container.uniqueId().attr("id");
// Generated css rules for some levels (extended on demand)
cssText = renderLevelCss(containerId, this._local.maxDepth,
this._local.levelOfs, this._local.lineOfs, this._local.measureUnit);
defineHeadStyleElement(containerId, cssText);
},
treeDestroy: function(ctx){
// Remove generated css rules
defineHeadStyleElement(this.$container.attr("id"), null);
return this._superApply(arguments);
},
nodeRenderStatus: function(ctx) {
var containerId, cssText, res,
node = ctx.node,
level = node.getLevel();
res = this._superApply(arguments);
// Generate some more level-n rules if required
if( level > this._local.maxDepth ) {
containerId = this.$container.attr("id");
this._local.maxDepth *= 2;
node.debug("Define global ext-wide css up to level " + this._local.maxDepth);
cssText = renderLevelCss(containerId, this._local.maxDepth,
this._local.levelOfs, this._local.lineOfs, this._local.measureUnit);
defineHeadStyleElement(containerId, cssText);
}
// Add level-n class to apply indentation padding.
// (Setting element style would not work, since it cannot easily be
// overriden while animations run)
$(node.span).addClass("fancytree-level-" + level);
return res;
}
});
}(jQuery, window, document));
|
pages/secret.js | jayzehngebot/dod3 | /**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { Component } from 'react';
export default class extends Component {
render() {
return (
<div>
<h1>secret</h1>
<p>123</p>
</div>
);
}
}
|
files/react/0.10.0/JSXTransformer.js | dnbard/jsdelivr | /**
* JSXTransformer v0.10.0
*/
!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.JSXTransformer=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){
/**
* The buffer module from node.js, for the browser.
*
* Author: Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* License: MIT
*
* `npm install buffer`
*/
var base64 = _dereq_('base64-js')
var ieee754 = _dereq_('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = Buffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192
/**
* If `Buffer._useTypedArrays`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (compatible down to IE6)
*/
Buffer._useTypedArrays = (function () {
// Detect if browser supports Typed Arrays. Supported browsers are IE 10+,
// Firefox 4+, Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+.
if (typeof Uint8Array !== 'function' || typeof ArrayBuffer !== 'function')
return false
// Does the browser support adding properties to `Uint8Array` instances? If
// not, then that's the same as no `Uint8Array` support. We need to be able to
// add all the node Buffer API methods.
// Bug in Firefox 4-29, now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
try {
var arr = new Uint8Array(0)
arr.foo = function () { return 42 }
return 42 === arr.foo() &&
typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding, noZero) {
if (!(this instanceof Buffer))
return new Buffer(subject, encoding, noZero)
var type = typeof subject
// Workaround: node's base64 implementation allows for non-padded strings
// while base64-js does not.
if (encoding === 'base64' && type === 'string') {
subject = stringtrim(subject)
while (subject.length % 4 !== 0) {
subject = subject + '='
}
}
// Find the length
var length
if (type === 'number')
length = coerce(subject)
else if (type === 'string')
length = Buffer.byteLength(subject, encoding)
else if (type === 'object')
length = coerce(subject.length) // Assume object is an array
else
throw new Error('First argument needs to be a number, array or string.')
var buf
if (Buffer._useTypedArrays) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
buf = augment(new Uint8Array(length))
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
buf = this
buf.length = length
buf._isBuffer = true
}
var i
if (Buffer._useTypedArrays && typeof Uint8Array === 'function' &&
subject instanceof Uint8Array) {
// Speed optimization -- use set if we're copying from a Uint8Array
buf._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
for (i = 0; i < length; i++) {
if (Buffer.isBuffer(subject))
buf[i] = subject.readUInt8(i)
else
buf[i] = subject[i]
}
} else if (type === 'string') {
buf.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
for (i = 0; i < length; i++) {
buf[i] = 0
}
}
return buf
}
// STATIC METHODS
// ==============
Buffer.isEncoding = function (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.isBuffer = function (b) {
return !!(b !== null && b !== undefined && b._isBuffer)
}
Buffer.byteLength = function (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'hex':
ret = str.length / 2
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'base64':
ret = base64ToBytes(str).length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
default:
throw new Error('Unknown encoding')
}
return ret
}
Buffer.concat = function (list, totalLength) {
assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' +
'list should be an Array.')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (typeof totalLength !== 'number') {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
// BUFFER INSTANCE METHODS
// =======================
function _hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
assert(strLen % 2 === 0, 'Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var byte = parseInt(string.substr(i * 2, 2), 16)
assert(!isNaN(byte), 'Invalid hex string')
buf[offset + i] = byte
}
Buffer._charsWritten = i * 2
return i
}
function _utf8Write (buf, string, offset, length) {
var charsWritten = Buffer._charsWritten =
blitBuffer(utf8ToBytes(string), buf, offset, length)
return charsWritten
}
function _asciiWrite (buf, string, offset, length) {
var charsWritten = Buffer._charsWritten =
blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function _binaryWrite (buf, string, offset, length) {
return _asciiWrite(buf, string, offset, length)
}
function _base64Write (buf, string, offset, length) {
var charsWritten = Buffer._charsWritten =
blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function _utf16leWrite (buf, string, offset, length) {
var charsWritten = Buffer._charsWritten =
blitBuffer(utf16leToBytes(string), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = _hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = _utf8Write(this, string, offset, length)
break
case 'ascii':
ret = _asciiWrite(this, string, offset, length)
break
case 'binary':
ret = _binaryWrite(this, string, offset, length)
break
case 'base64':
ret = _base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = _utf16leWrite(this, string, offset, length)
break
default:
throw new Error('Unknown encoding')
}
return ret
}
Buffer.prototype.toString = function (encoding, start, end) {
var self = this
encoding = String(encoding || 'utf8').toLowerCase()
start = Number(start) || 0
end = (end !== undefined)
? Number(end)
: end = self.length
// Fastpath empty strings
if (end === start)
return ''
var ret
switch (encoding) {
case 'hex':
ret = _hexSlice(self, start, end)
break
case 'utf8':
case 'utf-8':
ret = _utf8Slice(self, start, end)
break
case 'ascii':
ret = _asciiSlice(self, start, end)
break
case 'binary':
ret = _binarySlice(self, start, end)
break
case 'base64':
ret = _base64Slice(self, start, end)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = _utf16leSlice(self, start, end)
break
default:
throw new Error('Unknown encoding')
}
return ret
}
Buffer.prototype.toJSON = function () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function (target, target_start, start, end) {
var source = this
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (!target_start) target_start = 0
// Copy 0 bytes; we're done
if (end === start) return
if (target.length === 0 || source.length === 0) return
// Fatal error conditions
assert(end >= start, 'sourceEnd < sourceStart')
assert(target_start >= 0 && target_start < target.length,
'targetStart out of bounds')
assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
// Are we oob?
if (end > this.length)
end = this.length
if (target.length - target_start < end - start)
end = target.length - target_start + start
// copy!
for (var i = 0; i < end - start; i++)
target[i + target_start] = this[i + start]
}
function _base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function _utf8Slice (buf, start, end) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
function _asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++)
ret += String.fromCharCode(buf[i])
return ret
}
function _binarySlice (buf, start, end) {
return _asciiSlice(buf, start, end)
}
function _hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function _utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i+1] * 256)
}
return res
}
Buffer.prototype.slice = function (start, end) {
var len = this.length
start = clamp(start, len, 0)
end = clamp(end, len, len)
if (Buffer._useTypedArrays) {
return augment(this.subarray(start, end))
} else {
var sliceLen = end - start
var newBuf = new Buffer(sliceLen, undefined, true)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
return newBuf
}
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
Buffer.prototype.set = function (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
Buffer.prototype.readUInt8 = function (offset, noAssert) {
if (!noAssert) {
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < this.length, 'Trying to read beyond buffer length')
}
if (offset >= this.length)
return
return this[offset]
}
function _readUInt16 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val
if (littleEndian) {
val = buf[offset]
if (offset + 1 < len)
val |= buf[offset + 1] << 8
} else {
val = buf[offset] << 8
if (offset + 1 < len)
val |= buf[offset + 1]
}
return val
}
Buffer.prototype.readUInt16LE = function (offset, noAssert) {
return _readUInt16(this, offset, true, noAssert)
}
Buffer.prototype.readUInt16BE = function (offset, noAssert) {
return _readUInt16(this, offset, false, noAssert)
}
function _readUInt32 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val
if (littleEndian) {
if (offset + 2 < len)
val = buf[offset + 2] << 16
if (offset + 1 < len)
val |= buf[offset + 1] << 8
val |= buf[offset]
if (offset + 3 < len)
val = val + (buf[offset + 3] << 24 >>> 0)
} else {
if (offset + 1 < len)
val = buf[offset + 1] << 16
if (offset + 2 < len)
val |= buf[offset + 2] << 8
if (offset + 3 < len)
val |= buf[offset + 3]
val = val + (buf[offset] << 24 >>> 0)
}
return val
}
Buffer.prototype.readUInt32LE = function (offset, noAssert) {
return _readUInt32(this, offset, true, noAssert)
}
Buffer.prototype.readUInt32BE = function (offset, noAssert) {
return _readUInt32(this, offset, false, noAssert)
}
Buffer.prototype.readInt8 = function (offset, noAssert) {
if (!noAssert) {
assert(offset !== undefined && offset !== null,
'missing offset')
assert(offset < this.length, 'Trying to read beyond buffer length')
}
if (offset >= this.length)
return
var neg = this[offset] & 0x80
if (neg)
return (0xff - this[offset] + 1) * -1
else
return this[offset]
}
function _readInt16 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val = _readUInt16(buf, offset, littleEndian, true)
var neg = val & 0x8000
if (neg)
return (0xffff - val + 1) * -1
else
return val
}
Buffer.prototype.readInt16LE = function (offset, noAssert) {
return _readInt16(this, offset, true, noAssert)
}
Buffer.prototype.readInt16BE = function (offset, noAssert) {
return _readInt16(this, offset, false, noAssert)
}
function _readInt32 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val = _readUInt32(buf, offset, littleEndian, true)
var neg = val & 0x80000000
if (neg)
return (0xffffffff - val + 1) * -1
else
return val
}
Buffer.prototype.readInt32LE = function (offset, noAssert) {
return _readInt32(this, offset, true, noAssert)
}
Buffer.prototype.readInt32BE = function (offset, noAssert) {
return _readInt32(this, offset, false, noAssert)
}
function _readFloat (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
}
return ieee754.read(buf, offset, littleEndian, 23, 4)
}
Buffer.prototype.readFloatLE = function (offset, noAssert) {
return _readFloat(this, offset, true, noAssert)
}
Buffer.prototype.readFloatBE = function (offset, noAssert) {
return _readFloat(this, offset, false, noAssert)
}
function _readDouble (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
}
return ieee754.read(buf, offset, littleEndian, 52, 8)
}
Buffer.prototype.readDoubleLE = function (offset, noAssert) {
return _readDouble(this, offset, true, noAssert)
}
Buffer.prototype.readDoubleBE = function (offset, noAssert) {
return _readDouble(this, offset, false, noAssert)
}
Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < this.length, 'trying to write beyond buffer length')
verifuint(value, 0xff)
}
if (offset >= this.length) return
this[offset] = value
}
function _writeUInt16 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
verifuint(value, 0xffff)
}
var len = buf.length
if (offset >= len)
return
for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
buf[offset + i] =
(value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
_writeUInt16(this, value, offset, true, noAssert)
}
Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
_writeUInt16(this, value, offset, false, noAssert)
}
function _writeUInt32 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
verifuint(value, 0xffffffff)
}
var len = buf.length
if (offset >= len)
return
for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
buf[offset + i] =
(value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
_writeUInt32(this, value, offset, true, noAssert)
}
Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
_writeUInt32(this, value, offset, false, noAssert)
}
Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < this.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7f, -0x80)
}
if (offset >= this.length)
return
if (value >= 0)
this.writeUInt8(value, offset, noAssert)
else
this.writeUInt8(0xff + value + 1, offset, noAssert)
}
function _writeInt16 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7fff, -0x8000)
}
var len = buf.length
if (offset >= len)
return
if (value >= 0)
_writeUInt16(buf, value, offset, littleEndian, noAssert)
else
_writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
}
Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
_writeInt16(this, value, offset, true, noAssert)
}
Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
_writeInt16(this, value, offset, false, noAssert)
}
function _writeInt32 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7fffffff, -0x80000000)
}
var len = buf.length
if (offset >= len)
return
if (value >= 0)
_writeUInt32(buf, value, offset, littleEndian, noAssert)
else
_writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
}
Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
_writeInt32(this, value, offset, true, noAssert)
}
Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
_writeInt32(this, value, offset, false, noAssert)
}
function _writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
var len = buf.length
if (offset >= len)
return
ieee754.write(buf, value, offset, littleEndian, 23, 4)
}
Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
_writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
_writeFloat(this, value, offset, false, noAssert)
}
function _writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 7 < buf.length,
'Trying to write beyond buffer length')
verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
var len = buf.length
if (offset >= len)
return
ieee754.write(buf, value, offset, littleEndian, 52, 8)
}
Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
_writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
_writeDouble(this, value, offset, false, noAssert)
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (typeof value === 'string') {
value = value.charCodeAt(0)
}
assert(typeof value === 'number' && !isNaN(value), 'value is not a number')
assert(end >= start, 'end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
assert(start >= 0 && start < this.length, 'start out of bounds')
assert(end >= 0 && end <= this.length, 'end out of bounds')
for (var i = start; i < end; i++) {
this[i] = value
}
}
Buffer.prototype.inspect = function () {
var out = []
var len = this.length
for (var i = 0; i < len; i++) {
out[i] = toHex(this[i])
if (i === exports.INSPECT_MAX_BYTES) {
out[i + 1] = '...'
break
}
}
return '<Buffer ' + out.join(' ') + '>'
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function () {
if (typeof Uint8Array === 'function') {
if (Buffer._useTypedArrays) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1)
buf[i] = this[i]
return buf.buffer
}
} else {
throw new Error('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
var BP = Buffer.prototype
/**
* Augment the Uint8Array *instance* (not the class!) with Buffer methods
*/
function augment (arr) {
arr._isBuffer = true
// save reference to original Uint8Array get/set methods before overwriting
arr._get = arr.get
arr._set = arr.set
// deprecated, will be removed in node 0.13+
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
// slice(start, end)
function clamp (index, len, defaultValue) {
if (typeof index !== 'number') return defaultValue
index = ~~index; // Coerce to integer.
if (index >= len) return len
if (index >= 0) return index
index += len
if (index >= 0) return index
return 0
}
function coerce (length) {
// Coerce length to a number (possibly NaN), round up
// in case it's fractional (e.g. 123.456) then do a
// double negate to coerce a NaN to 0. Easy, right?
length = ~~Math.ceil(+length)
return length < 0 ? 0 : length
}
function isArray (subject) {
return (Array.isArray || function (subject) {
return Object.prototype.toString.call(subject) === '[object Array]'
})(subject)
}
function isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
var b = str.charCodeAt(i)
if (b <= 0x7F)
byteArray.push(str.charCodeAt(i))
else {
var start = i
if (b >= 0xD800 && b <= 0xDFFF) i++
var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
for (var j = 0; j < h.length; j++)
byteArray.push(parseInt(h[j], 16))
}
}
return byteArray
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(str)
}
function blitBuffer (src, dst, offset, length) {
var pos
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length))
break
dst[i + offset] = src[i]
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
/*
* We have to make sure that the value is a valid integer. This means that it
* is non-negative. It has no fractional component and that it does not
* exceed the maximum allowed value.
*/
function verifuint (value, max) {
assert(typeof value === 'number', 'cannot write a non-number as a number')
assert(value >= 0, 'specified a negative value for writing an unsigned value')
assert(value <= max, 'value is larger than maximum value for type')
assert(Math.floor(value) === value, 'value has a fractional component')
}
function verifsint (value, max, min) {
assert(typeof value === 'number', 'cannot write a non-number as a number')
assert(value <= max, 'value larger than maximum allowed value')
assert(value >= min, 'value smaller than minimum allowed value')
assert(Math.floor(value) === value, 'value has a fractional component')
}
function verifIEEE754 (value, max, min) {
assert(typeof value === 'number', 'cannot write a non-number as a number')
assert(value <= max, 'value larger than maximum allowed value')
assert(value >= min, 'value smaller than minimum allowed value')
}
function assert (test, message) {
if (!test) throw new Error(message || 'Failed assertion')
}
},{"base64-js":2,"ieee754":3}],2:[function(_dereq_,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var ZERO = '0'.charCodeAt(0)
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS)
return 62 // '+'
if (code === SLASH)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
module.exports.toByteArray = b64ToByteArray
module.exports.fromByteArray = uint8ToBase64
}())
},{}],3:[function(_dereq_,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity);
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],4:[function(_dereq_,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 = [];
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');
};
},{}],5:[function(_dereq_,module,exports){
(function (process){
// 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.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,_dereq_("/Users/poshannessy/FB/code/react/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"))
},{"/Users/poshannessy/FB/code/react/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":4}],6:[function(_dereq_,module,exports){
/*
Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint bitwise:true plusplus:true */
/*global esprima:true, define:true, exports:true, window: true,
throwError: true, generateStatement: true, peek: true,
parseAssignmentExpression: true, parseBlock: true,
parseClassExpression: true, parseClassDeclaration: true, parseExpression: true,
parseForStatement: true,
parseFunctionDeclaration: true, parseFunctionExpression: true,
parseFunctionSourceElements: true, parseVariableIdentifier: true,
parseImportSpecifier: true,
parseLeftHandSideExpression: true, parseParams: true, validateParam: true,
parseSpreadOrAssignmentExpression: true,
parseStatement: true, parseSourceElement: true, parseModuleBlock: true, parseConciseBody: true,
advanceXJSChild: true, isXJSIdentifierStart: true, isXJSIdentifierPart: true,
scanXJSStringLiteral: true, scanXJSIdentifier: true,
parseXJSAttributeValue: true, parseXJSChild: true, parseXJSElement: true, parseXJSExpressionContainer: true, parseXJSEmptyExpression: true,
parseTypeAnnotation: true, parseTypeAnnotatableIdentifier: true,
parseYieldExpression: true
*/
(function (root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
// Rhino, and plain browser loading.
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.esprima = {}));
}
}(this, function (exports) {
'use strict';
var Token,
TokenName,
FnExprTokens,
Syntax,
PropertyKind,
Messages,
Regex,
SyntaxTreeDelegate,
XHTMLEntities,
ClassPropertyType,
source,
strict,
index,
lineNumber,
lineStart,
length,
delegate,
lookahead,
state,
extra;
Token = {
BooleanLiteral: 1,
EOF: 2,
Identifier: 3,
Keyword: 4,
NullLiteral: 5,
NumericLiteral: 6,
Punctuator: 7,
StringLiteral: 8,
RegularExpression: 9,
Template: 10,
XJSIdentifier: 11,
XJSText: 12
};
TokenName = {};
TokenName[Token.BooleanLiteral] = 'Boolean';
TokenName[Token.EOF] = '<end>';
TokenName[Token.Identifier] = 'Identifier';
TokenName[Token.Keyword] = 'Keyword';
TokenName[Token.NullLiteral] = 'Null';
TokenName[Token.NumericLiteral] = 'Numeric';
TokenName[Token.Punctuator] = 'Punctuator';
TokenName[Token.StringLiteral] = 'String';
TokenName[Token.XJSIdentifier] = 'XJSIdentifier';
TokenName[Token.XJSText] = 'XJSText';
TokenName[Token.RegularExpression] = 'RegularExpression';
// A function following one of those tokens is an expression.
FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
'return', 'case', 'delete', 'throw', 'void',
// assignment operators
'=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
'&=', '|=', '^=', ',',
// binary/unary operators
'+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
'|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
'<=', '<', '>', '!=', '!=='];
Syntax = {
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrowFunctionExpression: 'ArrowFunctionExpression',
AssignmentExpression: 'AssignmentExpression',
BinaryExpression: 'BinaryExpression',
BlockStatement: 'BlockStatement',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ClassHeritage: 'ClassHeritage',
ComprehensionBlock: 'ComprehensionBlock',
ComprehensionExpression: 'ComprehensionExpression',
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DebuggerStatement: 'DebuggerStatement',
DoWhileStatement: 'DoWhileStatement',
EmptyStatement: 'EmptyStatement',
ExportDeclaration: 'ExportDeclaration',
ExportBatchSpecifier: 'ExportBatchSpecifier',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForInStatement: 'ForInStatement',
ForOfStatement: 'ForOfStatement',
ForStatement: 'ForStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportDeclaration: 'ImportDeclaration',
ImportSpecifier: 'ImportSpecifier',
LabeledStatement: 'LabeledStatement',
Literal: 'Literal',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MethodDefinition: 'MethodDefinition',
ModuleDeclaration: 'ModuleDeclaration',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
Program: 'Program',
Property: 'Property',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
SwitchCase: 'SwitchCase',
SwitchStatement: 'SwitchStatement',
TaggedTemplateExpression: 'TaggedTemplateExpression',
TemplateElement: 'TemplateElement',
TemplateLiteral: 'TemplateLiteral',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TryStatement: 'TryStatement',
TypeAnnotatedIdentifier: 'TypeAnnotatedIdentifier',
TypeAnnotation: 'TypeAnnotation',
UnaryExpression: 'UnaryExpression',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
XJSIdentifier: 'XJSIdentifier',
XJSEmptyExpression: 'XJSEmptyExpression',
XJSExpressionContainer: 'XJSExpressionContainer',
XJSElement: 'XJSElement',
XJSClosingElement: 'XJSClosingElement',
XJSOpeningElement: 'XJSOpeningElement',
XJSAttribute: 'XJSAttribute',
XJSText: 'XJSText',
YieldExpression: 'YieldExpression'
};
PropertyKind = {
Data: 1,
Get: 2,
Set: 4
};
ClassPropertyType = {
'static': 'static',
prototype: 'prototype'
};
// Error messages should be identical to V8.
Messages = {
UnexpectedToken: 'Unexpected token %0',
UnexpectedNumber: 'Unexpected number',
UnexpectedString: 'Unexpected string',
UnexpectedIdentifier: 'Unexpected identifier',
UnexpectedReserved: 'Unexpected reserved word',
UnexpectedTemplate: 'Unexpected quasi %0',
UnexpectedEOS: 'Unexpected end of input',
NewlineAfterThrow: 'Illegal newline after throw',
InvalidRegExp: 'Invalid regular expression',
UnterminatedRegExp: 'Invalid regular expression: missing /',
InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
InvalidLHSInFormalsList: 'Invalid left-hand side in formals list',
InvalidLHSInForIn: 'Invalid left-hand side in for-in',
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
NoCatchOrFinally: 'Missing catch or finally after try',
UnknownLabel: 'Undefined label \'%0\'',
Redeclaration: '%0 \'%1\' has already been declared',
IllegalContinue: 'Illegal continue statement',
IllegalBreak: 'Illegal break statement',
IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition',
IllegalReturn: 'Illegal return statement',
IllegalYield: 'Illegal yield expression',
IllegalSpread: 'Illegal spread element',
StrictModeWith: 'Strict mode code may not include a with statement',
StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
StrictVarName: 'Variable name may not be eval or arguments in strict mode',
StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list',
DefaultRestParameter: 'Rest parameter can not have a default value',
ElementAfterSpreadElement: 'Spread must be the final element of an element list',
ObjectPatternAsRestParameter: 'Invalid rest parameter',
ObjectPatternAsSpread: 'Invalid spread argument',
StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
StrictDelete: 'Delete of an unqualified identifier in strict mode.',
StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
StrictReservedWord: 'Use of future reserved word in strict mode',
NewlineAfterModule: 'Illegal newline after module',
NoFromAfterImport: 'Missing from after import',
InvalidModuleSpecifier: 'Invalid module specifier',
NestedModule: 'Module declaration can not be nested',
NoYieldInGenerator: 'Missing yield in generator',
NoUnintializedConst: 'Const must be initialized',
ComprehensionRequiresBlock: 'Comprehension must have at least one block',
ComprehensionError: 'Comprehension Error',
EachNotAllowed: 'Each is not supported',
InvalidXJSTagName: 'XJS tag name can not be empty',
InvalidXJSAttributeValue: 'XJS value should be either an expression or a quoted XJS text',
ExpectedXJSClosingTag: 'Expected corresponding XJS closing tag for %0'
};
// See also tools/generate-unicode-regex.py.
Regex = {
NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')
};
// Ensure the condition is true, otherwise throw an error.
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.
function assert(condition, message) {
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
function isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0..9
}
function isHexDigit(ch) {
return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
}
function isOctalDigit(ch) {
return '01234567'.indexOf(ch) >= 0;
}
// 7.2 White Space
function isWhiteSpace(ch) {
return (ch === 32) || // space
(ch === 9) || // tab
(ch === 0xB) ||
(ch === 0xC) ||
(ch === 0xA0) ||
(ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0);
}
// 7.3 Line Terminators
function isLineTerminator(ch) {
return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029);
}
// 7.6 Identifier Names and Identifiers
function isIdentifierStart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
}
function isIdentifierPart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch >= 48 && ch <= 57) || // 0..9
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
}
// 7.6.1.2 Future Reserved Words
function isFutureReservedWord(id) {
switch (id) {
case 'class':
case 'enum':
case 'export':
case 'extends':
case 'import':
case 'super':
return true;
default:
return false;
}
}
function isStrictModeReservedWord(id) {
switch (id) {
case 'implements':
case 'interface':
case 'package':
case 'private':
case 'protected':
case 'public':
case 'static':
case 'yield':
case 'let':
return true;
default:
return false;
}
}
function isRestrictedWord(id) {
return id === 'eval' || id === 'arguments';
}
// 7.6.1.1 Keywords
function isKeyword(id) {
if (strict && isStrictModeReservedWord(id)) {
return true;
}
// 'const' is specialized as Keyword in V8.
// 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next.
// Some others are from future reserved words.
switch (id.length) {
case 2:
return (id === 'if') || (id === 'in') || (id === 'do');
case 3:
return (id === 'var') || (id === 'for') || (id === 'new') ||
(id === 'try') || (id === 'let');
case 4:
return (id === 'this') || (id === 'else') || (id === 'case') ||
(id === 'void') || (id === 'with') || (id === 'enum');
case 5:
return (id === 'while') || (id === 'break') || (id === 'catch') ||
(id === 'throw') || (id === 'const') || (id === 'yield') ||
(id === 'class') || (id === 'super');
case 6:
return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
(id === 'switch') || (id === 'export') || (id === 'import');
case 7:
return (id === 'default') || (id === 'finally') || (id === 'extends');
case 8:
return (id === 'function') || (id === 'continue') || (id === 'debugger');
case 10:
return (id === 'instanceof');
default:
return false;
}
}
// 7.4 Comments
function skipComment() {
var ch, blockComment, lineComment;
blockComment = false;
lineComment = false;
while (index < length) {
ch = source.charCodeAt(index);
if (lineComment) {
++index;
if (isLineTerminator(ch)) {
lineComment = false;
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
}
} else if (blockComment) {
if (isLineTerminator(ch)) {
if (ch === 13 && source.charCodeAt(index + 1) === 10) {
++index;
}
++lineNumber;
++index;
lineStart = index;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
ch = source.charCodeAt(index++);
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// Block comment ends with '*/' (char #42, char #47).
if (ch === 42) {
ch = source.charCodeAt(index);
if (ch === 47) {
++index;
blockComment = false;
}
}
}
} else if (ch === 47) {
ch = source.charCodeAt(index + 1);
// Line comment starts with '//' (char #47, char #47).
if (ch === 47) {
index += 2;
lineComment = true;
} else if (ch === 42) {
// Block comment starts with '/*' (char #47, char #42).
index += 2;
blockComment = true;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
break;
}
} else if (isWhiteSpace(ch)) {
++index;
} else if (isLineTerminator(ch)) {
++index;
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
} else {
break;
}
}
}
function scanHexEscape(prefix) {
var i, len, ch, code = 0;
len = (prefix === 'u') ? 4 : 2;
for (i = 0; i < len; ++i) {
if (index < length && isHexDigit(source[index])) {
ch = source[index++];
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
} else {
return '';
}
}
return String.fromCharCode(code);
}
function scanUnicodeCodePointEscape() {
var ch, code, cu1, cu2;
ch = source[index];
code = 0;
// At least, one hex digit is required.
if (ch === '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
while (index < length) {
ch = source[index++];
if (!isHexDigit(ch)) {
break;
}
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
}
if (code > 0x10FFFF || ch !== '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// UTF-16 Encoding
if (code <= 0xFFFF) {
return String.fromCharCode(code);
}
cu1 = ((code - 0x10000) >> 10) + 0xD800;
cu2 = ((code - 0x10000) & 1023) + 0xDC00;
return String.fromCharCode(cu1, cu2);
}
function getEscapedIdentifier() {
var ch, id;
ch = source.charCodeAt(index++);
id = String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id = ch;
}
while (index < length) {
ch = source.charCodeAt(index);
if (!isIdentifierPart(ch)) {
break;
}
++index;
id += String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
id = id.substr(0, id.length - 1);
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id += ch;
}
}
return id;
}
function getIdentifier() {
var start, ch;
start = index++;
while (index < length) {
ch = source.charCodeAt(index);
if (ch === 92) {
// Blackslash (char #92) marks Unicode escape sequence.
index = start;
return getEscapedIdentifier();
}
if (isIdentifierPart(ch)) {
++index;
} else {
break;
}
}
return source.slice(start, index);
}
function scanIdentifier() {
var start, id, type;
start = index;
// Backslash (char #92) starts an escaped character.
id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier();
// There is no keyword or literal with only one character.
// Thus, it must be an identifier.
if (id.length === 1) {
type = Token.Identifier;
} else if (isKeyword(id)) {
type = Token.Keyword;
} else if (id === 'null') {
type = Token.NullLiteral;
} else if (id === 'true' || id === 'false') {
type = Token.BooleanLiteral;
} else {
type = Token.Identifier;
}
return {
type: type,
value: id,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.7 Punctuators
function scanPunctuator() {
var start = index,
code = source.charCodeAt(index),
code2,
ch1 = source[index],
ch2,
ch3,
ch4;
switch (code) {
// Check for most common single-character punctuators.
case 40: // ( open bracket
case 41: // ) close bracket
case 59: // ; semicolon
case 44: // , comma
case 123: // { open curly brace
case 125: // } close curly brace
case 91: // [
case 93: // ]
case 58: // :
case 63: // ?
case 126: // ~
++index;
if (extra.tokenize) {
if (code === 40) {
extra.openParenToken = extra.tokens.length;
} else if (code === 123) {
extra.openCurlyToken = extra.tokens.length;
}
}
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
code2 = source.charCodeAt(index + 1);
// '=' (char #61) marks an assignment or comparison operator.
if (code2 === 61) {
switch (code) {
case 37: // %
case 38: // &
case 42: // *:
case 43: // +
case 45: // -
case 47: // /
case 60: // <
case 62: // >
case 94: // ^
case 124: // |
index += 2;
return {
type: Token.Punctuator,
value: String.fromCharCode(code) + String.fromCharCode(code2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
case 33: // !
case 61: // =
index += 2;
// !== and ===
if (source.charCodeAt(index) === 61) {
++index;
}
return {
type: Token.Punctuator,
value: source.slice(start, index),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
break;
}
}
break;
}
// Peek more characters.
ch2 = source[index + 1];
ch3 = source[index + 2];
ch4 = source[index + 3];
// 4-character punctuator: >>>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
if (ch4 === '=') {
index += 4;
return {
type: Token.Punctuator,
value: '>>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
}
// 3-character punctuators: === !== >>> <<= >>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
index += 3;
return {
type: Token.Punctuator,
value: '>>>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '<<=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.' && ch2 === '.' && ch3 === '.') {
index += 3;
return {
type: Token.Punctuator,
value: '...',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// Other 2-character punctuators: ++ -- << >> && ||
if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) {
index += 2;
return {
type: Token.Punctuator,
value: ch1 + ch2,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '=' && ch2 === '>') {
index += 2;
return {
type: Token.Punctuator,
value: '=>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.') {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// 7.8.3 Numeric Literals
function scanHexLiteral(start) {
var number = '';
while (index < length) {
if (!isHexDigit(source[index])) {
break;
}
number += source[index++];
}
if (number.length === 0) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt('0x' + number, 16),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanOctalLiteral(prefix, start) {
var number, octal;
if (isOctalDigit(prefix)) {
octal = true;
number = '0' + source[index++];
} else {
octal = false;
++index;
number = '';
}
while (index < length) {
if (!isOctalDigit(source[index])) {
break;
}
number += source[index++];
}
if (!octal && number.length === 0) {
// only 0o or 0O
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 8),
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanNumericLiteral() {
var number, start, ch, octal;
ch = source[index];
assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
'Numeric literal must start with a decimal digit or a decimal point');
start = index;
number = '';
if (ch !== '.') {
number = source[index++];
ch = source[index];
// Hex number starts with '0x'.
// Octal number starts with '0'.
// Octal number in ES6 starts with '0o'.
// Binary number in ES6 starts with '0b'.
if (number === '0') {
if (ch === 'x' || ch === 'X') {
++index;
return scanHexLiteral(start);
}
if (ch === 'b' || ch === 'B') {
++index;
number = '';
while (index < length) {
ch = source[index];
if (ch !== '0' && ch !== '1') {
break;
}
number += source[index++];
}
if (number.length === 0) {
// only 0b or 0B
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (index < length) {
ch = source.charCodeAt(index);
if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) {
return scanOctalLiteral(ch, start);
}
// decimal number starts with '0' such as '09' is illegal.
if (ch && isDecimalDigit(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === '.') {
number += source[index++];
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === 'e' || ch === 'E') {
number += source[index++];
ch = source[index];
if (ch === '+' || ch === '-') {
number += source[index++];
}
if (isDecimalDigit(source.charCodeAt(index))) {
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
} else {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseFloat(number),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.8.4 String Literals
function scanStringLiteral() {
var str = '', quote, start, ch, code, unescaped, restore, octal = false;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === quote) {
quote = '';
break;
} else if (ch === '\\') {
ch = source[index++];
if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
str += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
str += unescaped;
} else {
index = restore;
str += ch;
}
}
break;
case 'b':
str += '\b';
break;
case 'f':
str += '\f';
break;
case 'v':
str += '\x0B';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
str += String.fromCharCode(code);
} else {
str += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
break;
} else {
str += ch;
}
}
if (quote !== '') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.StringLiteral,
value: str,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplate() {
var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal;
terminated = false;
tail = false;
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === '`') {
tail = true;
terminated = true;
break;
} else if (ch === '$') {
if (source[index] === '{') {
++index;
terminated = true;
break;
}
cooked += ch;
} else if (ch === '\\') {
ch = source[index++];
if (!isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
cooked += '\n';
break;
case 'r':
cooked += '\r';
break;
case 't':
cooked += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
cooked += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
cooked += unescaped;
} else {
index = restore;
cooked += ch;
}
}
break;
case 'b':
cooked += '\b';
break;
case 'f':
cooked += '\f';
break;
case 'v':
cooked += '\v';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
cooked += String.fromCharCode(code);
} else {
cooked += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
cooked += '\n';
} else {
cooked += ch;
}
}
if (!terminated) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.Template,
value: {
cooked: cooked,
raw: source.slice(start + 1, index - ((tail) ? 1 : 2))
},
tail: tail,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplateElement(option) {
var startsWith, template;
lookahead = null;
skipComment();
startsWith = (option.head) ? '`' : '}';
if (source[index] !== startsWith) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
template = scanTemplate();
peek();
return template;
}
function scanRegExp() {
var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false;
lookahead = null;
skipComment();
start = index;
ch = source[index];
assert(ch === '/', 'Regular expression literal must start with a slash');
str = source[index++];
while (index < length) {
ch = source[index++];
str += ch;
if (classMarker) {
if (ch === ']') {
classMarker = false;
}
} else {
if (ch === '\\') {
ch = source[index++];
// ECMA-262 7.8.5
if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
}
str += ch;
} else if (ch === '/') {
terminated = true;
break;
} else if (ch === '[') {
classMarker = true;
} else if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
}
}
}
if (!terminated) {
throwError({}, Messages.UnterminatedRegExp);
}
// Exclude leading and trailing slash.
pattern = str.substr(1, str.length - 2);
flags = '';
while (index < length) {
ch = source[index];
if (!isIdentifierPart(ch.charCodeAt(0))) {
break;
}
++index;
if (ch === '\\' && index < length) {
ch = source[index];
if (ch === 'u') {
++index;
restore = index;
ch = scanHexEscape('u');
if (ch) {
flags += ch;
for (str += '\\u'; restore < index; ++restore) {
str += source[restore];
}
} else {
index = restore;
flags += 'u';
str += '\\u';
}
} else {
str += '\\';
}
} else {
flags += ch;
str += ch;
}
}
try {
value = new RegExp(pattern, flags);
} catch (e) {
throwError({}, Messages.InvalidRegExp);
}
peek();
if (extra.tokenize) {
return {
type: Token.RegularExpression,
value: value,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
return {
literal: str,
value: value,
range: [start, index]
};
}
function isIdentifierName(token) {
return token.type === Token.Identifier ||
token.type === Token.Keyword ||
token.type === Token.BooleanLiteral ||
token.type === Token.NullLiteral;
}
function advanceSlash() {
var prevToken,
checkToken;
// Using the following algorithm:
// https://github.com/mozilla/sweet.js/wiki/design
prevToken = extra.tokens[extra.tokens.length - 1];
if (!prevToken) {
// Nothing before that: it cannot be a division.
return scanRegExp();
}
if (prevToken.type === 'Punctuator') {
if (prevToken.value === ')') {
checkToken = extra.tokens[extra.openParenToken - 1];
if (checkToken &&
checkToken.type === 'Keyword' &&
(checkToken.value === 'if' ||
checkToken.value === 'while' ||
checkToken.value === 'for' ||
checkToken.value === 'with')) {
return scanRegExp();
}
return scanPunctuator();
}
if (prevToken.value === '}') {
// Dividing a function by anything makes little sense,
// but we have to check for that.
if (extra.tokens[extra.openCurlyToken - 3] &&
extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
// Anonymous function.
checkToken = extra.tokens[extra.openCurlyToken - 4];
if (!checkToken) {
return scanPunctuator();
}
} else if (extra.tokens[extra.openCurlyToken - 4] &&
extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
// Named function.
checkToken = extra.tokens[extra.openCurlyToken - 5];
if (!checkToken) {
return scanRegExp();
}
} else {
return scanPunctuator();
}
// checkToken determines whether the function is
// a declaration or an expression.
if (FnExprTokens.indexOf(checkToken.value) >= 0) {
// It is an expression.
return scanPunctuator();
}
// It is a declaration.
return scanRegExp();
}
return scanRegExp();
}
if (prevToken.type === 'Keyword') {
return scanRegExp();
}
return scanPunctuator();
}
function advance() {
var ch;
if (!state.inXJSChild) {
skipComment();
}
if (index >= length) {
return {
type: Token.EOF,
lineNumber: lineNumber,
lineStart: lineStart,
range: [index, index]
};
}
if (state.inXJSChild) {
return advanceXJSChild();
}
ch = source.charCodeAt(index);
// Very common: ( and ) and ;
if (ch === 40 || ch === 41 || ch === 58) {
return scanPunctuator();
}
// String literal starts with single quote (#39) or double quote (#34).
if (ch === 39 || ch === 34) {
if (state.inXJSTag) {
return scanXJSStringLiteral();
}
return scanStringLiteral();
}
if (state.inXJSTag && isXJSIdentifierStart(ch)) {
return scanXJSIdentifier();
}
if (ch === 96) {
return scanTemplate();
}
if (isIdentifierStart(ch)) {
return scanIdentifier();
}
// Dot (.) char #46 can also start a floating-point number, hence the need
// to check the next character.
if (ch === 46) {
if (isDecimalDigit(source.charCodeAt(index + 1))) {
return scanNumericLiteral();
}
return scanPunctuator();
}
if (isDecimalDigit(ch)) {
return scanNumericLiteral();
}
// Slash (/) char #47 can also start a regex.
if (extra.tokenize && ch === 47) {
return advanceSlash();
}
return scanPunctuator();
}
function lex() {
var token;
token = lookahead;
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
lookahead = advance();
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
return token;
}
function peek() {
var pos, line, start;
pos = index;
line = lineNumber;
start = lineStart;
lookahead = advance();
index = pos;
lineNumber = line;
lineStart = start;
}
function lookahead2() {
var adv, pos, line, start, result;
// If we are collecting the tokens, don't grab the next one yet.
adv = (typeof extra.advance === 'function') ? extra.advance : advance;
pos = index;
line = lineNumber;
start = lineStart;
// Scan for the next immediate token.
if (lookahead === null) {
lookahead = adv();
}
index = lookahead.range[1];
lineNumber = lookahead.lineNumber;
lineStart = lookahead.lineStart;
// Grab the token right after.
result = adv();
index = pos;
lineNumber = line;
lineStart = start;
return result;
}
SyntaxTreeDelegate = {
name: 'SyntaxTree',
postProcess: function (node) {
return node;
},
createArrayExpression: function (elements) {
return {
type: Syntax.ArrayExpression,
elements: elements
};
},
createAssignmentExpression: function (operator, left, right) {
return {
type: Syntax.AssignmentExpression,
operator: operator,
left: left,
right: right
};
},
createBinaryExpression: function (operator, left, right) {
var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :
Syntax.BinaryExpression;
return {
type: type,
operator: operator,
left: left,
right: right
};
},
createBlockStatement: function (body) {
return {
type: Syntax.BlockStatement,
body: body
};
},
createBreakStatement: function (label) {
return {
type: Syntax.BreakStatement,
label: label
};
},
createCallExpression: function (callee, args) {
return {
type: Syntax.CallExpression,
callee: callee,
'arguments': args
};
},
createCatchClause: function (param, body) {
return {
type: Syntax.CatchClause,
param: param,
body: body
};
},
createConditionalExpression: function (test, consequent, alternate) {
return {
type: Syntax.ConditionalExpression,
test: test,
consequent: consequent,
alternate: alternate
};
},
createContinueStatement: function (label) {
return {
type: Syntax.ContinueStatement,
label: label
};
},
createDebuggerStatement: function () {
return {
type: Syntax.DebuggerStatement
};
},
createDoWhileStatement: function (body, test) {
return {
type: Syntax.DoWhileStatement,
body: body,
test: test
};
},
createEmptyStatement: function () {
return {
type: Syntax.EmptyStatement
};
},
createExpressionStatement: function (expression) {
return {
type: Syntax.ExpressionStatement,
expression: expression
};
},
createForStatement: function (init, test, update, body) {
return {
type: Syntax.ForStatement,
init: init,
test: test,
update: update,
body: body
};
},
createForInStatement: function (left, right, body) {
return {
type: Syntax.ForInStatement,
left: left,
right: right,
body: body,
each: false
};
},
createForOfStatement: function (left, right, body) {
return {
type: Syntax.ForOfStatement,
left: left,
right: right,
body: body
};
},
createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression,
returnType) {
return {
type: Syntax.FunctionDeclaration,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType
};
},
createFunctionExpression: function (id, params, defaults, body, rest, generator, expression,
returnType) {
return {
type: Syntax.FunctionExpression,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType
};
},
createIdentifier: function (name) {
return {
type: Syntax.Identifier,
name: name,
// Only here to initialize the shape of the object to ensure
// that the 'typeAnnotation' key is ordered before others that
// are added later (like 'loc' and 'range'). This just helps
// keep the shape of Identifier nodes consistent with everything
// else.
typeAnnotation: undefined
};
},
createTypeAnnotation: function (typeIdentifier, paramTypes, returnType, nullable) {
return {
type: Syntax.TypeAnnotation,
id: typeIdentifier,
paramTypes: paramTypes,
returnType: returnType,
nullable: nullable
};
},
createTypeAnnotatedIdentifier: function (identifier, annotation) {
return {
type: Syntax.TypeAnnotatedIdentifier,
id: identifier,
annotation: annotation
};
},
createXJSAttribute: function (name, value) {
return {
type: Syntax.XJSAttribute,
name: name,
value: value
};
},
createXJSIdentifier: function (name, namespace) {
return {
type: Syntax.XJSIdentifier,
name: name,
namespace: namespace
};
},
createXJSElement: function (openingElement, closingElement, children) {
return {
type: Syntax.XJSElement,
openingElement: openingElement,
closingElement: closingElement,
children: children
};
},
createXJSEmptyExpression: function () {
return {
type: Syntax.XJSEmptyExpression
};
},
createXJSExpressionContainer: function (expression) {
return {
type: Syntax.XJSExpressionContainer,
expression: expression
};
},
createXJSOpeningElement: function (name, attributes, selfClosing) {
return {
type: Syntax.XJSOpeningElement,
name: name,
selfClosing: selfClosing,
attributes: attributes
};
},
createXJSClosingElement: function (name) {
return {
type: Syntax.XJSClosingElement,
name: name
};
},
createIfStatement: function (test, consequent, alternate) {
return {
type: Syntax.IfStatement,
test: test,
consequent: consequent,
alternate: alternate
};
},
createLabeledStatement: function (label, body) {
return {
type: Syntax.LabeledStatement,
label: label,
body: body
};
},
createLiteral: function (token) {
return {
type: Syntax.Literal,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
},
createMemberExpression: function (accessor, object, property) {
return {
type: Syntax.MemberExpression,
computed: accessor === '[',
object: object,
property: property
};
},
createNewExpression: function (callee, args) {
return {
type: Syntax.NewExpression,
callee: callee,
'arguments': args
};
},
createObjectExpression: function (properties) {
return {
type: Syntax.ObjectExpression,
properties: properties
};
},
createPostfixExpression: function (operator, argument) {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: false
};
},
createProgram: function (body) {
return {
type: Syntax.Program,
body: body
};
},
createProperty: function (kind, key, value, method, shorthand) {
return {
type: Syntax.Property,
key: key,
value: value,
kind: kind,
method: method,
shorthand: shorthand
};
},
createReturnStatement: function (argument) {
return {
type: Syntax.ReturnStatement,
argument: argument
};
},
createSequenceExpression: function (expressions) {
return {
type: Syntax.SequenceExpression,
expressions: expressions
};
},
createSwitchCase: function (test, consequent) {
return {
type: Syntax.SwitchCase,
test: test,
consequent: consequent
};
},
createSwitchStatement: function (discriminant, cases) {
return {
type: Syntax.SwitchStatement,
discriminant: discriminant,
cases: cases
};
},
createThisExpression: function () {
return {
type: Syntax.ThisExpression
};
},
createThrowStatement: function (argument) {
return {
type: Syntax.ThrowStatement,
argument: argument
};
},
createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
return {
type: Syntax.TryStatement,
block: block,
guardedHandlers: guardedHandlers,
handlers: handlers,
finalizer: finalizer
};
},
createUnaryExpression: function (operator, argument) {
if (operator === '++' || operator === '--') {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: true
};
}
return {
type: Syntax.UnaryExpression,
operator: operator,
argument: argument
};
},
createVariableDeclaration: function (declarations, kind) {
return {
type: Syntax.VariableDeclaration,
declarations: declarations,
kind: kind
};
},
createVariableDeclarator: function (id, init) {
return {
type: Syntax.VariableDeclarator,
id: id,
init: init
};
},
createWhileStatement: function (test, body) {
return {
type: Syntax.WhileStatement,
test: test,
body: body
};
},
createWithStatement: function (object, body) {
return {
type: Syntax.WithStatement,
object: object,
body: body
};
},
createTemplateElement: function (value, tail) {
return {
type: Syntax.TemplateElement,
value: value,
tail: tail
};
},
createTemplateLiteral: function (quasis, expressions) {
return {
type: Syntax.TemplateLiteral,
quasis: quasis,
expressions: expressions
};
},
createSpreadElement: function (argument) {
return {
type: Syntax.SpreadElement,
argument: argument
};
},
createTaggedTemplateExpression: function (tag, quasi) {
return {
type: Syntax.TaggedTemplateExpression,
tag: tag,
quasi: quasi
};
},
createArrowFunctionExpression: function (params, defaults, body, rest, expression) {
return {
type: Syntax.ArrowFunctionExpression,
id: null,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: false,
expression: expression
};
},
createMethodDefinition: function (propertyType, kind, key, value) {
return {
type: Syntax.MethodDefinition,
key: key,
value: value,
kind: kind,
'static': propertyType === ClassPropertyType["static"]
};
},
createClassBody: function (body) {
return {
type: Syntax.ClassBody,
body: body
};
},
createClassExpression: function (id, superClass, body) {
return {
type: Syntax.ClassExpression,
id: id,
superClass: superClass,
body: body
};
},
createClassDeclaration: function (id, superClass, body) {
return {
type: Syntax.ClassDeclaration,
id: id,
superClass: superClass,
body: body
};
},
createExportSpecifier: function (id, name) {
return {
type: Syntax.ExportSpecifier,
id: id,
name: name
};
},
createExportBatchSpecifier: function () {
return {
type: Syntax.ExportBatchSpecifier
};
},
createExportDeclaration: function (declaration, specifiers, source) {
return {
type: Syntax.ExportDeclaration,
declaration: declaration,
specifiers: specifiers,
source: source
};
},
createImportSpecifier: function (id, name) {
return {
type: Syntax.ImportSpecifier,
id: id,
name: name
};
},
createImportDeclaration: function (specifiers, kind, source) {
return {
type: Syntax.ImportDeclaration,
specifiers: specifiers,
kind: kind,
source: source
};
},
createYieldExpression: function (argument, delegate) {
return {
type: Syntax.YieldExpression,
argument: argument,
delegate: delegate
};
},
createModuleDeclaration: function (id, source, body) {
return {
type: Syntax.ModuleDeclaration,
id: id,
source: source,
body: body
};
}
};
// Return true if there is a line terminator before the next token.
function peekLineTerminator() {
var pos, line, start, found;
pos = index;
line = lineNumber;
start = lineStart;
skipComment();
found = lineNumber !== line;
index = pos;
lineNumber = line;
lineStart = start;
return found;
}
// Throw an exception
function throwError(token, messageFormat) {
var error,
args = Array.prototype.slice.call(arguments, 2),
msg = messageFormat.replace(
/%(\d)/g,
function (whole, index) {
assert(index < args.length, 'Message reference must be in range');
return args[index];
}
);
if (typeof token.lineNumber === 'number') {
error = new Error('Line ' + token.lineNumber + ': ' + msg);
error.index = token.range[0];
error.lineNumber = token.lineNumber;
error.column = token.range[0] - lineStart + 1;
} else {
error = new Error('Line ' + lineNumber + ': ' + msg);
error.index = index;
error.lineNumber = lineNumber;
error.column = index - lineStart + 1;
}
error.description = msg;
throw error;
}
function throwErrorTolerant() {
try {
throwError.apply(null, arguments);
} catch (e) {
if (extra.errors) {
extra.errors.push(e);
} else {
throw e;
}
}
}
// Throw an exception because of the token.
function throwUnexpected(token) {
if (token.type === Token.EOF) {
throwError(token, Messages.UnexpectedEOS);
}
if (token.type === Token.NumericLiteral) {
throwError(token, Messages.UnexpectedNumber);
}
if (token.type === Token.StringLiteral || token.type === Token.XJSText) {
throwError(token, Messages.UnexpectedString);
}
if (token.type === Token.Identifier) {
throwError(token, Messages.UnexpectedIdentifier);
}
if (token.type === Token.Keyword) {
if (isFutureReservedWord(token.value)) {
throwError(token, Messages.UnexpectedReserved);
} else if (strict && isStrictModeReservedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictReservedWord);
return;
}
throwError(token, Messages.UnexpectedToken, token.value);
}
if (token.type === Token.Template) {
throwError(token, Messages.UnexpectedTemplate, token.value.raw);
}
// BooleanLiteral, NullLiteral, or Punctuator.
throwError(token, Messages.UnexpectedToken, token.value);
}
// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.
function expect(value) {
var token = lex();
if (token.type !== Token.Punctuator || token.value !== value) {
throwUnexpected(token);
}
}
// Expect the next token to match the specified keyword.
// If not, an exception will be thrown.
function expectKeyword(keyword) {
var token = lex();
if (token.type !== Token.Keyword || token.value !== keyword) {
throwUnexpected(token);
}
}
// Return true if the next token matches the specified punctuator.
function match(value) {
return lookahead.type === Token.Punctuator && lookahead.value === value;
}
// Return true if the next token matches the specified keyword
function matchKeyword(keyword) {
return lookahead.type === Token.Keyword && lookahead.value === keyword;
}
// Return true if the next token matches the specified contextual keyword
function matchContextualKeyword(keyword) {
return lookahead.type === Token.Identifier && lookahead.value === keyword;
}
// Return true if the next token is an assignment operator
function matchAssign() {
var op;
if (lookahead.type !== Token.Punctuator) {
return false;
}
op = lookahead.value;
return op === '=' ||
op === '*=' ||
op === '/=' ||
op === '%=' ||
op === '+=' ||
op === '-=' ||
op === '<<=' ||
op === '>>=' ||
op === '>>>=' ||
op === '&=' ||
op === '^=' ||
op === '|=';
}
function consumeSemicolon() {
var line;
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
return;
}
line = lineNumber;
skipComment();
if (lineNumber !== line) {
return;
}
if (match(';')) {
lex();
return;
}
if (lookahead.type !== Token.EOF && !match('}')) {
throwUnexpected(lookahead);
}
}
// Return true if provided expression is LeftHandSideExpression
function isLeftHandSide(expr) {
return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
}
function isAssignableLeftHandSide(expr) {
return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern;
}
// 11.1.4 Array Initialiser
function parseArrayInitialiser() {
var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, body;
expect('[');
while (!match(']')) {
if (lookahead.value === 'for' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
matchKeyword('for');
tmp = parseForStatement({ignoreBody: true});
tmp.of = tmp.type === Syntax.ForOfStatement;
tmp.type = Syntax.ComprehensionBlock;
if (tmp.left.kind) { // can't be let or const
throwError({}, Messages.ComprehensionError);
}
blocks.push(tmp);
} else if (lookahead.value === 'if' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
expectKeyword('if');
expect('(');
filter = parseExpression();
expect(')');
} else if (lookahead.value === ',' &&
lookahead.type === Token.Punctuator) {
possiblecomprehension = false; // no longer allowed.
lex();
elements.push(null);
} else {
tmp = parseSpreadOrAssignmentExpression();
elements.push(tmp);
if (tmp && tmp.type === Syntax.SpreadElement) {
if (!match(']')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
} else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) {
expect(','); // this lexes.
possiblecomprehension = false;
}
}
}
expect(']');
if (filter && !blocks.length) {
throwError({}, Messages.ComprehensionRequiresBlock);
}
if (blocks.length) {
if (elements.length !== 1) {
throwError({}, Messages.ComprehensionError);
}
return {
type: Syntax.ComprehensionExpression,
filter: filter,
blocks: blocks,
body: elements[0]
};
}
return delegate.createArrayExpression(elements);
}
// 11.1.5 Object Initialiser
function parsePropertyFunction(options) {
var previousStrict, previousYieldAllowed, params, defaults, body;
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = options.generator;
params = options.params || [];
defaults = options.defaults || [];
body = parseConciseBody();
if (options.name && strict && isRestrictedWord(params[0].name)) {
throwErrorTolerant(options.name, Messages.StrictParamName);
}
if (state.yieldAllowed && !state.yieldFound) {
throwErrorTolerant({}, Messages.NoYieldInGenerator);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
return delegate.createFunctionExpression(null, params, defaults, body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement,
options.returnTypeAnnotation);
}
function parsePropertyMethodFunction(options) {
var previousStrict, tmp, method;
previousStrict = strict;
strict = true;
tmp = parseParams();
if (tmp.stricted) {
throwErrorTolerant(tmp.stricted, tmp.message);
}
method = parsePropertyFunction({
params: tmp.params,
defaults: tmp.defaults,
rest: tmp.rest,
generator: options.generator,
returnTypeAnnotation: tmp.returnTypeAnnotation
});
strict = previousStrict;
return method;
}
function parseObjectPropertyKey() {
var token = lex();
// Note: This function is called only from parseObjectProperty(), where
// EOF and Punctuator tokens are already filtered out.
if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
if (strict && token.octal) {
throwErrorTolerant(token, Messages.StrictOctalLiteral);
}
return delegate.createLiteral(token);
}
return delegate.createIdentifier(token.value);
}
function parseObjectProperty() {
var token, key, id, value, param;
token = lookahead;
if (token.type === Token.Identifier) {
id = parseObjectPropertyKey();
// Property Assignment: Getter and Setter.
if (token.value === 'get' && !(match(':') || match('('))) {
key = parseObjectPropertyKey();
expect('(');
expect(')');
return delegate.createProperty('get', key, parsePropertyFunction({ generator: false }), false, false);
}
if (token.value === 'set' && !(match(':') || match('('))) {
key = parseObjectPropertyKey();
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
return delegate.createProperty('set', key, parsePropertyFunction({ params: param, generator: false, name: token }), false, false);
}
if (match(':')) {
lex();
return delegate.createProperty('init', id, parseAssignmentExpression(), false, false);
}
if (match('(')) {
return delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: false }), true, false);
}
return delegate.createProperty('init', id, id, false, true);
}
if (token.type === Token.EOF || token.type === Token.Punctuator) {
if (!match('*')) {
throwUnexpected(token);
}
lex();
id = parseObjectPropertyKey();
if (!match('(')) {
throwUnexpected(lex());
}
return delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: true }), true, false);
}
key = parseObjectPropertyKey();
if (match(':')) {
lex();
return delegate.createProperty('init', key, parseAssignmentExpression(), false, false);
}
if (match('(')) {
return delegate.createProperty('init', key, parsePropertyMethodFunction({ generator: false }), true, false);
}
throwUnexpected(lex());
}
function parseObjectInitialiser() {
var properties = [], property, name, key, kind, map = {}, toString = String;
expect('{');
while (!match('}')) {
property = parseObjectProperty();
if (property.key.type === Syntax.Identifier) {
name = property.key.name;
} else {
name = toString(property.key.value);
}
kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
key = '$' + name;
if (Object.prototype.hasOwnProperty.call(map, key)) {
if (map[key] === PropertyKind.Data) {
if (strict && kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.StrictDuplicateProperty);
} else if (kind !== PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
}
} else {
if (kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
} else if (map[key] & kind) {
throwErrorTolerant({}, Messages.AccessorGetSet);
}
}
map[key] |= kind;
} else {
map[key] = kind;
}
properties.push(property);
if (!match('}')) {
expect(',');
}
}
expect('}');
return delegate.createObjectExpression(properties);
}
function parseTemplateElement(option) {
var token = scanTemplateElement(option);
if (strict && token.octal) {
throwError(token, Messages.StrictOctalLiteral);
}
return delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
}
function parseTemplateLiteral() {
var quasi, quasis, expressions;
quasi = parseTemplateElement({ head: true });
quasis = [ quasi ];
expressions = [];
while (!quasi.tail) {
expressions.push(parseExpression());
quasi = parseTemplateElement({ head: false });
quasis.push(quasi);
}
return delegate.createTemplateLiteral(quasis, expressions);
}
// 11.1.6 The Grouping Operator
function parseGroupExpression() {
var expr;
expect('(');
++state.parenthesizedCount;
expr = parseExpression();
expect(')');
return expr;
}
// 11.1 Primary Expressions
function parsePrimaryExpression() {
var type, token;
token = lookahead;
type = lookahead.type;
if (type === Token.Identifier) {
lex();
return delegate.createIdentifier(token.value);
}
if (type === Token.StringLiteral || type === Token.NumericLiteral) {
if (strict && lookahead.octal) {
throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
}
return delegate.createLiteral(lex());
}
if (type === Token.Keyword) {
if (matchKeyword('this')) {
lex();
return delegate.createThisExpression();
}
if (matchKeyword('function')) {
return parseFunctionExpression();
}
if (matchKeyword('class')) {
return parseClassExpression();
}
if (matchKeyword('super')) {
lex();
return delegate.createIdentifier('super');
}
}
if (type === Token.BooleanLiteral) {
token = lex();
token.value = (token.value === 'true');
return delegate.createLiteral(token);
}
if (type === Token.NullLiteral) {
token = lex();
token.value = null;
return delegate.createLiteral(token);
}
if (match('[')) {
return parseArrayInitialiser();
}
if (match('{')) {
return parseObjectInitialiser();
}
if (match('(')) {
return parseGroupExpression();
}
if (match('/') || match('/=')) {
return delegate.createLiteral(scanRegExp());
}
if (type === Token.Template) {
return parseTemplateLiteral();
}
if (match('<')) {
return parseXJSElement();
}
return throwUnexpected(lex());
}
// 11.2 Left-Hand-Side Expressions
function parseArguments() {
var args = [], arg;
expect('(');
if (!match(')')) {
while (index < length) {
arg = parseSpreadOrAssignmentExpression();
args.push(arg);
if (match(')')) {
break;
} else if (arg.type === Syntax.SpreadElement) {
throwError({}, Messages.ElementAfterSpreadElement);
}
expect(',');
}
}
expect(')');
return args;
}
function parseSpreadOrAssignmentExpression() {
if (match('...')) {
lex();
return delegate.createSpreadElement(parseAssignmentExpression());
}
return parseAssignmentExpression();
}
function parseNonComputedProperty() {
var token = lex();
if (!isIdentifierName(token)) {
throwUnexpected(token);
}
return delegate.createIdentifier(token.value);
}
function parseNonComputedMember() {
expect('.');
return parseNonComputedProperty();
}
function parseComputedMember() {
var expr;
expect('[');
expr = parseExpression();
expect(']');
return expr;
}
function parseNewExpression() {
var callee, args;
expectKeyword('new');
callee = parseLeftHandSideExpression();
args = match('(') ? parseArguments() : [];
return delegate.createNewExpression(callee, args);
}
function parseLeftHandSideExpressionAllowCall() {
var expr, args, property;
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) {
if (match('(')) {
args = parseArguments();
expr = delegate.createCallExpression(expr, args);
} else if (match('[')) {
expr = delegate.createMemberExpression('[', expr, parseComputedMember());
} else if (match('.')) {
expr = delegate.createMemberExpression('.', expr, parseNonComputedMember());
} else {
expr = delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral());
}
}
return expr;
}
function parseLeftHandSideExpression() {
var expr, property;
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || lookahead.type === Token.Template) {
if (match('[')) {
expr = delegate.createMemberExpression('[', expr, parseComputedMember());
} else if (match('.')) {
expr = delegate.createMemberExpression('.', expr, parseNonComputedMember());
} else {
expr = delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral());
}
}
return expr;
}
// 11.3 Postfix Expressions
function parsePostfixExpression() {
var expr = parseLeftHandSideExpressionAllowCall(),
token = lookahead;
if (lookahead.type !== Token.Punctuator) {
return expr;
}
if ((match('++') || match('--')) && !peekLineTerminator()) {
// 11.3.1, 11.3.2
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPostfix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
token = lex();
expr = delegate.createPostfixExpression(token.value, expr);
}
return expr;
}
// 11.4 Unary Operators
function parseUnaryExpression() {
var token, expr;
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
return parsePostfixExpression();
}
if (match('++') || match('--')) {
token = lex();
expr = parseUnaryExpression();
// 11.4.4, 11.4.5
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPrefix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
return delegate.createUnaryExpression(token.value, expr);
}
if (match('+') || match('-') || match('~') || match('!')) {
token = lex();
expr = parseUnaryExpression();
return delegate.createUnaryExpression(token.value, expr);
}
if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
token = lex();
expr = parseUnaryExpression();
expr = delegate.createUnaryExpression(token.value, expr);
if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
throwErrorTolerant({}, Messages.StrictDelete);
}
return expr;
}
return parsePostfixExpression();
}
function binaryPrecedence(token, allowIn) {
var prec = 0;
if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
return 0;
}
switch (token.value) {
case '||':
prec = 1;
break;
case '&&':
prec = 2;
break;
case '|':
prec = 3;
break;
case '^':
prec = 4;
break;
case '&':
prec = 5;
break;
case '==':
case '!=':
case '===':
case '!==':
prec = 6;
break;
case '<':
case '>':
case '<=':
case '>=':
case 'instanceof':
prec = 7;
break;
case 'in':
prec = allowIn ? 7 : 0;
break;
case '<<':
case '>>':
case '>>>':
prec = 8;
break;
case '+':
case '-':
prec = 9;
break;
case '*':
case '/':
case '%':
prec = 11;
break;
default:
break;
}
return prec;
}
// 11.5 Multiplicative Operators
// 11.6 Additive Operators
// 11.7 Bitwise Shift Operators
// 11.8 Relational Operators
// 11.9 Equality Operators
// 11.10 Binary Bitwise Operators
// 11.11 Binary Logical Operators
function parseBinaryExpression() {
var expr, token, prec, previousAllowIn, stack, right, operator, left, i;
previousAllowIn = state.allowIn;
state.allowIn = true;
expr = parseUnaryExpression();
token = lookahead;
prec = binaryPrecedence(token, previousAllowIn);
if (prec === 0) {
return expr;
}
token.prec = prec;
lex();
stack = [expr, token, parseUnaryExpression()];
while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) {
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
operator = stack.pop().value;
left = stack.pop();
stack.push(delegate.createBinaryExpression(operator, left, right));
}
// Shift.
token = lex();
token.prec = prec;
stack.push(token);
stack.push(parseUnaryExpression());
}
state.allowIn = previousAllowIn;
// Final reduce to clean-up the stack.
i = stack.length - 1;
expr = stack[i];
while (i > 1) {
expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
i -= 2;
}
return expr;
}
// 11.12 Conditional Operator
function parseConditionalExpression() {
var expr, previousAllowIn, consequent, alternate;
expr = parseBinaryExpression();
if (match('?')) {
lex();
previousAllowIn = state.allowIn;
state.allowIn = true;
consequent = parseAssignmentExpression();
state.allowIn = previousAllowIn;
expect(':');
alternate = parseAssignmentExpression();
expr = delegate.createConditionalExpression(expr, consequent, alternate);
}
return expr;
}
// 11.13 Assignment Operators
function reinterpretAsAssignmentBindingPattern(expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInAssignment);
}
reinterpretAsAssignmentBindingPattern(property.value);
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
if (element) {
reinterpretAsAssignmentBindingPattern(element);
}
}
} else if (expr.type === Syntax.Identifier) {
if (isRestrictedWord(expr.name)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
} else if (expr.type === Syntax.SpreadElement) {
reinterpretAsAssignmentBindingPattern(expr.argument);
if (expr.argument.type === Syntax.ObjectPattern) {
throwError({}, Messages.ObjectPatternAsSpread);
}
} else {
if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
throwError({}, Messages.InvalidLHSInAssignment);
}
}
}
function reinterpretAsDestructuredParameter(options, expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInFormalsList);
}
reinterpretAsDestructuredParameter(options, property.value);
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
if (element) {
reinterpretAsDestructuredParameter(options, element);
}
}
} else if (expr.type === Syntax.Identifier) {
validateParam(options, expr, expr.name);
} else {
if (expr.type !== Syntax.MemberExpression) {
throwError({}, Messages.InvalidLHSInFormalsList);
}
}
}
function reinterpretAsCoverFormalsList(expressions) {
var i, len, param, params, defaults, defaultCount, options, rest;
params = [];
defaults = [];
defaultCount = 0;
rest = null;
options = {
paramSet: {}
};
for (i = 0, len = expressions.length; i < len; i += 1) {
param = expressions[i];
if (param.type === Syntax.Identifier) {
params.push(param);
defaults.push(null);
validateParam(options, param, param.name);
} else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) {
reinterpretAsDestructuredParameter(options, param);
params.push(param);
defaults.push(null);
} else if (param.type === Syntax.SpreadElement) {
assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression');
reinterpretAsDestructuredParameter(options, param.argument);
rest = param.argument;
} else if (param.type === Syntax.AssignmentExpression) {
params.push(param.left);
defaults.push(param.right);
++defaultCount;
validateParam(options, param.left, param.left.name);
} else {
return null;
}
}
if (options.message === Messages.StrictParamDupe) {
throwError(
strict ? options.stricted : options.firstRestricted,
options.message
);
}
if (defaultCount === 0) {
defaults = [];
}
return {
params: params,
defaults: defaults,
rest: rest,
stricted: options.stricted,
firstRestricted: options.firstRestricted,
message: options.message
};
}
function parseArrowFunctionExpression(options) {
var previousStrict, previousYieldAllowed, body;
expect('=>');
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
body = parseConciseBody();
if (strict && options.firstRestricted) {
throwError(options.firstRestricted, options.message);
}
if (strict && options.stricted) {
throwErrorTolerant(options.stricted, options.message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
return delegate.createArrowFunctionExpression(options.params, options.defaults, body, options.rest, body.type !== Syntax.BlockStatement);
}
function parseAssignmentExpression() {
var expr, token, params, oldParenthesizedCount;
if (matchKeyword('yield')) {
return parseYieldExpression();
}
oldParenthesizedCount = state.parenthesizedCount;
if (match('(')) {
token = lookahead2();
if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') {
params = parseParams();
if (!match('=>')) {
throwUnexpected(lex());
}
return parseArrowFunctionExpression(params);
}
}
token = lookahead;
expr = parseConditionalExpression();
if (match('=>') &&
(state.parenthesizedCount === oldParenthesizedCount ||
state.parenthesizedCount === (oldParenthesizedCount + 1))) {
if (expr.type === Syntax.Identifier) {
params = reinterpretAsCoverFormalsList([ expr ]);
} else if (expr.type === Syntax.SequenceExpression) {
params = reinterpretAsCoverFormalsList(expr.expressions);
}
if (params) {
return parseArrowFunctionExpression(params);
}
}
if (matchAssign()) {
// 11.13.1
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant(token, Messages.StrictLHSAssignment);
}
// ES.next draf 11.13 Runtime Semantics step 1
if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) {
reinterpretAsAssignmentBindingPattern(expr);
} else if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
expr = delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression());
}
return expr;
}
// 11.14 Comma Operator
function parseExpression() {
var expr, expressions, sequence, coverFormalsList, spreadFound, oldParenthesizedCount;
oldParenthesizedCount = state.parenthesizedCount;
expr = parseAssignmentExpression();
expressions = [ expr ];
if (match(',')) {
while (index < length) {
if (!match(',')) {
break;
}
lex();
expr = parseSpreadOrAssignmentExpression();
expressions.push(expr);
if (expr.type === Syntax.SpreadElement) {
spreadFound = true;
if (!match(')')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
break;
}
}
sequence = delegate.createSequenceExpression(expressions);
}
if (match('=>')) {
// Do not allow nested parentheses on the LHS of the =>.
if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) {
expr = expr.type === Syntax.SequenceExpression ? expr.expressions : expressions;
coverFormalsList = reinterpretAsCoverFormalsList(expr);
if (coverFormalsList) {
return parseArrowFunctionExpression(coverFormalsList);
}
}
throwUnexpected(lex());
}
if (spreadFound && lookahead2().value !== '=>') {
throwError({}, Messages.IllegalSpread);
}
return sequence || expr;
}
// 12.1 Block
function parseStatementList() {
var list = [],
statement;
while (index < length) {
if (match('}')) {
break;
}
statement = parseSourceElement();
if (typeof statement === 'undefined') {
break;
}
list.push(statement);
}
return list;
}
function parseBlock() {
var block;
expect('{');
block = parseStatementList();
expect('}');
return delegate.createBlockStatement(block);
}
// 12.2 Variable Statement
function parseTypeAnnotation(dontExpectColon) {
var typeIdentifier = null, paramTypes = null, returnType = null,
nullable = false;
if (!dontExpectColon) {
expect(':');
}
if (match('?')) {
lex();
nullable = true;
}
if (lookahead.type === Token.Identifier) {
typeIdentifier = parseVariableIdentifier();
}
if (match('(')) {
lex();
paramTypes = [];
while (lookahead.type === Token.Identifier || match('?')) {
paramTypes.push(parseTypeAnnotation(true));
if (!match(')')) {
expect(',');
}
}
expect(')');
expect('=>');
if (matchKeyword('void')) {
lex();
} else {
returnType = parseTypeAnnotation(true);
}
}
return delegate.createTypeAnnotation(
typeIdentifier,
paramTypes,
returnType,
nullable
);
}
function parseVariableIdentifier() {
var token = lex();
if (token.type !== Token.Identifier) {
throwUnexpected(token);
}
return delegate.createIdentifier(token.value);
}
function parseTypeAnnotatableIdentifier() {
var ident = parseVariableIdentifier();
if (match(':')) {
return delegate.createTypeAnnotatedIdentifier(ident, parseTypeAnnotation());
}
return ident;
}
function parseVariableDeclaration(kind) {
var id,
init = null;
if (match('{')) {
id = parseObjectInitialiser();
reinterpretAsAssignmentBindingPattern(id);
} else if (match('[')) {
id = parseArrayInitialiser();
reinterpretAsAssignmentBindingPattern(id);
} else {
id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier();
// 12.2.1
if (strict && isRestrictedWord(id.name)) {
throwErrorTolerant({}, Messages.StrictVarName);
}
}
if (kind === 'const') {
if (!match('=')) {
throwError({}, Messages.NoUnintializedConst);
}
expect('=');
init = parseAssignmentExpression();
} else if (match('=')) {
lex();
init = parseAssignmentExpression();
}
return delegate.createVariableDeclarator(id, init);
}
function parseVariableDeclarationList(kind) {
var list = [];
do {
list.push(parseVariableDeclaration(kind));
if (!match(',')) {
break;
}
lex();
} while (index < length);
return list;
}
function parseVariableStatement() {
var declarations;
expectKeyword('var');
declarations = parseVariableDeclarationList();
consumeSemicolon();
return delegate.createVariableDeclaration(declarations, 'var');
}
// kind may be `const` or `let`
// Both are experimental and not in the specification yet.
// see http://wiki.ecmascript.org/doku.php?id=harmony:const
// and http://wiki.ecmascript.org/doku.php?id=harmony:let
function parseConstLetDeclaration(kind) {
var declarations;
expectKeyword(kind);
declarations = parseVariableDeclarationList(kind);
consumeSemicolon();
return delegate.createVariableDeclaration(declarations, kind);
}
// http://wiki.ecmascript.org/doku.php?id=harmony:modules
function parseModuleDeclaration() {
var id, src, body;
lex(); // 'module'
if (peekLineTerminator()) {
throwError({}, Messages.NewlineAfterModule);
}
switch (lookahead.type) {
case Token.StringLiteral:
id = parsePrimaryExpression();
body = parseModuleBlock();
src = null;
break;
case Token.Identifier:
id = parseVariableIdentifier();
body = null;
if (!matchContextualKeyword('from')) {
throwUnexpected(lex());
}
lex();
src = parsePrimaryExpression();
if (src.type !== Syntax.Literal) {
throwError({}, Messages.InvalidModuleSpecifier);
}
break;
}
consumeSemicolon();
return delegate.createModuleDeclaration(id, src, body);
}
function parseExportBatchSpecifier() {
expect('*');
return delegate.createExportBatchSpecifier();
}
function parseExportSpecifier() {
var id, name = null;
id = parseVariableIdentifier();
if (matchContextualKeyword('as')) {
lex();
name = parseNonComputedProperty();
}
return delegate.createExportSpecifier(id, name);
}
function parseExportDeclaration() {
var previousAllowKeyword, decl, def, src, specifiers;
expectKeyword('export');
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'let':
case 'const':
case 'var':
case 'class':
case 'function':
return delegate.createExportDeclaration(parseSourceElement(), null, null);
}
}
if (isIdentifierName(lookahead)) {
previousAllowKeyword = state.allowKeyword;
state.allowKeyword = true;
decl = parseVariableDeclarationList('let');
state.allowKeyword = previousAllowKeyword;
return delegate.createExportDeclaration(decl, null, null);
}
specifiers = [];
src = null;
if (match('*')) {
specifiers.push(parseExportBatchSpecifier());
} else {
expect('{');
do {
specifiers.push(parseExportSpecifier());
} while (match(',') && lex());
expect('}');
}
if (matchContextualKeyword('from')) {
lex();
src = parsePrimaryExpression();
if (src.type !== Syntax.Literal) {
throwError({}, Messages.InvalidModuleSpecifier);
}
}
consumeSemicolon();
return delegate.createExportDeclaration(null, specifiers, src);
}
function parseImportDeclaration() {
var specifiers, kind, src;
expectKeyword('import');
specifiers = [];
if (isIdentifierName(lookahead)) {
kind = 'default';
specifiers.push(parseImportSpecifier());
if (!matchContextualKeyword('from')) {
throwError({}, Messages.NoFromAfterImport);
}
lex();
} else if (match('{')) {
kind = 'named';
lex();
do {
specifiers.push(parseImportSpecifier());
} while (match(',') && lex());
expect('}');
if (!matchContextualKeyword('from')) {
throwError({}, Messages.NoFromAfterImport);
}
lex();
}
src = parsePrimaryExpression();
if (src.type !== Syntax.Literal) {
throwError({}, Messages.InvalidModuleSpecifier);
}
consumeSemicolon();
return delegate.createImportDeclaration(specifiers, kind, src);
}
function parseImportSpecifier() {
var id, name = null;
id = parseNonComputedProperty();
if (matchContextualKeyword('as')) {
lex();
name = parseVariableIdentifier();
}
return delegate.createImportSpecifier(id, name);
}
// 12.3 Empty Statement
function parseEmptyStatement() {
expect(';');
return delegate.createEmptyStatement();
}
// 12.4 Expression Statement
function parseExpressionStatement() {
var expr = parseExpression();
consumeSemicolon();
return delegate.createExpressionStatement(expr);
}
// 12.5 If statement
function parseIfStatement() {
var test, consequent, alternate;
expectKeyword('if');
expect('(');
test = parseExpression();
expect(')');
consequent = parseStatement();
if (matchKeyword('else')) {
lex();
alternate = parseStatement();
} else {
alternate = null;
}
return delegate.createIfStatement(test, consequent, alternate);
}
// 12.6 Iteration Statements
function parseDoWhileStatement() {
var body, test, oldInIteration;
expectKeyword('do');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
if (match(';')) {
lex();
}
return delegate.createDoWhileStatement(body, test);
}
function parseWhileStatement() {
var test, body, oldInIteration;
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
return delegate.createWhileStatement(test, body);
}
function parseForVariableDeclaration() {
var token = lex(),
declarations = parseVariableDeclarationList();
return delegate.createVariableDeclaration(declarations, token.value);
}
function parseForStatement(opts) {
var init, test, update, left, right, body, operator, oldInIteration;
init = test = update = null;
expectKeyword('for');
// http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each
if (matchContextualKeyword('each')) {
throwError({}, Messages.EachNotAllowed);
}
expect('(');
if (match(';')) {
lex();
} else {
if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) {
state.allowIn = false;
init = parseForVariableDeclaration();
state.allowIn = true;
if (init.declarations.length === 1) {
if (matchKeyword('in') || matchContextualKeyword('of')) {
operator = lookahead;
if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) {
lex();
left = init;
right = parseExpression();
init = null;
}
}
}
} else {
state.allowIn = false;
init = parseExpression();
state.allowIn = true;
if (matchContextualKeyword('of')) {
operator = lex();
left = init;
right = parseExpression();
init = null;
} else if (matchKeyword('in')) {
// LeftHandSideExpression
if (!isAssignableLeftHandSide(init)) {
throwError({}, Messages.InvalidLHSInForIn);
}
operator = lex();
left = init;
right = parseExpression();
init = null;
}
}
if (typeof left === 'undefined') {
expect(';');
}
}
if (typeof left === 'undefined') {
if (!match(';')) {
test = parseExpression();
}
expect(';');
if (!match(')')) {
update = parseExpression();
}
}
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
if (!(opts !== undefined && opts.ignoreBody)) {
body = parseStatement();
}
state.inIteration = oldInIteration;
if (typeof left === 'undefined') {
return delegate.createForStatement(init, test, update, body);
}
if (operator.value === 'in') {
return delegate.createForInStatement(left, right, body);
}
return delegate.createForOfStatement(left, right, body);
}
// 12.7 The continue statement
function parseContinueStatement() {
var label = null, key;
expectKeyword('continue');
// Optimize the most common form: 'continue;'.
if (source.charCodeAt(index) === 59) {
lex();
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return delegate.createContinueStatement(null);
}
if (peekLineTerminator()) {
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return delegate.createContinueStatement(null);
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
key = '$' + label.name;
if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return delegate.createContinueStatement(label);
}
// 12.8 The break statement
function parseBreakStatement() {
var label = null, key;
expectKeyword('break');
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return delegate.createBreakStatement(null);
}
if (peekLineTerminator()) {
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return delegate.createBreakStatement(null);
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
key = '$' + label.name;
if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return delegate.createBreakStatement(label);
}
// 12.9 The return statement
function parseReturnStatement() {
var argument = null;
expectKeyword('return');
if (!state.inFunctionBody) {
throwErrorTolerant({}, Messages.IllegalReturn);
}
// 'return' followed by a space and an identifier is very common.
if (source.charCodeAt(index) === 32) {
if (isIdentifierStart(source.charCodeAt(index + 1))) {
argument = parseExpression();
consumeSemicolon();
return delegate.createReturnStatement(argument);
}
}
if (peekLineTerminator()) {
return delegate.createReturnStatement(null);
}
if (!match(';')) {
if (!match('}') && lookahead.type !== Token.EOF) {
argument = parseExpression();
}
}
consumeSemicolon();
return delegate.createReturnStatement(argument);
}
// 12.10 The with statement
function parseWithStatement() {
var object, body;
if (strict) {
throwErrorTolerant({}, Messages.StrictModeWith);
}
expectKeyword('with');
expect('(');
object = parseExpression();
expect(')');
body = parseStatement();
return delegate.createWithStatement(object, body);
}
// 12.10 The swith statement
function parseSwitchCase() {
var test,
consequent = [],
sourceElement;
if (matchKeyword('default')) {
lex();
test = null;
} else {
expectKeyword('case');
test = parseExpression();
}
expect(':');
while (index < length) {
if (match('}') || matchKeyword('default') || matchKeyword('case')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
consequent.push(sourceElement);
}
return delegate.createSwitchCase(test, consequent);
}
function parseSwitchStatement() {
var discriminant, cases, clause, oldInSwitch, defaultFound;
expectKeyword('switch');
expect('(');
discriminant = parseExpression();
expect(')');
expect('{');
cases = [];
if (match('}')) {
lex();
return delegate.createSwitchStatement(discriminant, cases);
}
oldInSwitch = state.inSwitch;
state.inSwitch = true;
defaultFound = false;
while (index < length) {
if (match('}')) {
break;
}
clause = parseSwitchCase();
if (clause.test === null) {
if (defaultFound) {
throwError({}, Messages.MultipleDefaultsInSwitch);
}
defaultFound = true;
}
cases.push(clause);
}
state.inSwitch = oldInSwitch;
expect('}');
return delegate.createSwitchStatement(discriminant, cases);
}
// 12.13 The throw statement
function parseThrowStatement() {
var argument;
expectKeyword('throw');
if (peekLineTerminator()) {
throwError({}, Messages.NewlineAfterThrow);
}
argument = parseExpression();
consumeSemicolon();
return delegate.createThrowStatement(argument);
}
// 12.14 The try statement
function parseCatchClause() {
var param, body;
expectKeyword('catch');
expect('(');
if (match(')')) {
throwUnexpected(lookahead);
}
param = parseExpression();
// 12.14.1
if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
throwErrorTolerant({}, Messages.StrictCatchVariable);
}
expect(')');
body = parseBlock();
return delegate.createCatchClause(param, body);
}
function parseTryStatement() {
var block, handlers = [], finalizer = null;
expectKeyword('try');
block = parseBlock();
if (matchKeyword('catch')) {
handlers.push(parseCatchClause());
}
if (matchKeyword('finally')) {
lex();
finalizer = parseBlock();
}
if (handlers.length === 0 && !finalizer) {
throwError({}, Messages.NoCatchOrFinally);
}
return delegate.createTryStatement(block, [], handlers, finalizer);
}
// 12.15 The debugger statement
function parseDebuggerStatement() {
expectKeyword('debugger');
consumeSemicolon();
return delegate.createDebuggerStatement();
}
// 12 Statements
function parseStatement() {
var type = lookahead.type,
expr,
labeledBody,
key;
if (type === Token.EOF) {
throwUnexpected(lookahead);
}
if (type === Token.Punctuator) {
switch (lookahead.value) {
case ';':
return parseEmptyStatement();
case '{':
return parseBlock();
case '(':
return parseExpressionStatement();
default:
break;
}
}
if (type === Token.Keyword) {
switch (lookahead.value) {
case 'break':
return parseBreakStatement();
case 'continue':
return parseContinueStatement();
case 'debugger':
return parseDebuggerStatement();
case 'do':
return parseDoWhileStatement();
case 'for':
return parseForStatement();
case 'function':
return parseFunctionDeclaration();
case 'class':
return parseClassDeclaration();
case 'if':
return parseIfStatement();
case 'return':
return parseReturnStatement();
case 'switch':
return parseSwitchStatement();
case 'throw':
return parseThrowStatement();
case 'try':
return parseTryStatement();
case 'var':
return parseVariableStatement();
case 'while':
return parseWhileStatement();
case 'with':
return parseWithStatement();
default:
break;
}
}
expr = parseExpression();
// 12.12 Labelled Statements
if ((expr.type === Syntax.Identifier) && match(':')) {
lex();
key = '$' + expr.name;
if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
throwError({}, Messages.Redeclaration, 'Label', expr.name);
}
state.labelSet[key] = true;
labeledBody = parseStatement();
delete state.labelSet[key];
return delegate.createLabeledStatement(expr, labeledBody);
}
consumeSemicolon();
return delegate.createExpressionStatement(expr);
}
// 13 Function Definition
function parseConciseBody() {
if (match('{')) {
return parseFunctionSourceElements();
}
return parseAssignmentExpression();
}
function parseFunctionSourceElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted,
oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount;
expect('{');
while (index < length) {
if (lookahead.type !== Token.StringLiteral) {
break;
}
token = lookahead;
sourceElement = parseSourceElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
oldLabelSet = state.labelSet;
oldInIteration = state.inIteration;
oldInSwitch = state.inSwitch;
oldInFunctionBody = state.inFunctionBody;
oldParenthesizedCount = state.parenthesizedCount;
state.labelSet = {};
state.inIteration = false;
state.inSwitch = false;
state.inFunctionBody = true;
state.parenthesizedCount = 0;
while (index < length) {
if (match('}')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
expect('}');
state.labelSet = oldLabelSet;
state.inIteration = oldInIteration;
state.inSwitch = oldInSwitch;
state.inFunctionBody = oldInFunctionBody;
state.parenthesizedCount = oldParenthesizedCount;
return delegate.createBlockStatement(sourceElements);
}
function validateParam(options, param, name) {
var key = '$' + name;
if (strict) {
if (isRestrictedWord(name)) {
options.stricted = param;
options.message = Messages.StrictParamName;
}
if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
options.stricted = param;
options.message = Messages.StrictParamDupe;
}
} else if (!options.firstRestricted) {
if (isRestrictedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamName;
} else if (isStrictModeReservedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictReservedWord;
} else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
options.firstRestricted = param;
options.message = Messages.StrictParamDupe;
}
}
options.paramSet[key] = true;
}
function parseParam(options) {
var token, rest, param, def;
token = lookahead;
if (token.value === '...') {
token = lex();
rest = true;
}
if (match('[')) {
param = parseArrayInitialiser();
reinterpretAsDestructuredParameter(options, param);
} else if (match('{')) {
if (rest) {
throwError({}, Messages.ObjectPatternAsRestParameter);
}
param = parseObjectInitialiser();
reinterpretAsDestructuredParameter(options, param);
} else {
// Typing rest params is awkward, so punting on that for now
param = rest
? parseVariableIdentifier()
: parseTypeAnnotatableIdentifier();
validateParam(options, token, token.value);
if (match('=')) {
if (rest) {
throwErrorTolerant(lookahead, Messages.DefaultRestParameter);
}
lex();
def = parseAssignmentExpression();
++options.defaultCount;
}
}
if (rest) {
if (!match(')')) {
throwError({}, Messages.ParameterAfterRestParameter);
}
options.rest = param;
return false;
}
options.params.push(param);
options.defaults.push(def);
return !match(')');
}
function parseParams(firstRestricted) {
var options;
options = {
params: [],
defaultCount: 0,
defaults: [],
rest: null,
firstRestricted: firstRestricted
};
expect('(');
if (!match(')')) {
options.paramSet = {};
while (index < length) {
if (!parseParam(options)) {
break;
}
expect(',');
}
}
expect(')');
if (options.defaultCount === 0) {
options.defaults = [];
}
if (match(':')) {
options.returnTypeAnnotation = parseTypeAnnotation();
}
return options;
}
function parseFunctionDeclaration() {
var id, body, token, tmp, firstRestricted, message, previousStrict, previousYieldAllowed, generator;
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
token = lookahead;
id = parseVariableIdentifier();
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
if (state.yieldAllowed && !state.yieldFound) {
throwErrorTolerant({}, Messages.NoYieldInGenerator);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
return delegate.createFunctionDeclaration(id, tmp.params, tmp.defaults, body, tmp.rest, generator, false,
tmp.returnTypeAnnotation);
}
function parseFunctionExpression() {
var token, id = null, firstRestricted, message, tmp, body, previousStrict, previousYieldAllowed, generator;
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
if (!match('(')) {
token = lookahead;
id = parseVariableIdentifier();
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
if (state.yieldAllowed && !state.yieldFound) {
throwErrorTolerant({}, Messages.NoYieldInGenerator);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
return delegate.createFunctionExpression(id, tmp.params, tmp.defaults, body, tmp.rest, generator, false,
tmp.returnTypeAnnotation);
}
function parseYieldExpression() {
var delegateFlag, expr;
expectKeyword('yield');
if (!state.yieldAllowed) {
throwErrorTolerant({}, Messages.IllegalYield);
}
delegateFlag = false;
if (match('*')) {
lex();
delegateFlag = true;
}
expr = parseAssignmentExpression();
state.yieldFound = true;
return delegate.createYieldExpression(expr, delegateFlag);
}
// 14 Classes
function parseMethodDefinition(existingPropNames) {
var token, key, param, propType, isValidDuplicateProp = false;
if (lookahead.value === 'static') {
propType = ClassPropertyType["static"];
lex();
} else {
propType = ClassPropertyType.prototype;
}
if (match('*')) {
lex();
return delegate.createMethodDefinition(
propType,
'',
parseObjectPropertyKey(),
parsePropertyMethodFunction({ generator: true })
);
}
token = lookahead;
key = parseObjectPropertyKey();
if (token.value === 'get' && !match('(')) {
key = parseObjectPropertyKey();
// It is a syntax error if any other properties have a name
// duplicating this one unless they are a setter
if (existingPropNames[propType].hasOwnProperty(key.name)) {
isValidDuplicateProp =
// There isn't already a getter for this prop
existingPropNames[propType][key.name].get === undefined
// There isn't already a data prop by this name
&& existingPropNames[propType][key.name].data === undefined
// The only existing prop by this name is a setter
&& existingPropNames[propType][key.name].set !== undefined;
if (!isValidDuplicateProp) {
throwError(key, Messages.IllegalDuplicateClassProperty);
}
} else {
existingPropNames[propType][key.name] = {};
}
existingPropNames[propType][key.name].get = true;
expect('(');
expect(')');
return delegate.createMethodDefinition(
propType,
'get',
key,
parsePropertyFunction({ generator: false })
);
}
if (token.value === 'set' && !match('(')) {
key = parseObjectPropertyKey();
// It is a syntax error if any other properties have a name
// duplicating this one unless they are a getter
if (existingPropNames[propType].hasOwnProperty(key.name)) {
isValidDuplicateProp =
// There isn't already a setter for this prop
existingPropNames[propType][key.name].set === undefined
// There isn't already a data prop by this name
&& existingPropNames[propType][key.name].data === undefined
// The only existing prop by this name is a getter
&& existingPropNames[propType][key.name].get !== undefined;
if (!isValidDuplicateProp) {
throwError(key, Messages.IllegalDuplicateClassProperty);
}
} else {
existingPropNames[propType][key.name] = {};
}
existingPropNames[propType][key.name].set = true;
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
return delegate.createMethodDefinition(
propType,
'set',
key,
parsePropertyFunction({ params: param, generator: false, name: token })
);
}
// It is a syntax error if any other properties have the same name as a
// non-getter, non-setter method
if (existingPropNames[propType].hasOwnProperty(key.name)) {
throwError(key, Messages.IllegalDuplicateClassProperty);
} else {
existingPropNames[propType][key.name] = {};
}
existingPropNames[propType][key.name].data = true;
return delegate.createMethodDefinition(
propType,
'',
key,
parsePropertyMethodFunction({ generator: false })
);
}
function parseClassElement(existingProps) {
if (match(';')) {
lex();
return;
}
return parseMethodDefinition(existingProps);
}
function parseClassBody() {
var classElement, classElements = [], existingProps = {};
existingProps[ClassPropertyType["static"]] = {};
existingProps[ClassPropertyType.prototype] = {};
expect('{');
while (index < length) {
if (match('}')) {
break;
}
classElement = parseClassElement(existingProps);
if (typeof classElement !== 'undefined') {
classElements.push(classElement);
}
}
expect('}');
return delegate.createClassBody(classElements);
}
function parseClassExpression() {
var id, previousYieldAllowed, superClass = null;
expectKeyword('class');
if (!matchKeyword('extends') && !match('{')) {
id = parseVariableIdentifier();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseAssignmentExpression();
state.yieldAllowed = previousYieldAllowed;
}
return delegate.createClassExpression(id, superClass, parseClassBody());
}
function parseClassDeclaration() {
var id, previousYieldAllowed, superClass = null;
expectKeyword('class');
id = parseVariableIdentifier();
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseAssignmentExpression();
state.yieldAllowed = previousYieldAllowed;
}
return delegate.createClassDeclaration(id, superClass, parseClassBody());
}
// 15 Program
function matchModuleDeclaration() {
var id;
if (matchContextualKeyword('module')) {
id = lookahead2();
return id.type === Token.StringLiteral || id.type === Token.Identifier;
}
return false;
}
function parseSourceElement() {
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'const':
case 'let':
return parseConstLetDeclaration(lookahead.value);
case 'function':
return parseFunctionDeclaration();
case 'export':
return parseExportDeclaration();
case 'import':
return parseImportDeclaration();
default:
return parseStatement();
}
}
if (matchModuleDeclaration()) {
throwError({}, Messages.NestedModule);
}
if (lookahead.type !== Token.EOF) {
return parseStatement();
}
}
function parseProgramElement() {
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'export':
return parseExportDeclaration();
case 'import':
return parseImportDeclaration();
}
}
if (matchModuleDeclaration()) {
return parseModuleDeclaration();
}
return parseSourceElement();
}
function parseProgramElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted;
while (index < length) {
token = lookahead;
if (token.type !== Token.StringLiteral) {
break;
}
sourceElement = parseProgramElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
while (index < length) {
sourceElement = parseProgramElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
return sourceElements;
}
function parseModuleElement() {
return parseSourceElement();
}
function parseModuleElements() {
var list = [],
statement;
while (index < length) {
if (match('}')) {
break;
}
statement = parseModuleElement();
if (typeof statement === 'undefined') {
break;
}
list.push(statement);
}
return list;
}
function parseModuleBlock() {
var block;
expect('{');
block = parseModuleElements();
expect('}');
return delegate.createBlockStatement(block);
}
function parseProgram() {
var body;
strict = false;
peek();
body = parseProgramElements();
return delegate.createProgram(body);
}
// The following functions are needed only when the option to preserve
// the comments is active.
function addComment(type, value, start, end, loc) {
assert(typeof start === 'number', 'Comment must have valid position');
// Because the way the actual token is scanned, often the comments
// (if any) are skipped twice during the lexical analysis.
// Thus, we need to skip adding a comment if the comment array already
// handled it.
if (extra.comments.length > 0) {
if (extra.comments[extra.comments.length - 1].range[1] > start) {
return;
}
}
extra.comments.push({
type: type,
value: value,
range: [start, end],
loc: loc
});
}
function scanComment() {
var comment, ch, loc, start, blockComment, lineComment;
comment = '';
blockComment = false;
lineComment = false;
while (index < length) {
ch = source[index];
if (lineComment) {
ch = source[index++];
if (isLineTerminator(ch.charCodeAt(0))) {
loc.end = {
line: lineNumber,
column: index - lineStart - 1
};
lineComment = false;
addComment('Line', comment, start, index - 1, loc);
if (ch === '\r' && source[index] === '\n') {
++index;
}
++lineNumber;
lineStart = index;
comment = '';
} else if (index >= length) {
lineComment = false;
comment += ch;
loc.end = {
line: lineNumber,
column: length - lineStart
};
addComment('Line', comment, start, length, loc);
} else {
comment += ch;
}
} else if (blockComment) {
if (isLineTerminator(ch.charCodeAt(0))) {
if (ch === '\r' && source[index + 1] === '\n') {
++index;
comment += '\r\n';
} else {
comment += ch;
}
++lineNumber;
++index;
lineStart = index;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
ch = source[index++];
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
comment += ch;
if (ch === '*') {
ch = source[index];
if (ch === '/') {
comment = comment.substr(0, comment.length - 1);
blockComment = false;
++index;
loc.end = {
line: lineNumber,
column: index - lineStart
};
addComment('Block', comment, start, index, loc);
comment = '';
}
}
}
} else if (ch === '/') {
ch = source[index + 1];
if (ch === '/') {
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
start = index;
index += 2;
lineComment = true;
if (index >= length) {
loc.end = {
line: lineNumber,
column: index - lineStart
};
lineComment = false;
addComment('Line', comment, start, index, loc);
}
} else if (ch === '*') {
start = index;
index += 2;
blockComment = true;
loc = {
start: {
line: lineNumber,
column: index - lineStart - 2
}
};
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
break;
}
} else if (isWhiteSpace(ch.charCodeAt(0))) {
++index;
} else if (isLineTerminator(ch.charCodeAt(0))) {
++index;
if (ch === '\r' && source[index] === '\n') {
++index;
}
++lineNumber;
lineStart = index;
} else {
break;
}
}
}
function filterCommentLocation() {
var i, entry, comment, comments = [];
for (i = 0; i < extra.comments.length; ++i) {
entry = extra.comments[i];
comment = {
type: entry.type,
value: entry.value
};
if (extra.range) {
comment.range = entry.range;
}
if (extra.loc) {
comment.loc = entry.loc;
}
comments.push(comment);
}
extra.comments = comments;
}
// 16 XJS
XHTMLEntities = {
quot: '\u0022',
amp: '&',
apos: "\u0027",
lt: "<",
gt: ">",
nbsp: "\u00A0",
iexcl: "\u00A1",
cent: "\u00A2",
pound: "\u00A3",
curren: "\u00A4",
yen: "\u00A5",
brvbar: "\u00A6",
sect: "\u00A7",
uml: "\u00A8",
copy: "\u00A9",
ordf: "\u00AA",
laquo: "\u00AB",
not: "\u00AC",
shy: "\u00AD",
reg: "\u00AE",
macr: "\u00AF",
deg: "\u00B0",
plusmn: "\u00B1",
sup2: "\u00B2",
sup3: "\u00B3",
acute: "\u00B4",
micro: "\u00B5",
para: "\u00B6",
middot: "\u00B7",
cedil: "\u00B8",
sup1: "\u00B9",
ordm: "\u00BA",
raquo: "\u00BB",
frac14: "\u00BC",
frac12: "\u00BD",
frac34: "\u00BE",
iquest: "\u00BF",
Agrave: "\u00C0",
Aacute: "\u00C1",
Acirc: "\u00C2",
Atilde: "\u00C3",
Auml: "\u00C4",
Aring: "\u00C5",
AElig: "\u00C6",
Ccedil: "\u00C7",
Egrave: "\u00C8",
Eacute: "\u00C9",
Ecirc: "\u00CA",
Euml: "\u00CB",
Igrave: "\u00CC",
Iacute: "\u00CD",
Icirc: "\u00CE",
Iuml: "\u00CF",
ETH: "\u00D0",
Ntilde: "\u00D1",
Ograve: "\u00D2",
Oacute: "\u00D3",
Ocirc: "\u00D4",
Otilde: "\u00D5",
Ouml: "\u00D6",
times: "\u00D7",
Oslash: "\u00D8",
Ugrave: "\u00D9",
Uacute: "\u00DA",
Ucirc: "\u00DB",
Uuml: "\u00DC",
Yacute: "\u00DD",
THORN: "\u00DE",
szlig: "\u00DF",
agrave: "\u00E0",
aacute: "\u00E1",
acirc: "\u00E2",
atilde: "\u00E3",
auml: "\u00E4",
aring: "\u00E5",
aelig: "\u00E6",
ccedil: "\u00E7",
egrave: "\u00E8",
eacute: "\u00E9",
ecirc: "\u00EA",
euml: "\u00EB",
igrave: "\u00EC",
iacute: "\u00ED",
icirc: "\u00EE",
iuml: "\u00EF",
eth: "\u00F0",
ntilde: "\u00F1",
ograve: "\u00F2",
oacute: "\u00F3",
ocirc: "\u00F4",
otilde: "\u00F5",
ouml: "\u00F6",
divide: "\u00F7",
oslash: "\u00F8",
ugrave: "\u00F9",
uacute: "\u00FA",
ucirc: "\u00FB",
uuml: "\u00FC",
yacute: "\u00FD",
thorn: "\u00FE",
yuml: "\u00FF",
OElig: "\u0152",
oelig: "\u0153",
Scaron: "\u0160",
scaron: "\u0161",
Yuml: "\u0178",
fnof: "\u0192",
circ: "\u02C6",
tilde: "\u02DC",
Alpha: "\u0391",
Beta: "\u0392",
Gamma: "\u0393",
Delta: "\u0394",
Epsilon: "\u0395",
Zeta: "\u0396",
Eta: "\u0397",
Theta: "\u0398",
Iota: "\u0399",
Kappa: "\u039A",
Lambda: "\u039B",
Mu: "\u039C",
Nu: "\u039D",
Xi: "\u039E",
Omicron: "\u039F",
Pi: "\u03A0",
Rho: "\u03A1",
Sigma: "\u03A3",
Tau: "\u03A4",
Upsilon: "\u03A5",
Phi: "\u03A6",
Chi: "\u03A7",
Psi: "\u03A8",
Omega: "\u03A9",
alpha: "\u03B1",
beta: "\u03B2",
gamma: "\u03B3",
delta: "\u03B4",
epsilon: "\u03B5",
zeta: "\u03B6",
eta: "\u03B7",
theta: "\u03B8",
iota: "\u03B9",
kappa: "\u03BA",
lambda: "\u03BB",
mu: "\u03BC",
nu: "\u03BD",
xi: "\u03BE",
omicron: "\u03BF",
pi: "\u03C0",
rho: "\u03C1",
sigmaf: "\u03C2",
sigma: "\u03C3",
tau: "\u03C4",
upsilon: "\u03C5",
phi: "\u03C6",
chi: "\u03C7",
psi: "\u03C8",
omega: "\u03C9",
thetasym: "\u03D1",
upsih: "\u03D2",
piv: "\u03D6",
ensp: "\u2002",
emsp: "\u2003",
thinsp: "\u2009",
zwnj: "\u200C",
zwj: "\u200D",
lrm: "\u200E",
rlm: "\u200F",
ndash: "\u2013",
mdash: "\u2014",
lsquo: "\u2018",
rsquo: "\u2019",
sbquo: "\u201A",
ldquo: "\u201C",
rdquo: "\u201D",
bdquo: "\u201E",
dagger: "\u2020",
Dagger: "\u2021",
bull: "\u2022",
hellip: "\u2026",
permil: "\u2030",
prime: "\u2032",
Prime: "\u2033",
lsaquo: "\u2039",
rsaquo: "\u203A",
oline: "\u203E",
frasl: "\u2044",
euro: "\u20AC",
image: "\u2111",
weierp: "\u2118",
real: "\u211C",
trade: "\u2122",
alefsym: "\u2135",
larr: "\u2190",
uarr: "\u2191",
rarr: "\u2192",
darr: "\u2193",
harr: "\u2194",
crarr: "\u21B5",
lArr: "\u21D0",
uArr: "\u21D1",
rArr: "\u21D2",
dArr: "\u21D3",
hArr: "\u21D4",
forall: "\u2200",
part: "\u2202",
exist: "\u2203",
empty: "\u2205",
nabla: "\u2207",
isin: "\u2208",
notin: "\u2209",
ni: "\u220B",
prod: "\u220F",
sum: "\u2211",
minus: "\u2212",
lowast: "\u2217",
radic: "\u221A",
prop: "\u221D",
infin: "\u221E",
ang: "\u2220",
and: "\u2227",
or: "\u2228",
cap: "\u2229",
cup: "\u222A",
"int": "\u222B",
there4: "\u2234",
sim: "\u223C",
cong: "\u2245",
asymp: "\u2248",
ne: "\u2260",
equiv: "\u2261",
le: "\u2264",
ge: "\u2265",
sub: "\u2282",
sup: "\u2283",
nsub: "\u2284",
sube: "\u2286",
supe: "\u2287",
oplus: "\u2295",
otimes: "\u2297",
perp: "\u22A5",
sdot: "\u22C5",
lceil: "\u2308",
rceil: "\u2309",
lfloor: "\u230A",
rfloor: "\u230B",
lang: "\u2329",
rang: "\u232A",
loz: "\u25CA",
spades: "\u2660",
clubs: "\u2663",
hearts: "\u2665",
diams: "\u2666"
};
function isXJSIdentifierStart(ch) {
// exclude backslash (\)
return (ch !== 92) && isIdentifierStart(ch);
}
function isXJSIdentifierPart(ch) {
// exclude backslash (\) and add hyphen (-)
return (ch !== 92) && (ch === 45 || isIdentifierPart(ch));
}
function scanXJSIdentifier() {
var ch, start, id = '', namespace;
start = index;
while (index < length) {
ch = source.charCodeAt(index);
if (!isXJSIdentifierPart(ch)) {
break;
}
id += source[index++];
}
if (ch === 58) { // :
++index;
namespace = id;
id = '';
while (index < length) {
ch = source.charCodeAt(index);
if (!isXJSIdentifierPart(ch)) {
break;
}
id += source[index++];
}
}
if (!id) {
throwError({}, Messages.InvalidXJSTagName);
}
return {
type: Token.XJSIdentifier,
value: id,
namespace: namespace,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanXJSEntity() {
var ch, str = '', count = 0, entity;
ch = source[index];
assert(ch === '&', 'Entity must start with an ampersand');
index++;
while (index < length && count++ < 10) {
ch = source[index++];
if (ch === ';') {
break;
}
str += ch;
}
if (str[0] === '#' && str[1] === 'x') {
entity = String.fromCharCode(parseInt(str.substr(2), 16));
} else if (str[0] === '#') {
entity = String.fromCharCode(parseInt(str.substr(1), 10));
} else {
entity = XHTMLEntities[str];
}
return entity;
}
function scanXJSText(stopChars) {
var ch, str = '', start;
start = index;
while (index < length) {
ch = source[index];
if (stopChars.indexOf(ch) !== -1) {
break;
}
if (ch === '&') {
str += scanXJSEntity();
} else {
ch = source[index++];
if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
lineStart = index;
}
str += ch;
}
}
return {
type: Token.XJSText,
value: str,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanXJSStringLiteral() {
var innerToken, quote, start;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
innerToken = scanXJSText([quote]);
if (quote !== source[index]) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
innerToken.range = [start, index];
return innerToken;
}
/**
* Between XJS opening and closing tags (e.g. <foo>HERE</foo>), anything that
* is not another XJS tag and is not an expression wrapped by {} is text.
*/
function advanceXJSChild() {
var ch = source.charCodeAt(index);
// { (123) and < (60)
if (ch !== 123 && ch !== 60) {
return scanXJSText(['<', '{']);
}
return scanPunctuator();
}
function parseXJSIdentifier() {
var token;
if (lookahead.type !== Token.XJSIdentifier) {
throwUnexpected(lookahead);
}
token = lex();
return delegate.createXJSIdentifier(token.value, token.namespace);
}
function parseXJSAttributeValue() {
var value;
if (match('{')) {
value = parseXJSExpressionContainer();
if (value.expression.type === Syntax.XJSEmptyExpression) {
throwError(
value,
'XJS attributes must only be assigned a non-empty ' +
'expression'
);
}
} else if (match('<')) {
value = parseXJSElement();
} else if (lookahead.type === Token.XJSText) {
value = delegate.createLiteral(lex());
} else {
throwError({}, Messages.InvalidXJSAttributeValue);
}
return value;
}
function parseXJSEmptyExpression() {
while (source.charAt(index) !== '}') {
index++;
}
return delegate.createXJSEmptyExpression();
}
function parseXJSExpressionContainer() {
var expression, origInXJSChild, origInXJSTag;
origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
state.inXJSChild = false;
state.inXJSTag = false;
expect('{');
if (match('}')) {
expression = parseXJSEmptyExpression();
} else {
expression = parseExpression();
}
state.inXJSChild = origInXJSChild;
state.inXJSTag = origInXJSTag;
expect('}');
return delegate.createXJSExpressionContainer(expression);
}
function parseXJSAttribute() {
var token, name, value;
name = parseXJSIdentifier();
// HTML empty attribute
if (match('=')) {
lex();
return delegate.createXJSAttribute(name, parseXJSAttributeValue());
}
return delegate.createXJSAttribute(name);
}
function parseXJSChild() {
var token;
if (match('{')) {
token = parseXJSExpressionContainer();
} else if (lookahead.type === Token.XJSText) {
token = delegate.createLiteral(lex());
} else {
token = parseXJSElement();
}
return token;
}
function parseXJSClosingElement() {
var name, origInXJSChild, origInXJSTag;
origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
state.inXJSChild = false;
state.inXJSTag = true;
expect('<');
expect('/');
name = parseXJSIdentifier();
// Because advance() (called by lex() called by expect()) expects there
// to be a valid token after >, it needs to know whether to look for a
// standard JS token or an XJS text node
state.inXJSChild = origInXJSChild;
state.inXJSTag = origInXJSTag;
expect('>');
return delegate.createXJSClosingElement(name);
}
function parseXJSOpeningElement() {
var name, attribute, attributes = [], selfClosing = false, origInXJSChild, origInXJSTag;
origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
state.inXJSChild = false;
state.inXJSTag = true;
expect('<');
name = parseXJSIdentifier();
while (index < length &&
lookahead.value !== '/' &&
lookahead.value !== '>') {
attributes.push(parseXJSAttribute());
}
state.inXJSTag = origInXJSTag;
if (lookahead.value === '/') {
expect('/');
// Because advance() (called by lex() called by expect()) expects
// there to be a valid token after >, it needs to know whether to
// look for a standard JS token or an XJS text node
state.inXJSChild = origInXJSChild;
expect('>');
selfClosing = true;
} else {
state.inXJSChild = true;
expect('>');
}
return delegate.createXJSOpeningElement(name, attributes, selfClosing);
}
function parseXJSElement() {
var openingElement, closingElement, children = [], origInXJSChild, origInXJSTag;
origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
openingElement = parseXJSOpeningElement();
if (!openingElement.selfClosing) {
while (index < length) {
state.inXJSChild = false; // Call lookahead2() with inXJSChild = false because </ should not be considered in the child
if (lookahead.value === '<' && lookahead2().value === '/') {
break;
}
state.inXJSChild = true;
peek(); // reset lookahead token
children.push(parseXJSChild());
}
state.inXJSChild = origInXJSChild;
state.inXJSTag = origInXJSTag;
closingElement = parseXJSClosingElement();
if (closingElement.name.namespace !== openingElement.name.namespace || closingElement.name.name !== openingElement.name.name) {
throwError({}, Messages.ExpectedXJSClosingTag, openingElement.name.namespace ? openingElement.name.namespace + ':' + openingElement.name.name : openingElement.name.name);
}
}
return delegate.createXJSElement(openingElement, closingElement, children);
}
function collectToken() {
var start, loc, token, range, value;
skipComment();
start = index;
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
token = extra.advance();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (token.type !== Token.EOF) {
range = [token.range[0], token.range[1]];
value = source.slice(token.range[0], token.range[1]);
extra.tokens.push({
type: TokenName[token.type],
value: value,
range: range,
loc: loc
});
}
return token;
}
function collectRegex() {
var pos, loc, regex, token;
skipComment();
pos = index;
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
regex = extra.scanRegExp();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (!extra.tokenize) {
// Pop the previous token, which is likely '/' or '/='
if (extra.tokens.length > 0) {
token = extra.tokens[extra.tokens.length - 1];
if (token.range[0] === pos && token.type === 'Punctuator') {
if (token.value === '/' || token.value === '/=') {
extra.tokens.pop();
}
}
}
extra.tokens.push({
type: 'RegularExpression',
value: regex.literal,
range: [pos, index],
loc: loc
});
}
return regex;
}
function filterTokenLocation() {
var i, entry, token, tokens = [];
for (i = 0; i < extra.tokens.length; ++i) {
entry = extra.tokens[i];
token = {
type: entry.type,
value: entry.value
};
if (extra.range) {
token.range = entry.range;
}
if (extra.loc) {
token.loc = entry.loc;
}
tokens.push(token);
}
extra.tokens = tokens;
}
function LocationMarker() {
this.range = [index, index];
this.loc = {
start: {
line: lineNumber,
column: index - lineStart
},
end: {
line: lineNumber,
column: index - lineStart
}
};
}
LocationMarker.prototype = {
constructor: LocationMarker,
end: function () {
this.range[1] = index;
this.loc.end.line = lineNumber;
this.loc.end.column = index - lineStart;
},
applyGroup: function (node) {
if (extra.range) {
node.groupRange = [this.range[0], this.range[1]];
}
if (extra.loc) {
node.groupLoc = {
start: {
line: this.loc.start.line,
column: this.loc.start.column
},
end: {
line: this.loc.end.line,
column: this.loc.end.column
}
};
node = delegate.postProcess(node);
}
},
apply: function (node) {
var nodeType = typeof node;
assert(nodeType === 'object',
'Applying location marker to an unexpected node type: ' +
nodeType);
if (extra.range) {
node.range = [this.range[0], this.range[1]];
}
if (extra.loc) {
node.loc = {
start: {
line: this.loc.start.line,
column: this.loc.start.column
},
end: {
line: this.loc.end.line,
column: this.loc.end.column
}
};
node = delegate.postProcess(node);
}
}
};
function createLocationMarker() {
return new LocationMarker();
}
function trackGroupExpression() {
var marker, expr;
skipComment();
marker = createLocationMarker();
expect('(');
++state.parenthesizedCount;
expr = parseExpression();
expect(')');
marker.end();
marker.applyGroup(expr);
return expr;
}
function trackLeftHandSideExpression() {
var marker, expr;
skipComment();
marker = createLocationMarker();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || lookahead.type === Token.Template) {
if (match('[')) {
expr = delegate.createMemberExpression('[', expr, parseComputedMember());
marker.end();
marker.apply(expr);
} else if (match('.')) {
expr = delegate.createMemberExpression('.', expr, parseNonComputedMember());
marker.end();
marker.apply(expr);
} else {
expr = delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral());
marker.end();
marker.apply(expr);
}
}
return expr;
}
function trackLeftHandSideExpressionAllowCall() {
var marker, expr, args;
skipComment();
marker = createLocationMarker();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) {
if (match('(')) {
args = parseArguments();
expr = delegate.createCallExpression(expr, args);
marker.end();
marker.apply(expr);
} else if (match('[')) {
expr = delegate.createMemberExpression('[', expr, parseComputedMember());
marker.end();
marker.apply(expr);
} else if (match('.')) {
expr = delegate.createMemberExpression('.', expr, parseNonComputedMember());
marker.end();
marker.apply(expr);
} else {
expr = delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral());
marker.end();
marker.apply(expr);
}
}
return expr;
}
function filterGroup(node) {
var n, i, entry;
n = (Object.prototype.toString.apply(node) === '[object Array]') ? [] : {};
for (i in node) {
if (node.hasOwnProperty(i) && i !== 'groupRange' && i !== 'groupLoc') {
entry = node[i];
if (entry === null || typeof entry !== 'object' || entry instanceof RegExp) {
n[i] = entry;
} else {
n[i] = filterGroup(entry);
}
}
}
return n;
}
function wrapTrackingFunction(range, loc, preserveWhitespace) {
return function (parseFunction) {
function isBinary(node) {
return node.type === Syntax.LogicalExpression ||
node.type === Syntax.BinaryExpression;
}
function visit(node) {
var start, end;
if (isBinary(node.left)) {
visit(node.left);
}
if (isBinary(node.right)) {
visit(node.right);
}
if (range) {
if (node.left.groupRange || node.right.groupRange) {
start = node.left.groupRange ? node.left.groupRange[0] : node.left.range[0];
end = node.right.groupRange ? node.right.groupRange[1] : node.right.range[1];
node.range = [start, end];
} else if (typeof node.range === 'undefined') {
start = node.left.range[0];
end = node.right.range[1];
node.range = [start, end];
}
}
if (loc) {
if (node.left.groupLoc || node.right.groupLoc) {
start = node.left.groupLoc ? node.left.groupLoc.start : node.left.loc.start;
end = node.right.groupLoc ? node.right.groupLoc.end : node.right.loc.end;
node.loc = {
start: start,
end: end
};
node = delegate.postProcess(node);
} else if (typeof node.loc === 'undefined') {
node.loc = {
start: node.left.loc.start,
end: node.right.loc.end
};
node = delegate.postProcess(node);
}
}
}
return function () {
var marker, node;
if (!preserveWhitespace) {
skipComment();
}
marker = createLocationMarker();
node = parseFunction.apply(null, arguments);
marker.end();
if (range && typeof node.range === 'undefined') {
marker.apply(node);
}
if (loc && typeof node.loc === 'undefined') {
marker.apply(node);
}
if (isBinary(node)) {
visit(node);
}
return node;
};
};
}
function patch() {
var wrapTracking, wrapTrackingPreserveWhitespace;
if (extra.comments) {
extra.skipComment = skipComment;
skipComment = scanComment;
}
if (extra.range || extra.loc) {
extra.parseGroupExpression = parseGroupExpression;
extra.parseLeftHandSideExpression = parseLeftHandSideExpression;
extra.parseLeftHandSideExpressionAllowCall = parseLeftHandSideExpressionAllowCall;
parseGroupExpression = trackGroupExpression;
parseLeftHandSideExpression = trackLeftHandSideExpression;
parseLeftHandSideExpressionAllowCall = trackLeftHandSideExpressionAllowCall;
wrapTracking = wrapTrackingFunction(extra.range, extra.loc);
wrapTrackingPreserveWhitespace =
wrapTrackingFunction(extra.range, extra.loc, true);
extra.parseArrayInitialiser = parseArrayInitialiser;
extra.parseAssignmentExpression = parseAssignmentExpression;
extra.parseBinaryExpression = parseBinaryExpression;
extra.parseBlock = parseBlock;
extra.parseFunctionSourceElements = parseFunctionSourceElements;
extra.parseCatchClause = parseCatchClause;
extra.parseComputedMember = parseComputedMember;
extra.parseConditionalExpression = parseConditionalExpression;
extra.parseConstLetDeclaration = parseConstLetDeclaration;
extra.parseExportBatchSpecifier = parseExportBatchSpecifier;
extra.parseExportDeclaration = parseExportDeclaration;
extra.parseExportSpecifier = parseExportSpecifier;
extra.parseExpression = parseExpression;
extra.parseForVariableDeclaration = parseForVariableDeclaration;
extra.parseFunctionDeclaration = parseFunctionDeclaration;
extra.parseFunctionExpression = parseFunctionExpression;
extra.parseParams = parseParams;
extra.parseImportDeclaration = parseImportDeclaration;
extra.parseImportSpecifier = parseImportSpecifier;
extra.parseModuleDeclaration = parseModuleDeclaration;
extra.parseModuleBlock = parseModuleBlock;
extra.parseNewExpression = parseNewExpression;
extra.parseNonComputedProperty = parseNonComputedProperty;
extra.parseObjectInitialiser = parseObjectInitialiser;
extra.parseObjectProperty = parseObjectProperty;
extra.parseObjectPropertyKey = parseObjectPropertyKey;
extra.parsePostfixExpression = parsePostfixExpression;
extra.parsePrimaryExpression = parsePrimaryExpression;
extra.parseProgram = parseProgram;
extra.parsePropertyFunction = parsePropertyFunction;
extra.parseSpreadOrAssignmentExpression = parseSpreadOrAssignmentExpression;
extra.parseTemplateElement = parseTemplateElement;
extra.parseTemplateLiteral = parseTemplateLiteral;
extra.parseTypeAnnotatableIdentifier = parseTypeAnnotatableIdentifier;
extra.parseTypeAnnotation = parseTypeAnnotation;
extra.parseStatement = parseStatement;
extra.parseSwitchCase = parseSwitchCase;
extra.parseUnaryExpression = parseUnaryExpression;
extra.parseVariableDeclaration = parseVariableDeclaration;
extra.parseVariableIdentifier = parseVariableIdentifier;
extra.parseMethodDefinition = parseMethodDefinition;
extra.parseClassDeclaration = parseClassDeclaration;
extra.parseClassExpression = parseClassExpression;
extra.parseClassBody = parseClassBody;
extra.parseXJSIdentifier = parseXJSIdentifier;
extra.parseXJSChild = parseXJSChild;
extra.parseXJSAttribute = parseXJSAttribute;
extra.parseXJSAttributeValue = parseXJSAttributeValue;
extra.parseXJSExpressionContainer = parseXJSExpressionContainer;
extra.parseXJSEmptyExpression = parseXJSEmptyExpression;
extra.parseXJSElement = parseXJSElement;
extra.parseXJSClosingElement = parseXJSClosingElement;
extra.parseXJSOpeningElement = parseXJSOpeningElement;
parseArrayInitialiser = wrapTracking(extra.parseArrayInitialiser);
parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression);
parseBinaryExpression = wrapTracking(extra.parseBinaryExpression);
parseBlock = wrapTracking(extra.parseBlock);
parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements);
parseCatchClause = wrapTracking(extra.parseCatchClause);
parseComputedMember = wrapTracking(extra.parseComputedMember);
parseConditionalExpression = wrapTracking(extra.parseConditionalExpression);
parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration);
parseExportBatchSpecifier = wrapTracking(parseExportBatchSpecifier);
parseExportDeclaration = wrapTracking(parseExportDeclaration);
parseExportSpecifier = wrapTracking(parseExportSpecifier);
parseExpression = wrapTracking(extra.parseExpression);
parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration);
parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration);
parseFunctionExpression = wrapTracking(extra.parseFunctionExpression);
parseParams = wrapTracking(extra.parseParams);
parseImportDeclaration = wrapTracking(extra.parseImportDeclaration);
parseImportSpecifier = wrapTracking(extra.parseImportSpecifier);
parseModuleDeclaration = wrapTracking(extra.parseModuleDeclaration);
parseModuleBlock = wrapTracking(extra.parseModuleBlock);
parseLeftHandSideExpression = wrapTracking(parseLeftHandSideExpression);
parseNewExpression = wrapTracking(extra.parseNewExpression);
parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty);
parseObjectInitialiser = wrapTracking(extra.parseObjectInitialiser);
parseObjectProperty = wrapTracking(extra.parseObjectProperty);
parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey);
parsePostfixExpression = wrapTracking(extra.parsePostfixExpression);
parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression);
parseProgram = wrapTracking(extra.parseProgram);
parsePropertyFunction = wrapTracking(extra.parsePropertyFunction);
parseTemplateElement = wrapTracking(extra.parseTemplateElement);
parseTemplateLiteral = wrapTracking(extra.parseTemplateLiteral);
parseTypeAnnotatableIdentifier = wrapTracking(extra.parseTypeAnnotatableIdentifier);
parseTypeAnnotation = wrapTracking(extra.parseTypeAnnotation);
parseSpreadOrAssignmentExpression = wrapTracking(extra.parseSpreadOrAssignmentExpression);
parseStatement = wrapTracking(extra.parseStatement);
parseSwitchCase = wrapTracking(extra.parseSwitchCase);
parseUnaryExpression = wrapTracking(extra.parseUnaryExpression);
parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration);
parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier);
parseMethodDefinition = wrapTracking(extra.parseMethodDefinition);
parseClassDeclaration = wrapTracking(extra.parseClassDeclaration);
parseClassExpression = wrapTracking(extra.parseClassExpression);
parseClassBody = wrapTracking(extra.parseClassBody);
parseXJSIdentifier = wrapTracking(extra.parseXJSIdentifier);
parseXJSChild = wrapTrackingPreserveWhitespace(extra.parseXJSChild);
parseXJSAttribute = wrapTracking(extra.parseXJSAttribute);
parseXJSAttributeValue = wrapTracking(extra.parseXJSAttributeValue);
parseXJSExpressionContainer = wrapTracking(extra.parseXJSExpressionContainer);
parseXJSEmptyExpression = wrapTrackingPreserveWhitespace(extra.parseXJSEmptyExpression);
parseXJSElement = wrapTracking(extra.parseXJSElement);
parseXJSClosingElement = wrapTracking(extra.parseXJSClosingElement);
parseXJSOpeningElement = wrapTracking(extra.parseXJSOpeningElement);
}
if (typeof extra.tokens !== 'undefined') {
extra.advance = advance;
extra.scanRegExp = scanRegExp;
advance = collectToken;
scanRegExp = collectRegex;
}
}
function unpatch() {
if (typeof extra.skipComment === 'function') {
skipComment = extra.skipComment;
}
if (extra.range || extra.loc) {
parseArrayInitialiser = extra.parseArrayInitialiser;
parseAssignmentExpression = extra.parseAssignmentExpression;
parseBinaryExpression = extra.parseBinaryExpression;
parseBlock = extra.parseBlock;
parseFunctionSourceElements = extra.parseFunctionSourceElements;
parseCatchClause = extra.parseCatchClause;
parseComputedMember = extra.parseComputedMember;
parseConditionalExpression = extra.parseConditionalExpression;
parseConstLetDeclaration = extra.parseConstLetDeclaration;
parseExportBatchSpecifier = extra.parseExportBatchSpecifier;
parseExportDeclaration = extra.parseExportDeclaration;
parseExportSpecifier = extra.parseExportSpecifier;
parseExpression = extra.parseExpression;
parseForVariableDeclaration = extra.parseForVariableDeclaration;
parseFunctionDeclaration = extra.parseFunctionDeclaration;
parseFunctionExpression = extra.parseFunctionExpression;
parseImportDeclaration = extra.parseImportDeclaration;
parseImportSpecifier = extra.parseImportSpecifier;
parseGroupExpression = extra.parseGroupExpression;
parseLeftHandSideExpression = extra.parseLeftHandSideExpression;
parseLeftHandSideExpressionAllowCall = extra.parseLeftHandSideExpressionAllowCall;
parseModuleDeclaration = extra.parseModuleDeclaration;
parseModuleBlock = extra.parseModuleBlock;
parseNewExpression = extra.parseNewExpression;
parseNonComputedProperty = extra.parseNonComputedProperty;
parseObjectInitialiser = extra.parseObjectInitialiser;
parseObjectProperty = extra.parseObjectProperty;
parseObjectPropertyKey = extra.parseObjectPropertyKey;
parsePostfixExpression = extra.parsePostfixExpression;
parsePrimaryExpression = extra.parsePrimaryExpression;
parseProgram = extra.parseProgram;
parsePropertyFunction = extra.parsePropertyFunction;
parseTemplateElement = extra.parseTemplateElement;
parseTemplateLiteral = extra.parseTemplateLiteral;
parseTypeAnnotatableIdentifier = extra.parseTypeAnnotatableIdentifier;
parseTypeAnnotation = extra.parseTypeAnnotation;
parseSpreadOrAssignmentExpression = extra.parseSpreadOrAssignmentExpression;
parseStatement = extra.parseStatement;
parseSwitchCase = extra.parseSwitchCase;
parseUnaryExpression = extra.parseUnaryExpression;
parseVariableDeclaration = extra.parseVariableDeclaration;
parseVariableIdentifier = extra.parseVariableIdentifier;
parseMethodDefinition = extra.parseMethodDefinition;
parseClassDeclaration = extra.parseClassDeclaration;
parseClassExpression = extra.parseClassExpression;
parseClassBody = extra.parseClassBody;
parseXJSIdentifier = extra.parseXJSIdentifier;
parseXJSChild = extra.parseXJSChild;
parseXJSAttribute = extra.parseXJSAttribute;
parseXJSAttributeValue = extra.parseXJSAttributeValue;
parseXJSExpressionContainer = extra.parseXJSExpressionContainer;
parseXJSEmptyExpression = extra.parseXJSEmptyExpression;
parseXJSElement = extra.parseXJSElement;
parseXJSClosingElement = extra.parseXJSClosingElement;
parseXJSOpeningElement = extra.parseXJSOpeningElement;
}
if (typeof extra.scanRegExp === 'function') {
advance = extra.advance;
scanRegExp = extra.scanRegExp;
}
}
// This is used to modify the delegate.
function extend(object, properties) {
var entry, result = {};
for (entry in object) {
if (object.hasOwnProperty(entry)) {
result[entry] = object[entry];
}
}
for (entry in properties) {
if (properties.hasOwnProperty(entry)) {
result[entry] = properties[entry];
}
}
return result;
}
function tokenize(code, options) {
var toString,
token,
tokens;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: true,
allowIn: true,
labelSet: {},
inFunctionBody: false,
inIteration: false,
inSwitch: false
};
extra = {};
// Options matching.
options = options || {};
// Of course we collect tokens here.
options.tokens = true;
extra.tokens = [];
extra.tokenize = true;
// The following two fields are necessary to compute the Regex tokens.
extra.openParenToken = -1;
extra.openCurlyToken = -1;
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
if (length > 0) {
if (typeof source[0] === 'undefined') {
// Try first to convert to a string. This is good as fast path
// for old IE which understands string indexing for string
// literals only and not for string object.
if (code instanceof String) {
source = code.valueOf();
}
}
}
patch();
try {
peek();
if (lookahead.type === Token.EOF) {
return extra.tokens;
}
token = lex();
while (lookahead.type !== Token.EOF) {
try {
token = lex();
} catch (lexError) {
token = lookahead;
if (extra.errors) {
extra.errors.push(lexError);
// We have to break on the first error
// to avoid infinite loops.
break;
} else {
throw lexError;
}
}
}
filterTokenLocation();
tokens = extra.tokens;
if (typeof extra.comments !== 'undefined') {
filterCommentLocation();
tokens.comments = extra.comments;
}
if (typeof extra.errors !== 'undefined') {
tokens.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return tokens;
}
function parse(code, options) {
var program, toString;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: false,
allowIn: true,
labelSet: {},
parenthesizedCount: 0,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
inXJSChild: false,
inXJSTag: false,
yieldAllowed: false,
yieldFound: false
};
extra = {};
if (typeof options !== 'undefined') {
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
if (extra.loc && options.source !== null && options.source !== undefined) {
delegate = extend(delegate, {
'postProcess': function (node) {
node.loc.source = toString(options.source);
return node;
}
});
}
if (typeof options.tokens === 'boolean' && options.tokens) {
extra.tokens = [];
}
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
}
if (length > 0) {
if (typeof source[0] === 'undefined') {
// Try first to convert to a string. This is good as fast path
// for old IE which understands string indexing for string
// literals only and not for string object.
if (code instanceof String) {
source = code.valueOf();
}
}
}
patch();
try {
program = parseProgram();
if (typeof extra.comments !== 'undefined') {
filterCommentLocation();
program.comments = extra.comments;
}
if (typeof extra.tokens !== 'undefined') {
filterTokenLocation();
program.tokens = extra.tokens;
}
if (typeof extra.errors !== 'undefined') {
program.errors = extra.errors;
}
if (extra.range || extra.loc) {
program.body = filterGroup(program.body);
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return program;
}
// Sync with *.json manifests.
exports.version = '1.1.0-dev-harmony';
exports.tokenize = tokenize;
exports.parse = parse;
// Deep copy.
exports.Syntax = (function () {
var name, types = {};
if (typeof Object.create === 'function') {
types = Object.create(null);
}
for (name in Syntax) {
if (Syntax.hasOwnProperty(name)) {
types[name] = Syntax[name];
}
}
if (typeof Object.freeze === 'function') {
Object.freeze(types);
}
return types;
}());
}));
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],7:[function(_dereq_,module,exports){
var Base62 = (function (my) {
my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "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"]
my.encode = function(i){
if (i === 0) {return '0'}
var s = ''
while (i > 0) {
s = this.chars[i % 62] + s
i = Math.floor(i/62)
}
return s
};
my.decode = function(a,b,c,d){
for (
b = c = (
a === (/\W|_|^$/.test(a += "") || a)
) - 1;
d = a.charCodeAt(c++);
)
b = b * 62 + d - [, 48, 29, 87][d >> 5];
return b
};
return my;
}({}));
module.exports = Base62
},{}],8:[function(_dereq_,module,exports){
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer;
exports.SourceNode = _dereq_('./source-map/source-node').SourceNode;
},{"./source-map/source-map-consumer":13,"./source-map/source-map-generator":14,"./source-map/source-node":15}],9:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = {};
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var isDuplicate = this.has(aStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[util.toSetString(aStr)] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set,
util.toSetString(aStr));
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
return this._set[util.toSetString(aStr)];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
});
},{"./util":16,"amdefine":17}],10:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64 = _dereq_('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string.
*/
exports.decode = function base64VLQ_decode(aStr) {
var i = 0;
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (i >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charAt(i++));
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return {
value: fromVLQSigned(result),
rest: aStr.slice(i)
};
};
});
},{"./base64":11,"amdefine":17}],11:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
.split('')
.forEach(function (ch, index) {
charToIntMap[ch] = index;
intToCharMap[index] = ch;
});
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function base64_encode(aNumber) {
if (aNumber in intToCharMap) {
return intToCharMap[aNumber];
}
throw new TypeError("Must be between 0 and 63: " + aNumber);
};
/**
* Decode a single base 64 digit to an integer.
*/
exports.decode = function base64_decode(aChar) {
if (aChar in charToIntMap) {
return charToIntMap[aChar];
}
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
},{"amdefine":17}],12:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the next
// closest element that is less than that element.
//
// 3. We did not find the exact element, and there is no next-closest
// element which is less than the one we are searching for, so we
// return null.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return aHaystack[mid];
}
else if (cmp > 0) {
// aHaystack[mid] is greater than our needle.
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
// We did not find an exact match, return the next closest one
// (termination case 2).
return aHaystack[mid];
}
else {
// aHaystack[mid] is less than our needle.
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (2) or (3) and return the appropriate thing.
return aLow < 0
? null
: aHaystack[aLow];
}
}
/**
* This is an implementation of binary search which will always try and return
* the next lowest value checked if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
*/
exports.search = function search(aNeedle, aHaystack, aCompare) {
return aHaystack.length > 0
? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
: null;
};
});
},{"amdefine":17}],13:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
var binarySearch = _dereq_('./binary-search');
var ArraySet = _dereq_('./array-set').ArraySet;
var base64VLQ = _dereq_('./base64-vlq');
/**
* A SourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
*/
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names, true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
/**
* Create a SourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns SourceMapConsumer
*/
SourceMapConsumer.fromSourceMap =
function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(SourceMapConsumer.prototype);
smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
smc.sourceRoot);
smc.file = aSourceMap._file;
smc.__generatedMappings = aSourceMap._mappings.slice()
.sort(util.compareByGeneratedPositions);
smc.__originalMappings = aSourceMap._mappings.slice()
.sort(util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
get: function () {
return this._sources.toArray().map(function (s) {
return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function () {
if (!this.__generatedMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function () {
if (!this.__originalMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var mappingSeparator = /^[,;]/;
var str = aStr;
var mapping;
var temp;
while (str.length > 0) {
if (str.charAt(0) === ';') {
generatedLine++;
str = str.slice(1);
previousGeneratedColumn = 0;
}
else if (str.charAt(0) === ',') {
str = str.slice(1);
}
else {
mapping = {};
mapping.generatedLine = generatedLine;
// Generated column.
temp = base64VLQ.decode(str);
mapping.generatedColumn = previousGeneratedColumn + temp.value;
previousGeneratedColumn = mapping.generatedColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original source.
temp = base64VLQ.decode(str);
mapping.source = this._sources.at(previousSource + temp.value);
previousSource += temp.value;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source, but no line and column');
}
// Original line.
temp = base64VLQ.decode(str);
mapping.originalLine = previousOriginalLine + temp.value;
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source and line, but no column');
}
// Original column.
temp = base64VLQ.decode(str);
mapping.originalColumn = previousOriginalColumn + temp.value;
previousOriginalColumn = mapping.originalColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original name.
temp = base64VLQ.decode(str);
mapping.name = this._names.at(previousName + temp.value);
previousName += temp.value;
str = temp.rest;
}
}
this.__generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
this.__originalMappings.push(mapping);
}
}
}
this.__originalMappings.sort(util.compareByOriginalPositions);
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
SourceMapConsumer.prototype._findMapping =
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
aColumnName, aComparator) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got '
+ aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator);
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
SourceMapConsumer.prototype.originalPositionFor =
function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var mapping = this._findMapping(needle,
this._generatedMappings,
"generatedLine",
"generatedColumn",
util.compareByGeneratedPositions);
if (mapping) {
var source = util.getArg(mapping, 'source', null);
if (source && this.sourceRoot) {
source = util.join(this.sourceRoot, source);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: util.getArg(mapping, 'name', null)
};
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* availible.
*/
SourceMapConsumer.prototype.sourceContentFor =
function SourceMapConsumer_sourceContentFor(aSource) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot
&& (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file"
&& this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
}
if ((!url.path || url.path == "/")
&& this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
throw new Error('"' + aSource + '" is not in the SourceMap.');
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.generatedPositionFor =
function SourceMapConsumer_generatedPositionFor(aArgs) {
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
if (this.sourceRoot) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
var mapping = this._findMapping(needle,
this._originalMappings,
"originalLine",
"originalColumn",
util.compareByOriginalPositions);
if (mapping) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null)
};
}
return {
line: null,
column: null
};
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping =
function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source;
if (source && sourceRoot) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name
};
}).forEach(aCallback, context);
};
exports.SourceMapConsumer = SourceMapConsumer;
});
},{"./array-set":9,"./base64-vlq":10,"./binary-search":12,"./util":16,"amdefine":17}],14:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64VLQ = _dereq_('./base64-vlq');
var util = _dereq_('./util');
var ArraySet = _dereq_('./array-set').ArraySet;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. To create a new one, you must pass an object
* with the following properties:
*
* - file: The filename of the generated source.
* - sourceRoot: An optional root for all URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
this._file = util.getArg(aArgs, 'file');
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = [];
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source) {
newMapping.source = mapping.source;
if (sourceRoot) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
this._validateMapping(generated, original, source, name);
if (source && !this._sources.has(source)) {
this._sources.add(source);
}
if (name && !this._names.has(name)) {
this._names.add(name);
}
this._mappings.push({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent !== null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = {};
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (!aSourceFile) {
aSourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "aSourceFile" relative if an absolute Url is passed.
if (sourceRoot) {
aSourceFile = util.relative(sourceRoot, aSourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "aSourceFile"
this._mappings.forEach(function (mapping) {
if (mapping.source === aSourceFile && mapping.originalLine) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source !== null) {
// Copy mapping
if (sourceRoot) {
mapping.source = util.relative(sourceRoot, original.source);
} else {
mapping.source = original.source;
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name !== null && mapping.name !== null) {
// Only use the identifier name if it's an identifier
// in both SourceMaps
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
if (sourceRoot) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
orginal: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var mapping;
// The mappings must be guaranteed to be in sorted order before we start
// serializing them or else the generated line numbers (which are defined
// via the ';' separators) will be all messed up. Note: it might be more
// performant to maintain the sorting as we insert them, rather than as we
// serialize them, but the big O is the same either way.
this._mappings.sort(util.compareByGeneratedPositions);
for (var i = 0, len = this._mappings.length; i < len; i++) {
mapping = this._mappings[i];
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
result += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
continue;
}
result += ',';
}
}
result += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source) {
result += base64VLQ.encode(this._sources.indexOf(mapping.source)
- previousSource);
previousSource = this._sources.indexOf(mapping.source);
// lines are stored 0-based in SourceMap spec version 3
result += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
result += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name) {
result += base64VLQ.encode(this._names.indexOf(mapping.name)
- previousName);
previousName = this._names.indexOf(mapping.name);
}
}
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents,
key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
file: this._file,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._sourceRoot) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this);
};
exports.SourceMapGenerator = SourceMapGenerator;
});
},{"./array-set":9,"./base64-vlq":10,"./util":16,"amdefine":17}],15:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator;
var util = _dereq_('./util');
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine === undefined ? null : aLine;
this.column = aColumn === undefined ? null : aColumn;
this.source = aSource === undefined ? null : aSource;
this.name = aName === undefined ? null : aName;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// The generated code
// Processed fragments are removed from this array.
var remainingLines = aGeneratedCode.split('\n');
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping === null) {
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(remainingLines.shift() + "\n");
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
} else {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
var code = "";
// Associate full lines with "lastMapping"
do {
code += remainingLines.shift() + "\n";
lastGeneratedLine++;
lastGeneratedColumn = 0;
} while (lastGeneratedLine < mapping.generatedLine);
// When we reached the correct line, we add code until we
// reach the correct column too.
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
code += nextLine.substr(0, mapping.generatedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
// Create the SourceNode.
addMappingWithCode(lastMapping, code);
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
}
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
// Associate the remaining code in the current line with "lastMapping"
// and add the remaining lines without any mapping
addMappingWithCode(lastMapping, remainingLines.join("\n"));
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
mapping.source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk instanceof SourceNode) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild instanceof SourceNode) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i] instanceof SourceNode) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
chunk.split('').forEach(function (ch) {
if (ch === '\n') {
generated.line++;
generated.column = 0;
} else {
generated.column++;
}
});
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
});
},{"./source-map-generator":14,"./util":16,"amdefine":17}],16:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
var dataUrlRegexp = /^data:.+\,.+/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[3],
host: match[4],
port: match[6],
path: match[7]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = aParsedUrl.scheme + "://";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@"
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function join(aRoot, aPath) {
var url;
if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
url.path = aPath;
return urlGenerate(url);
}
return aRoot.replace(/\/$/, '') + '/' + aPath;
}
exports.join = join;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
};
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings where the generated positions are
* compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
},{"amdefine":17}],17:[function(_dereq_,module,exports){
(function (process,__filename){
/** vim: et:ts=4:sw=4:sts=4
* @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/amdefine for details
*/
/*jslint node: true */
/*global module, process */
'use strict';
/**
* Creates a define for node.
* @param {Object} module the "module" object that is defined by Node for the
* current module.
* @param {Function} [requireFn]. Node's require function for the current module.
* It only needs to be passed in Node versions before 0.5, when module.require
* did not exist.
* @returns {Function} a define function that is usable for the current node
* module.
*/
function amdefine(module, requireFn) {
'use strict';
var defineCache = {},
loaderCache = {},
alreadyCalled = false,
path = _dereq_('path'),
makeRequire, stringRequire;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i+= 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
function normalize(name, baseName) {
var baseParts;
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
baseParts = baseName.split('/');
baseParts = baseParts.slice(0, baseParts.length - 1);
baseParts = baseParts.concat(name.split('/'));
trimDots(baseParts);
name = baseParts.join('/');
}
}
return name;
}
/**
* Create the normalize() function passed to a loader plugin's
* normalize method.
*/
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(id) {
function load(value) {
loaderCache[id] = value;
}
load.fromText = function (id, text) {
//This one is difficult because the text can/probably uses
//define, and any relative paths and requires should be relative
//to that id was it would be found on disk. But this would require
//bootstrapping a module/require fairly deeply from node core.
//Not sure how best to go about that yet.
throw new Error('amdefine does not implement load.fromText');
};
return load;
}
makeRequire = function (systemRequire, exports, module, relId) {
function amdRequire(deps, callback) {
if (typeof deps === 'string') {
//Synchronous, single module require('')
return stringRequire(systemRequire, exports, module, deps, relId);
} else {
//Array of dependencies with a callback.
//Convert the dependencies to modules.
deps = deps.map(function (depName) {
return stringRequire(systemRequire, exports, module, depName, relId);
});
//Wait for next tick to call back the require call.
process.nextTick(function () {
callback.apply(null, deps);
});
}
}
amdRequire.toUrl = function (filePath) {
if (filePath.indexOf('.') === 0) {
return normalize(filePath, path.dirname(module.filename));
} else {
return filePath;
}
};
return amdRequire;
};
//Favor explicit value, passed in if the module wants to support Node 0.4.
requireFn = requireFn || function req() {
return module.require.apply(module, arguments);
};
function runFactory(id, deps, factory) {
var r, e, m, result;
if (id) {
e = loaderCache[id] = {};
m = {
id: id,
uri: __filename,
exports: e
};
r = makeRequire(requireFn, e, m, id);
} else {
//Only support one define call per file
if (alreadyCalled) {
throw new Error('amdefine with no module ID cannot be called more than once per file.');
}
alreadyCalled = true;
//Use the real variables from node
//Use module.exports for exports, since
//the exports in here is amdefine exports.
e = module.exports;
m = module;
r = makeRequire(requireFn, e, m, module.id);
}
//If there are dependencies, they are strings, so need
//to convert them to dependency values.
if (deps) {
deps = deps.map(function (depName) {
return r(depName);
});
}
//Call the factory with the right dependencies.
if (typeof factory === 'function') {
result = factory.apply(m.exports, deps);
} else {
result = factory;
}
if (result !== undefined) {
m.exports = result;
if (id) {
loaderCache[id] = m.exports;
}
}
}
stringRequire = function (systemRequire, exports, module, id, relId) {
//Split the ID by a ! so that
var index = id.indexOf('!'),
originalId = id,
prefix, plugin;
if (index === -1) {
id = normalize(id, relId);
//Straight module lookup. If it is one of the special dependencies,
//deal with it, otherwise, delegate to node.
if (id === 'require') {
return makeRequire(systemRequire, exports, module, relId);
} else if (id === 'exports') {
return exports;
} else if (id === 'module') {
return module;
} else if (loaderCache.hasOwnProperty(id)) {
return loaderCache[id];
} else if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
} else {
if(systemRequire) {
return systemRequire(originalId);
} else {
throw new Error('No module with ID: ' + id);
}
}
} else {
//There is a plugin in play.
prefix = id.substring(0, index);
id = id.substring(index + 1, id.length);
plugin = stringRequire(systemRequire, exports, module, prefix, relId);
if (plugin.normalize) {
id = plugin.normalize(id, makeNormalize(relId));
} else {
//Normalize the ID normally.
id = normalize(id, relId);
}
if (loaderCache[id]) {
return loaderCache[id];
} else {
plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
return loaderCache[id];
}
}
};
//Create a define function specific to the module asking for amdefine.
function define(id, deps, factory) {
if (Array.isArray(id)) {
factory = deps;
deps = id;
id = undefined;
} else if (typeof id !== 'string') {
factory = id;
id = deps = undefined;
}
if (deps && !Array.isArray(deps)) {
factory = deps;
deps = undefined;
}
if (!deps) {
deps = ['require', 'exports', 'module'];
}
//Set up properties for this module. If an ID, then use
//internal cache. If no ID, then use the external variables
//for this node module.
if (id) {
//Put the module in deep freeze until there is a
//require call for it.
defineCache[id] = [id, deps, factory];
} else {
runFactory(id, deps, factory);
}
}
//define.require, which has access to all the values in the
//cache. Useful for AMD modules that all have IDs in the file,
//but need to finally export a value to node based on one of those
//IDs.
define.require = function (id) {
if (loaderCache[id]) {
return loaderCache[id];
}
if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
}
};
define.amd = {};
return define;
}
module.exports = amdefine;
}).call(this,_dereq_("/Users/poshannessy/FB/code/react/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"),"/../node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js")
},{"/Users/poshannessy/FB/code/react/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":4,"path":5}],18:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/;
var ltrimRe = /^\s*/;
/**
* @param {String} contents
* @return {String}
*/
function extract(contents) {
var match = contents.match(docblockRe);
if (match) {
return match[0].replace(ltrimRe, '') || '';
}
return '';
}
var commentStartRe = /^\/\*\*?/;
var commentEndRe = /\*+\/$/;
var wsRe = /[\t ]+/g;
var stringStartRe = /(\r?\n|^) *\*/g;
var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
/**
* @param {String} contents
* @return {Array}
*/
function parse(docblock) {
docblock = docblock
.replace(commentStartRe, '')
.replace(commentEndRe, '')
.replace(wsRe, ' ')
.replace(stringStartRe, '$1');
// Normalize multi-line directives
var prev = '';
while (prev != docblock) {
prev = docblock;
docblock = docblock.replace(multilineRe, "\n$1 $2\n");
}
docblock = docblock.trim();
var result = [];
var match;
while (match = propertyRe.exec(docblock)) {
result.push([match[1], match[2]]);
}
return result;
}
/**
* Same as parse but returns an object of prop: value instead of array of paris
* If a property appers more than once the last one will be returned
*
* @param {String} contents
* @return {Object}
*/
function parseAsObject(docblock) {
var pairs = parse(docblock);
var result = {};
for (var i = 0; i < pairs.length; i++) {
result[pairs[i][0]] = pairs[i][1];
}
return result;
}
exports.extract = extract;
exports.parse = parse;
exports.parseAsObject = parseAsObject;
},{}],19:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node: true*/
"use strict";
/**
* Syntax transfomer for javascript. Takes the source in, spits the source
* out.
*
* Parses input source with esprima, applies the given list of visitors to the
* AST tree, and returns the resulting output.
*/
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('./utils');
var Syntax = esprima.Syntax;
/**
* @param {object} node
* @param {object} parentNode
* @return {boolean}
*/
function _nodeIsClosureScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return true;
}
var parentIsFunction =
parentNode.type === Syntax.FunctionDeclaration
|| parentNode.type === Syntax.FunctionExpression;
return node.type === Syntax.BlockStatement && parentIsFunction;
}
function _nodeIsBlockScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return false;
}
return node.type === Syntax.BlockStatement
&& parentNode.type === Syntax.CatchClause;
}
/**
* @param {object} node
* @param {function} visitor
* @param {array} path
* @param {object} state
*/
function traverse(node, path, state) {
// Create a scope stack entry if this is the first node we've encountered in
// its local scope
var parentNode = path[0];
if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) {
if (_nodeIsClosureScopeBoundary(node, parentNode)) {
var scopeIsStrict =
state.scopeIsStrict
|| node.body.length > 0
&& node.body[0].type === Syntax.ExpressionStatement
&& node.body[0].expression.type === Syntax.Literal
&& node.body[0].expression.value === 'use strict';
if (node.type === Syntax.Program) {
state = utils.updateState(state, {
scopeIsStrict: scopeIsStrict
});
} else {
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {}
},
scopeIsStrict: scopeIsStrict
});
// All functions have an implicit 'arguments' object in scope
state.localScope.identifiers['arguments'] = true;
// Include function arg identifiers in the scope boundaries of the
// function
if (parentNode.params.length > 0) {
var param;
for (var i = 0; i < parentNode.params.length; i++) {
param = parentNode.params[i];
if (param.type === Syntax.Identifier) {
state.localScope.identifiers[param.name] = true;
}
}
}
// Named FunctionExpressions scope their name within the body block of
// themselves only
if (parentNode.type === Syntax.FunctionExpression && parentNode.id) {
state.localScope.identifiers[parentNode.id.name] = true;
}
}
// Traverse and find all local identifiers in this closure first to
// account for function/variable declaration hoisting
collectClosureIdentsAndTraverse(node, path, state);
}
if (_nodeIsBlockScopeBoundary(node, parentNode)) {
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {}
}
});
if (parentNode.type === Syntax.CatchClause) {
state.localScope.identifiers[parentNode.param.name] = true;
}
collectBlockIdentsAndTraverse(node, path, state);
}
}
// Only catchup() before and after traversing a child node
function traverser(node, path, state) {
node.range && utils.catchup(node.range[0], state);
traverse(node, path, state);
node.range && utils.catchup(node.range[1], state);
}
utils.analyzeAndTraverse(walker, traverser, node, path, state);
}
function collectClosureIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalClosureIdentifiers,
collectClosureIdentsAndTraverse,
node,
path,
state
);
}
function collectBlockIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalBlockIdentifiers,
collectBlockIdentsAndTraverse,
node,
path,
state
);
}
function visitLocalClosureIdentifiers(node, path, state) {
var identifiers = state.localScope.identifiers;
switch (node.type) {
case Syntax.FunctionExpression:
// Function expressions don't get their names (if there is one) added to
// the closure scope they're defined in
return false;
case Syntax.ClassDeclaration:
case Syntax.ClassExpression:
case Syntax.FunctionDeclaration:
if (node.id) {
identifiers[node.id.name] = true;
}
return false;
case Syntax.VariableDeclarator:
if (path[0].kind === 'var') {
identifiers[node.id.name] = true;
}
break;
}
}
function visitLocalBlockIdentifiers(node, path, state) {
// TODO: Support 'let' here...maybe...one day...or something...
if (node.type === Syntax.CatchClause) {
return false;
}
}
function walker(node, path, state) {
var visitors = state.g.visitors;
for (var i = 0; i < visitors.length; i++) {
if (visitors[i].test(node, path, state)) {
return visitors[i](traverse, node, path, state);
}
}
}
/**
* Applies all available transformations to the source
* @param {array} visitors
* @param {string} source
* @param {?object} options
* @return {object}
*/
function transform(visitors, source, options) {
options = options || {};
var ast;
try {
ast = esprima.parse(source, {
comment: true,
loc: true,
range: true
});
} catch (e) {
e.message = 'Parse Error: ' + e.message;
throw e;
}
var state = utils.createState(source, ast, options);
state.g.visitors = visitors;
if (options.sourceMap) {
var SourceMapGenerator = _dereq_('source-map').SourceMapGenerator;
state.g.sourceMap = new SourceMapGenerator({file: 'transformed.js'});
}
traverse(ast, [], state);
utils.catchup(source.length, state);
var ret = {code: state.g.buffer};
if (options.sourceMap) {
ret.sourceMap = state.g.sourceMap;
ret.sourceMapFilename = options.filename || 'source.js';
}
return ret;
}
exports.transform = transform;
},{"./utils":20,"esprima-fb":6,"source-map":8}],20:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node: true*/
/**
* A `state` object represents the state of the parser. It has "local" and
* "global" parts. Global contains parser position, source, etc. Local contains
* scope based properties like current class name. State should contain all the
* info required for transformation. It's the only mandatory object that is
* being passed to every function in transform chain.
*
* @param {string} source
* @param {object} transformOptions
* @return {object}
*/
function createState(source, rootNode, transformOptions) {
return {
/**
* A tree representing the current local scope (and its lexical scope chain)
* Useful for tracking identifiers from parent scopes, etc.
* @type {Object}
*/
localScope: {
parentNode: rootNode,
parentScope: null,
identifiers: {}
},
/**
* The name (and, if applicable, expression) of the super class
* @type {Object}
*/
superClass: null,
/**
* The namespace to use when munging identifiers
* @type {String}
*/
mungeNamespace: '',
/**
* Ref to the node for the FunctionExpression of the enclosing
* MethodDefinition
* @type {Object}
*/
methodFuncNode: null,
/**
* Name of the enclosing class
* @type {String}
*/
className: null,
/**
* Whether we're currently within a `strict` scope
* @type {Bool}
*/
scopeIsStrict: null,
/**
* Global state (not affected by updateState)
* @type {Object}
*/
g: {
/**
* A set of general options that transformations can consider while doing
* a transformation:
*
* - minify
* Specifies that transformation steps should do their best to minify
* the output source when possible. This is useful for places where
* minification optimizations are possible with higher-level context
* info than what jsxmin can provide.
*
* For example, the ES6 class transform will minify munged private
* variables if this flag is set.
*/
opts: transformOptions,
/**
* Current position in the source code
* @type {Number}
*/
position: 0,
/**
* Buffer containing the result
* @type {String}
*/
buffer: '',
/**
* Indentation offset (only negative offset is supported now)
* @type {Number}
*/
indentBy: 0,
/**
* Source that is being transformed
* @type {String}
*/
source: source,
/**
* Cached parsed docblock (see getDocblock)
* @type {object}
*/
docblock: null,
/**
* Whether the thing was used
* @type {Boolean}
*/
tagNamespaceUsed: false,
/**
* If using bolt xjs transformation
* @type {Boolean}
*/
isBolt: undefined,
/**
* Whether to record source map (expensive) or not
* @type {SourceMapGenerator|null}
*/
sourceMap: null,
/**
* Filename of the file being processed. Will be returned as a source
* attribute in the source map
*/
sourceMapFilename: 'source.js',
/**
* Only when source map is used: last line in the source for which
* source map was generated
* @type {Number}
*/
sourceLine: 1,
/**
* Only when source map is used: last line in the buffer for which
* source map was generated
* @type {Number}
*/
bufferLine: 1,
/**
* The top-level Program AST for the original file.
*/
originalProgramAST: null,
sourceColumn: 0,
bufferColumn: 0
}
};
}
/**
* Updates a copy of a given state with "update" and returns an updated state.
*
* @param {object} state
* @param {object} update
* @return {object}
*/
function updateState(state, update) {
var ret = Object.create(state);
Object.keys(update).forEach(function(updatedKey) {
ret[updatedKey] = update[updatedKey];
});
return ret;
}
/**
* Given a state fill the resulting buffer from the original source up to
* the end
*
* @param {number} end
* @param {object} state
* @param {?function} contentTransformer Optional callback to transform newly
* added content.
*/
function catchup(end, state, contentTransformer) {
if (end < state.g.position) {
// cannot move backwards
return;
}
var source = state.g.source.substring(state.g.position, end);
var transformed = updateIndent(source, state);
if (state.g.sourceMap && transformed) {
// record where we are
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
// record line breaks in transformed source
var sourceLines = source.split('\n');
var transformedLines = transformed.split('\n');
// Add line break mappings between last known mapping and the end of the
// added piece. So for the code piece
// (foo, bar);
// > var x = 2;
// > var b = 3;
// var c =
// only add lines marked with ">": 2, 3.
for (var i = 1; i < sourceLines.length - 1; i++) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: 0 },
original: { line: state.g.sourceLine, column: 0 },
source: state.g.sourceMapFilename
});
state.g.sourceLine++;
state.g.bufferLine++;
}
// offset for the last piece
if (sourceLines.length > 1) {
state.g.sourceLine++;
state.g.bufferLine++;
state.g.sourceColumn = 0;
state.g.bufferColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer +=
contentTransformer ? contentTransformer(transformed) : transformed;
state.g.position = end;
}
/**
* Removes all non-whitespace characters
*/
var reNonWhite = /(\S)/g;
function stripNonWhite(value) {
return value.replace(reNonWhite, function() {
return '';
});
}
/**
* Catches up as `catchup` but removes all non-whitespace characters.
*/
function catchupWhiteSpace(end, state) {
catchup(end, state, stripNonWhite);
}
/**
* Removes all non-newline characters
*/
var reNonNewline = /[^\n]/g;
function stripNonNewline(value) {
return value.replace(reNonNewline, function() {
return '';
});
}
/**
* Catches up as `catchup` but removes all non-newline characters.
*
* Equivalent to appending as many newlines as there are in the original source
* between the current position and `end`.
*/
function catchupNewlines(end, state) {
catchup(end, state, stripNonNewline);
}
/**
* Same as catchup but does not touch the buffer
*
* @param {number} end
* @param {object} state
*/
function move(end, state) {
// move the internal cursors
if (state.g.sourceMap) {
if (end < state.g.position) {
state.g.position = 0;
state.g.sourceLine = 1;
state.g.sourceColumn = 0;
}
var source = state.g.source.substring(state.g.position, end);
var sourceLines = source.split('\n');
if (sourceLines.length > 1) {
state.g.sourceLine += sourceLines.length - 1;
state.g.sourceColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
}
state.g.position = end;
}
/**
* Appends a string of text to the buffer
*
* @param {string} str
* @param {object} state
*/
function append(str, state) {
if (state.g.sourceMap && str) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
var transformedLines = str.split('\n');
if (transformedLines.length > 1) {
state.g.bufferLine += transformedLines.length - 1;
state.g.bufferColumn = 0;
}
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer += str;
}
/**
* Update indent using state.indentBy property. Indent is measured in
* double spaces. Updates a single line only.
*
* @param {string} str
* @param {object} state
* @return {string}
*/
function updateIndent(str, state) {
for (var i = 0; i < -state.g.indentBy; i++) {
str = str.replace(/(^|\n)( {2}|\t)/g, '$1');
}
return str;
}
/**
* Calculates indent from the beginning of the line until "start" or the first
* character before start.
* @example
* " foo.bar()"
* ^
* start
* indent will be 2
*
* @param {number} start
* @param {object} state
* @return {number}
*/
function indentBefore(start, state) {
var end = start;
start = start - 1;
while (start > 0 && state.g.source[start] != '\n') {
if (!state.g.source[start].match(/[ \t]/)) {
end = start;
}
start--;
}
return state.g.source.substring(start + 1, end);
}
function getDocblock(state) {
if (!state.g.docblock) {
var docblock = _dereq_('./docblock');
state.g.docblock =
docblock.parseAsObject(docblock.extract(state.g.source));
}
return state.g.docblock;
}
function identWithinLexicalScope(identName, state, stopBeforeNode) {
var currScope = state.localScope;
while (currScope) {
if (currScope.identifiers[identName] !== undefined) {
return true;
}
if (stopBeforeNode && currScope.parentNode === stopBeforeNode) {
break;
}
currScope = currScope.parentScope;
}
return false;
}
function identInLocalScope(identName, state) {
return state.localScope.identifiers[identName] !== undefined;
}
function declareIdentInLocalScope(identName, state) {
state.localScope.identifiers[identName] = true;
}
/**
* Apply the given analyzer function to the current node. If the analyzer
* doesn't return false, traverse each child of the current node using the given
* traverser function.
*
* @param {function} analyzer
* @param {function} traverser
* @param {object} node
* @param {function} visitor
* @param {array} path
* @param {object} state
*/
function analyzeAndTraverse(analyzer, traverser, node, path, state) {
var key, child;
if (node.type) {
if (analyzer(node, path, state) === false) {
return;
}
path.unshift(node);
}
for (key in node) {
// skip obviously wrong attributes
if (key === 'range' || key === 'loc') {
continue;
}
if (node.hasOwnProperty(key)) {
child = node[key];
if (typeof child === 'object' && child !== null) {
traverser(child, path, state);
}
}
}
node.type && path.shift();
}
/**
* Checks whether a node or any of its sub-nodes contains
* a syntactic construct of the passed type.
* @param {object} node - AST node to test.
* @param {string} type - node type to lookup.
*/
function containsChildOfType(node, type) {
var foundMatchingChild = false;
function nodeTypeAnalyzer(node) {
if (node.type === type) {
foundMatchingChild = true;
return false;
}
}
function nodeTypeTraverser(child, path, state) {
if (!foundMatchingChild) {
foundMatchingChild = containsChildOfType(child, type);
}
}
analyzeAndTraverse(
nodeTypeAnalyzer,
nodeTypeTraverser,
node,
[]
);
return foundMatchingChild;
}
exports.append = append;
exports.catchup = catchup;
exports.catchupWhiteSpace = catchupWhiteSpace;
exports.catchupNewlines = catchupNewlines;
exports.containsChildOfType = containsChildOfType;
exports.createState = createState;
exports.declareIdentInLocalScope = declareIdentInLocalScope;
exports.getDocblock = getDocblock;
exports.identWithinLexicalScope = identWithinLexicalScope;
exports.identInLocalScope = identInLocalScope;
exports.indentBefore = indentBefore;
exports.move = move;
exports.updateIndent = updateIndent;
exports.updateState = updateState;
exports.analyzeAndTraverse = analyzeAndTraverse;
},{"./docblock":18}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*global exports:true*/
/**
* Desugars ES6 Arrow functions to ES3 function expressions.
* If the function contains `this` expression -- automatically
* binds the funciton to current value of `this`.
*
* Single parameter, simple expression:
*
* [1, 2, 3].map(x => x * x);
*
* [1, 2, 3].map(function(x) { return x * x; });
*
* Several parameters, complex block:
*
* this.users.forEach((user, idx) => {
* return this.isActive(idx) && this.send(user);
* });
*
* this.users.forEach(function(user, idx) {
* return this.isActive(idx) && this.send(user);
* }.bind(this));
*
*/
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitArrowFunction(traverse, node, path, state) {
// Prologue.
utils.append('function', state);
renderParams(node, state);
// Skip arrow.
utils.catchupWhiteSpace(node.body.range[0], state);
var renderBody = node.body.type == Syntax.BlockStatement
? renderStatementBody
: renderExpressionBody;
path.unshift(node);
renderBody(traverse, node, path, state);
path.shift();
// Bind the function only if `this` value is used
// inside it or inside any sub-expression.
if (utils.containsChildOfType(node.body, Syntax.ThisExpression)) {
utils.append('.bind(this)', state);
}
return false;
}
function renderParams(node, state) {
// To preserve inline typechecking directives, we
// distinguish between parens-free and paranthesized single param.
if (isParensFreeSingleParam(node, state) || !node.params.length) {
utils.append('(', state);
}
if (node.params.length !== 0) {
utils.catchup(node.params[node.params.length - 1].range[1], state);
}
utils.append(')', state);
}
function isParensFreeSingleParam(node, state) {
return node.params.length === 1 &&
state.g.source[state.g.position] !== '(';
}
function renderExpressionBody(traverse, node, path, state) {
// Wrap simple expression bodies into a block
// with explicit return statement.
utils.append('{', state);
if (node.rest) {
utils.append(
restParamVisitors.renderRestParamSetup(node),
state
);
}
utils.append('return ', state);
renderStatementBody(traverse, node, path, state);
utils.append(';}', state);
}
function renderStatementBody(traverse, node, path, state) {
traverse(node.body, path, state);
utils.catchup(node.body.range[1], state);
}
visitArrowFunction.test = function(node, path, state) {
return node.type === Syntax.ArrowFunctionExpression;
};
exports.visitorList = [
visitArrowFunction
];
},{"../src/utils":20,"./es6-rest-param-visitors":24,"esprima-fb":6}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var base62 = _dereq_('base62');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf';
var _anonClassUUIDCounter = 0;
var _mungedSymbolMaps = {};
/**
* Used to generate a unique class for use with code-gens for anonymous class
* expressions.
*
* @param {object} state
* @return {string}
*/
function _generateAnonymousClassName(state) {
var mungeNamespace = state.mungeNamespace || '';
return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++);
}
/**
* Given an identifier name, munge it using the current state's mungeNamespace.
*
* @param {string} identName
* @param {object} state
* @return {string}
*/
function _getMungedName(identName, state) {
var mungeNamespace = state.mungeNamespace;
var shouldMinify = state.g.opts.minify;
if (shouldMinify) {
if (!_mungedSymbolMaps[mungeNamespace]) {
_mungedSymbolMaps[mungeNamespace] = {
symbolMap: {},
identUUIDCounter: 0
};
}
var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap;
if (!symbolMap[identName]) {
symbolMap[identName] =
base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++);
}
identName = symbolMap[identName];
}
return '$' + mungeNamespace + identName;
}
/**
* Extracts super class information from a class node.
*
* Information includes name of the super class and/or the expression string
* (if extending from an expression)
*
* @param {object} node
* @param {object} state
* @return {object}
*/
function _getSuperClassInfo(node, state) {
var ret = {
name: null,
expression: null
};
if (node.superClass) {
if (node.superClass.type === Syntax.Identifier) {
ret.name = node.superClass.name;
} else {
// Extension from an expression
ret.name = _generateAnonymousClassName(state);
ret.expression = state.g.source.substring(
node.superClass.range[0],
node.superClass.range[1]
);
}
}
return ret;
}
/**
* Used with .filter() to find the constructor method in a list of
* MethodDefinition nodes.
*
* @param {object} classElement
* @return {boolean}
*/
function _isConstructorMethod(classElement) {
return classElement.type === Syntax.MethodDefinition &&
classElement.key.type === Syntax.Identifier &&
classElement.key.name === 'constructor';
}
/**
* @param {object} node
* @param {object} state
* @return {boolean}
*/
function _shouldMungeIdentifier(node, state) {
return (
!!state.methodFuncNode &&
!utils.getDocblock(state).hasOwnProperty('preventMunge') &&
/^_(?!_)/.test(node.name)
);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassMethod(traverse, node, path, state) {
utils.catchup(node.range[0], state);
path.unshift(node);
traverse(node.value, path, state);
path.shift();
return false;
}
visitClassMethod.test = function(node, path, state) {
return node.type === Syntax.MethodDefinition;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassFunctionExpression(traverse, node, path, state) {
var methodNode = path[0];
state = utils.updateState(state, {
methodFuncNode: node
});
if (methodNode.key.name === 'constructor') {
utils.append('function ' + state.className, state);
} else {
var methodName = methodNode.key.name;
if (_shouldMungeIdentifier(methodNode.key, state)) {
methodName = _getMungedName(methodName, state);
}
var prototypeOrStatic = methodNode["static"] ? '' : 'prototype.';
utils.append(
state.className + '.' + prototypeOrStatic + methodName + '=function',
state
);
}
utils.move(methodNode.key.range[1], state);
var params = node.params;
var paramName;
if (params.length > 0) {
for (var i = 0; i < params.length; i++) {
utils.catchup(node.params[i].range[0], state);
paramName = params[i].name;
if (_shouldMungeIdentifier(params[i], state)) {
paramName = _getMungedName(params[i].name, state);
}
utils.append(paramName, state);
utils.move(params[i].range[1], state);
}
} else {
utils.append('(', state);
}
utils.append(')', state);
utils.catchupWhiteSpace(node.body.range[0], state);
utils.append('{', state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
}
utils.move(node.body.range[0] + '{'.length, state);
path.unshift(node);
traverse(node.body, path, state);
path.shift();
utils.catchup(node.body.range[1], state);
if (methodNode.key.name !== 'constructor') {
utils.append(';', state);
}
return false;
}
visitClassFunctionExpression.test = function(node, path, state) {
return node.type === Syntax.FunctionExpression
&& path[0].type === Syntax.MethodDefinition;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function _renderClassBody(traverse, node, path, state) {
var className = state.className;
var superClass = state.superClass;
// Set up prototype of constructor on same line as `extends` for line-number
// preservation. This relies on function-hoisting if a constructor function is
// defined in the class body.
if (superClass.name) {
// If the super class is an expression, we need to memoize the output of the
// expression into the generated class name variable and use that to refer
// to the super class going forward. Example:
//
// class Foo extends mixin(Bar, Baz) {}
// --transforms to--
// function Foo() {} var ____Class0Blah = mixin(Bar, Baz);
if (superClass.expression !== null) {
utils.append(
'var ' + superClass.name + '=' + superClass.expression + ';',
state
);
}
var keyName = superClass.name + '____Key';
var keyNameDeclarator = '';
if (!utils.identWithinLexicalScope(keyName, state)) {
keyNameDeclarator = 'var ';
utils.declareIdentInLocalScope(keyName, state);
}
utils.append(
'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' +
'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' +
className + '[' + keyName + ']=' +
superClass.name + '[' + keyName + '];' +
'}' +
'}',
state
);
var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name;
if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) {
utils.append(
'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' +
'null:' + superClass.name + '.prototype;',
state
);
utils.declareIdentInLocalScope(superProtoIdentStr, state);
}
utils.append(
className + '.prototype=Object.create(' + superProtoIdentStr + ');',
state
);
utils.append(
className + '.prototype.constructor=' + className + ';',
state
);
utils.append(
className + '.__superConstructor__=' + superClass.name + ';',
state
);
}
// If there's no constructor method specified in the class body, create an
// empty constructor function at the top (same line as the class keyword)
if (!node.body.body.filter(_isConstructorMethod).pop()) {
utils.append('function ' + className + '(){', state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
}
if (superClass.name) {
utils.append(
'if(' + superClass.name + '!==null){' +
superClass.name + '.apply(this,arguments);}',
state
);
}
utils.append('}', state);
}
utils.move(node.body.range[0] + '{'.length, state);
traverse(node.body, path, state);
utils.catchupWhiteSpace(node.range[1], state);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassDeclaration(traverse, node, path, state) {
var className = node.id.name;
var superClass = _getSuperClassInfo(node, state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
return false;
}
visitClassDeclaration.test = function(node, path, state) {
return node.type === Syntax.ClassDeclaration;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassExpression(traverse, node, path, state) {
var className = node.id && node.id.name || _generateAnonymousClassName(state);
var superClass = _getSuperClassInfo(node, state);
utils.append('(function(){', state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
utils.append('return ' + className + ';})()', state);
return false;
}
visitClassExpression.test = function(node, path, state) {
return node.type === Syntax.ClassExpression;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitPrivateIdentifier(traverse, node, path, state) {
utils.append(_getMungedName(node.name, state), state);
utils.move(node.range[1], state);
}
visitPrivateIdentifier.test = function(node, path, state) {
if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) {
// Always munge non-computed properties of MemberExpressions
// (a la preventing access of properties of unowned objects)
if (path[0].type === Syntax.MemberExpression && path[0].object !== node
&& path[0].computed === false) {
return true;
}
// Always munge identifiers that were declared within the method function
// scope
if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) {
return true;
}
// Always munge private keys on object literals defined within a method's
// scope.
if (path[0].type === Syntax.Property
&& path[1].type === Syntax.ObjectExpression) {
return true;
}
// Always munge function parameters
if (path[0].type === Syntax.FunctionExpression
|| path[0].type === Syntax.FunctionDeclaration) {
for (var i = 0; i < path[0].params.length; i++) {
if (path[0].params[i] === node) {
return true;
}
}
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperCallExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
if (node.callee.type === Syntax.Identifier) {
utils.append(superClassName + '.call(', state);
utils.move(node.callee.range[1], state);
} else if (node.callee.type === Syntax.MemberExpression) {
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.callee.object.range[1], state);
if (node.callee.computed) {
// ["a" + "b"]
utils.catchup(node.callee.property.range[1] + ']'.length, state);
} else {
// .ab
utils.append('.' + node.callee.property.name, state);
}
utils.append('.call(', state);
utils.move(node.callee.range[1], state);
}
utils.append('this', state);
if (node.arguments.length > 0) {
utils.append(',', state);
utils.catchupWhiteSpace(node.arguments[0].range[0], state);
traverse(node.arguments, path, state);
}
utils.catchupWhiteSpace(node.range[1], state);
utils.append(')', state);
return false;
}
visitSuperCallExpression.test = function(node, path, state) {
if (state.superClass && node.type === Syntax.CallExpression) {
var callee = node.callee;
if (callee.type === Syntax.Identifier && callee.name === 'super'
|| callee.type == Syntax.MemberExpression
&& callee.object.name === 'super') {
return true;
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperMemberExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.object.range[1], state);
}
visitSuperMemberExpression.test = function(node, path, state) {
return state.superClass
&& node.type === Syntax.MemberExpression
&& node.object.type === Syntax.Identifier
&& node.object.name === 'super';
};
exports.visitorList = [
visitClassDeclaration,
visitClassExpression,
visitClassFunctionExpression,
visitClassMethod,
visitPrivateIdentifier,
visitSuperCallExpression,
visitSuperMemberExpression
];
},{"../src/utils":20,"base62":7,"esprima-fb":6}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node: true*/
/**
* Desugars ES6 Object Literal short notations into ES3 full notation.
*
* // Easier return values.
* function foo(x, y) {
* return {x, y}; // {x: x, y: y}
* };
*
* // Destrucruting.
* function init({port, ip, coords: {x, y}}) { ... }
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitObjectLiteralShortNotation(traverse, node, path, state) {
utils.catchup(node.key.range[1], state);
utils.append(':' + node.key.name, state);
return false;
}
visitObjectLiteralShortNotation.test = function(node, path, state) {
return node.type === Syntax.Property &&
node.kind === 'init' &&
node.shorthand === true;
};
exports.visitorList = [
visitObjectLiteralShortNotation
];
},{"../src/utils":20,"esprima-fb":6}],24:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node:true*/
/**
* Desugars ES6 rest parameters into ES3 arguments slicing.
*
* function printf(template, ...args) {
* args.forEach(...);
* };
*
* function printf(template) {
* var args = [].slice.call(arguments, 1);
* args.forEach(...);
* };
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function _nodeIsFunctionWithRestParam(node) {
return (node.type === Syntax.FunctionDeclaration
|| node.type === Syntax.FunctionExpression
|| node.type === Syntax.ArrowFunctionExpression)
&& node.rest;
}
function visitFunctionParamsWithRestParam(traverse, node, path, state) {
// Render params.
if (node.params.length) {
utils.catchup(node.params[node.params.length - 1].range[1], state);
} else {
// -3 is for ... of the rest.
utils.catchup(node.rest.range[0] - 3, state);
}
utils.catchupWhiteSpace(node.rest.range[1], state);
}
visitFunctionParamsWithRestParam.test = function(node, path, state) {
return _nodeIsFunctionWithRestParam(node);
};
function renderRestParamSetup(functionNode) {
return 'var ' + functionNode.rest.name + '=Array.prototype.slice.call(' +
'arguments,' +
functionNode.params.length +
');';
}
function visitFunctionBodyWithRestParam(traverse, node, path, state) {
utils.catchup(node.range[0] + 1, state);
var parentNode = path[0];
utils.append(renderRestParamSetup(parentNode), state);
traverse(node.body, path, state);
return false;
}
visitFunctionBodyWithRestParam.test = function(node, path, state) {
return node.type === Syntax.BlockStatement
&& _nodeIsFunctionWithRestParam(path[0]);
};
exports.renderRestParamSetup = renderRestParamSetup;
exports.visitorList = [
visitFunctionParamsWithRestParam,
visitFunctionBodyWithRestParam
];
},{"../src/utils":20,"esprima-fb":6}],25:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9
*/
function visitTemplateLiteral(traverse, node, path, state) {
var templateElements = node.quasis;
utils.append('(', state);
for (var ii = 0; ii < templateElements.length; ii++) {
var templateElement = templateElements[ii];
if (templateElement.value.raw !== '') {
utils.append(getCookedValue(templateElement), state);
if (!templateElement.tail) {
// + between element and substitution
utils.append(' + ', state);
}
// maintain line numbers
utils.move(templateElement.range[0], state);
utils.catchupNewlines(templateElement.range[1], state);
}
utils.move(templateElement.range[1], state);
if (!templateElement.tail) {
var substitution = node.expressions[ii];
if (substitution.type === Syntax.Identifier ||
substitution.type === Syntax.MemberExpression ||
substitution.type === Syntax.CallExpression) {
utils.catchup(substitution.range[1], state);
} else {
utils.append('(', state);
traverse(substitution, path, state);
utils.catchup(substitution.range[1], state);
utils.append(')', state);
}
// if next templateElement isn't empty...
if (templateElements[ii + 1].value.cooked !== '') {
utils.append(' + ', state);
}
}
}
utils.move(node.range[1], state);
utils.append(')', state);
return false;
}
visitTemplateLiteral.test = function(node, path, state) {
return node.type === Syntax.TemplateLiteral;
};
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6
*/
function visitTaggedTemplateExpression(traverse, node, path, state) {
var template = node.quasi;
var numQuasis = template.quasis.length;
// print the tag
utils.move(node.tag.range[0], state);
traverse(node.tag, path, state);
utils.catchup(node.tag.range[1], state);
// print array of template elements
utils.append('(function() { var siteObj = [', state);
for (var ii = 0; ii < numQuasis; ii++) {
utils.append(getCookedValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(']; siteObj.raw = [', state);
for (ii = 0; ii < numQuasis; ii++) {
utils.append(getRawValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(
']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()',
state
);
// print substitutions
if (numQuasis > 1) {
for (ii = 0; ii < template.expressions.length; ii++) {
var expression = template.expressions[ii];
utils.append(', ', state);
// maintain line numbers by calling catchupWhiteSpace over the whole
// previous TemplateElement
utils.move(template.quasis[ii].range[0], state);
utils.catchupNewlines(template.quasis[ii].range[1], state);
utils.move(expression.range[0], state);
traverse(expression, path, state);
utils.catchup(expression.range[1], state);
}
}
// print blank lines to push the closing ) down to account for the final
// TemplateElement.
utils.catchupNewlines(node.range[1], state);
utils.append(')', state);
return false;
}
visitTaggedTemplateExpression.test = function(node, path, state) {
return node.type === Syntax.TaggedTemplateExpression;
};
function getCookedValue(templateElement) {
return JSON.stringify(templateElement.value.cooked);
}
function getRawValue(templateElement) {
return JSON.stringify(templateElement.value.raw);
}
exports.visitorList = [
visitTemplateLiteral,
visitTaggedTemplateExpression
];
},{"../src/utils":20,"esprima-fb":6}],26:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, 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.
*/
/* jshint browser: true */
/* jslint evil: true */
'use strict';
var runScripts;
var headEl;
var buffer = _dereq_('buffer');
var transform = _dereq_('jstransform').transform;
var visitors = _dereq_('./fbtransform/visitors').transformVisitors;
var docblock = _dereq_('jstransform/src/docblock');
// The source-map library relies on Object.defineProperty, but IE8 doesn't
// support it fully even with es5-sham. Indeed, es5-sham's defineProperty
// throws when Object.prototype.__defineGetter__ is missing, so we skip building
// the source map in that case.
var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
function transformReact(source) {
return transform(visitors.react, source, {
sourceMap: supportsAccessors
});
}
exports.transform = transformReact;
exports.exec = function(code) {
return eval(transformReact(code).code);
};
var inlineScriptCount = 0;
// This method returns a nicely formated line of code pointing the
// exactly location of the error `e`.
// The line is limited in size so big lines of code are also shown
// in a readable way.
// Example:
//
// ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ...
// ^
var createSourceCodeErrorMessage = function(code, e) {
var sourceLines = code.split('\n');
var erroneousLine = sourceLines[e.lineNumber - 1];
// Removes any leading indenting spaces and gets the number of
// chars indenting the `erroneousLine`
var indentation = 0;
erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) {
indentation = leadingSpaces.length;
return '';
});
// Defines the number of characters that are going to show
// before and after the erroneous code
var LIMIT = 30;
var errorColumn = e.column - indentation;
if (errorColumn > LIMIT) {
erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT);
errorColumn = 4 + LIMIT;
}
if (erroneousLine.length - errorColumn > LIMIT) {
erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...';
}
var message = '\n\n' + erroneousLine + '\n';
message += new Array(errorColumn - 1).join(' ') + '^';
return message;
};
var transformCode = function(code, source) {
var jsx = docblock.parseAsObject(docblock.extract(code)).jsx;
if (jsx) {
try {
var transformed = transformReact(code);
} catch(e) {
e.message += '\n at ';
if (source) {
if ('fileName' in e) {
// We set `fileName` if it's supported by this error object and
// a `source` was provided.
// The error will correctly point to `source` in Firefox.
e.fileName = source;
}
e.message += source + ':' + e.lineNumber + ':' + e.column;
} else {
e.message += location.href;
}
e.message += createSourceCodeErrorMessage(code, e);
throw e;
}
if (!transformed.sourceMap) {
return transformed.code;
}
var map = transformed.sourceMap.toJSON();
if (source == null) {
source = "Inline JSX script";
inlineScriptCount++;
if (inlineScriptCount > 1) {
source += ' (' + inlineScriptCount + ')';
}
}
map.sources = [source];
map.sourcesContent = [code];
return (
transformed.code +
'//# sourceMappingURL=data:application/json;base64,' +
buffer.Buffer(JSON.stringify(map)).toString('base64')
);
} else {
return code;
}
};
var run = exports.run = function(code, source) {
var scriptEl = document.createElement('script');
scriptEl.text = transformCode(code, source);
headEl.appendChild(scriptEl);
};
var load = exports.load = function(url, callback) {
var xhr;
xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP')
: new XMLHttpRequest();
// Disable async since we need to execute scripts in the order they are in the
// DOM to mirror normal script loading.
xhr.open('GET', url, false);
if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0 || xhr.status === 200) {
run(xhr.responseText, url);
} else {
throw new Error("Could not load " + url);
}
if (callback) {
return callback();
}
}
};
return xhr.send(null);
};
runScripts = function() {
var scripts = document.getElementsByTagName('script');
// Array.prototype.slice cannot be used on NodeList on IE8
var jsxScripts = [];
for (var i = 0; i < scripts.length; i++) {
if (scripts.item(i).type === 'text/jsx') {
jsxScripts.push(scripts.item(i));
}
}
console.warn("You are using the in-browser JSX transformer. Be sure to precompile your JSX for production - http://facebook.github.io/react/docs/tooling-integration.html#jsx");
jsxScripts.forEach(function(script) {
if (script.src) {
load(script.src);
} else {
run(script.innerHTML, null);
}
});
};
if (typeof window !== "undefined" && window !== null) {
headEl = document.getElementsByTagName('head')[0];
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', runScripts, false);
} else {
window.attachEvent('onload', runScripts);
}
}
},{"./fbtransform/visitors":30,"buffer":1,"jstransform":19,"jstransform/src/docblock":18}],27:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, 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.
*/
/*global exports:true*/
"use strict";
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('jstransform/src/utils');
var FALLBACK_TAGS = _dereq_('./xjs').knownTags;
var renderXJSExpressionContainer =
_dereq_('./xjs').renderXJSExpressionContainer;
var renderXJSLiteral = _dereq_('./xjs').renderXJSLiteral;
var quoteAttrName = _dereq_('./xjs').quoteAttrName;
/**
* Customized desugar processor.
*
* Currently: (Somewhat tailored to React)
* <X> </X> => X(null, null)
* <X prop="1" /> => X({prop: '1'}, null)
* <X prop="2"><Y /></X> => X({prop:'2'}, Y(null, null))
* <X prop="2"><Y /><Z /></X> => X({prop:'2'}, [Y(null, null), Z(null, null)])
*
* Exceptions to the simple rules above:
* if a property is named "class" it will be changed to "className" in the
* javascript since "class" is not a valid object key in javascript.
*/
var JSX_ATTRIBUTE_TRANSFORMS = {
cxName: function(attr) {
throw new Error(
"cxName is no longer supported, use className={cx(...)} instead"
);
}
};
function visitReactTag(traverse, object, path, state) {
var jsxObjIdent = utils.getDocblock(state).jsx;
var openingElement = object.openingElement;
var nameObject = openingElement.name;
var attributesObject = openingElement.attributes;
utils.catchup(openingElement.range[0], state);
if (nameObject.namespace) {
throw new Error(
'Namespace tags are not supported. ReactJSX is not XML.');
}
var isFallbackTag = FALLBACK_TAGS.hasOwnProperty(nameObject.name);
utils.append(
(isFallbackTag ? jsxObjIdent + '.' : '') + (nameObject.name) + '(',
state
);
utils.move(nameObject.range[1], state);
// if we don't have any attributes, pass in null
if (attributesObject.length === 0) {
utils.append('null', state);
}
// write attributes
attributesObject.forEach(function(attr, index) {
utils.catchup(attr.range[0], state);
if (attr.name.namespace) {
throw new Error(
'Namespace attributes are not supported. ReactJSX is not XML.');
}
var name = attr.name.name;
var isFirst = index === 0;
var isLast = index === attributesObject.length - 1;
if (isFirst) {
utils.append('{', state);
}
utils.append(quoteAttrName(name), state);
utils.append(':', state);
if (!attr.value) {
state.g.buffer += 'true';
state.g.position = attr.name.range[1];
if (!isLast) {
utils.append(',', state);
}
} else {
utils.move(attr.name.range[1], state);
// Use catchupWhiteSpace to skip over the '=' in the attribute
utils.catchupWhiteSpace(attr.value.range[0], state);
if (JSX_ATTRIBUTE_TRANSFORMS.hasOwnProperty(attr.name.name)) {
utils.append(JSX_ATTRIBUTE_TRANSFORMS[attr.name.name](attr), state);
utils.move(attr.value.range[1], state);
if (!isLast) {
utils.append(',', state);
}
} else if (attr.value.type === Syntax.Literal) {
renderXJSLiteral(attr.value, isLast, state);
} else {
renderXJSExpressionContainer(traverse, attr.value, isLast, path, state);
}
}
if (isLast) {
utils.append('}', state);
}
utils.catchup(attr.range[1], state);
});
if (!openingElement.selfClosing) {
utils.catchup(openingElement.range[1] - 1, state);
utils.move(openingElement.range[1], state);
}
// filter out whitespace
var childrenToRender = object.children.filter(function(child) {
return !(child.type === Syntax.Literal
&& typeof child.value === 'string'
&& child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/));
});
if (childrenToRender.length > 0) {
var lastRenderableIndex;
childrenToRender.forEach(function(child, index) {
if (child.type !== Syntax.XJSExpressionContainer ||
child.expression.type !== Syntax.XJSEmptyExpression) {
lastRenderableIndex = index;
}
});
if (lastRenderableIndex !== undefined) {
utils.append(', ', state);
}
childrenToRender.forEach(function(child, index) {
utils.catchup(child.range[0], state);
var isLast = index >= lastRenderableIndex;
if (child.type === Syntax.Literal) {
renderXJSLiteral(child, isLast, state);
} else if (child.type === Syntax.XJSExpressionContainer) {
renderXJSExpressionContainer(traverse, child, isLast, path, state);
} else {
traverse(child, path, state);
if (!isLast) {
utils.append(',', state);
state.g.buffer = state.g.buffer.replace(/(\s*),$/, ',$1');
}
}
utils.catchup(child.range[1], state);
});
}
if (openingElement.selfClosing) {
// everything up to />
utils.catchup(openingElement.range[1] - 2, state);
utils.move(openingElement.range[1], state);
} else {
// everything up to </ sdflksjfd>
utils.catchup(object.closingElement.range[0], state);
utils.move(object.closingElement.range[1], state);
}
utils.append(')', state);
return false;
}
visitReactTag.test = function(object, path, state) {
// only run react when react @jsx namespace is specified in docblock
var jsx = utils.getDocblock(state).jsx;
return object.type === Syntax.XJSElement && jsx && jsx.length;
};
exports.visitorList = [
visitReactTag
];
},{"./xjs":29,"esprima-fb":6,"jstransform/src/utils":20}],28:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, 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.
*/
/*global exports:true*/
"use strict";
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('jstransform/src/utils');
function addDisplayName(displayName, object, state) {
if (object &&
object.type === Syntax.CallExpression &&
object.callee.type === Syntax.MemberExpression &&
object.callee.object.type === Syntax.Identifier &&
object.callee.object.name === 'React' &&
object.callee.property.type === Syntax.Identifier &&
object.callee.property.name === 'createClass' &&
object['arguments'].length === 1 &&
object['arguments'][0].type === Syntax.ObjectExpression) {
// Verify that the displayName property isn't already set
var properties = object['arguments'][0].properties;
var safe = properties.every(function(property) {
var value = property.key.type === Syntax.Identifier ?
property.key.name :
property.key.value;
return value !== 'displayName';
});
if (safe) {
utils.catchup(object['arguments'][0].range[0] + 1, state);
utils.append("displayName: '" + displayName + "',", state);
}
}
}
/**
* Transforms the following:
*
* var MyComponent = React.createClass({
* render: ...
* });
*
* into:
*
* var MyComponent = React.createClass({
* displayName: 'MyComponent',
* render: ...
* });
*
* Also catches:
*
* MyComponent = React.createClass(...);
* exports.MyComponent = React.createClass(...);
* module.exports = {MyComponent: React.createClass(...)};
*/
function visitReactDisplayName(traverse, object, path, state) {
var left, right;
if (object.type === Syntax.AssignmentExpression) {
left = object.left;
right = object.right;
} else if (object.type === Syntax.Property) {
left = object.key;
right = object.value;
} else if (object.type === Syntax.VariableDeclarator) {
left = object.id;
right = object.init;
}
if (left && left.type === Syntax.MemberExpression) {
left = left.property;
}
if (left && left.type === Syntax.Identifier) {
addDisplayName(left.name, right, state);
}
}
/**
* Will only run on @jsx files for now.
*/
visitReactDisplayName.test = function(object, path, state) {
if (utils.getDocblock(state).jsx) {
return (
object.type === Syntax.AssignmentExpression ||
object.type === Syntax.Property ||
object.type === Syntax.VariableDeclarator
);
} else {
return false;
}
};
exports.visitorList = [
visitReactDisplayName
];
},{"esprima-fb":6,"jstransform/src/utils":20}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, 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.
*/
/*global exports:true*/
"use strict";
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('jstransform/src/utils');
var knownTags = {
a: true,
abbr: true,
address: true,
applet: true,
area: true,
article: true,
aside: true,
audio: true,
b: true,
base: true,
bdi: true,
bdo: true,
big: true,
blockquote: true,
body: true,
br: true,
button: true,
canvas: true,
caption: true,
circle: true,
cite: true,
code: true,
col: true,
colgroup: true,
command: true,
data: true,
datalist: true,
dd: true,
defs: true,
del: true,
details: true,
dfn: true,
dialog: true,
div: true,
dl: true,
dt: true,
ellipse: true,
em: true,
embed: true,
fieldset: true,
figcaption: true,
figure: true,
footer: true,
form: true,
g: true,
h1: true,
h2: true,
h3: true,
h4: true,
h5: true,
h6: true,
head: true,
header: true,
hgroup: true,
hr: true,
html: true,
i: true,
iframe: true,
img: true,
input: true,
ins: true,
kbd: true,
keygen: true,
label: true,
legend: true,
li: true,
line: true,
linearGradient: true,
link: true,
main: true,
map: true,
mark: true,
marquee: true,
menu: true,
menuitem: true,
meta: true,
meter: true,
nav: true,
noscript: true,
object: true,
ol: true,
optgroup: true,
option: true,
output: true,
p: true,
param: true,
path: true,
polygon: true,
polyline: true,
pre: true,
progress: true,
q: true,
radialGradient: true,
rect: true,
rp: true,
rt: true,
ruby: true,
s: true,
samp: true,
script: true,
section: true,
select: true,
small: true,
source: true,
span: true,
stop: true,
strong: true,
style: true,
sub: true,
summary: true,
sup: true,
svg: true,
table: true,
tbody: true,
td: true,
text: true,
textarea: true,
tfoot: true,
th: true,
thead: true,
time: true,
title: true,
tr: true,
track: true,
u: true,
ul: true,
'var': true,
video: true,
wbr: true
};
function renderXJSLiteral(object, isLast, state, start, end) {
var lines = object.value.split(/\r\n|\n|\r/);
if (start) {
utils.append(start, state);
}
var lastNonEmptyLine = 0;
lines.forEach(function (line, index) {
if (line.match(/[^ \t]/)) {
lastNonEmptyLine = index;
}
});
lines.forEach(function (line, index) {
var isFirstLine = index === 0;
var isLastLine = index === lines.length - 1;
var isLastNonEmptyLine = index === lastNonEmptyLine;
// replace rendered whitespace tabs with spaces
var trimmedLine = line.replace(/\t/g, ' ');
// trim whitespace touching a newline
if (!isFirstLine) {
trimmedLine = trimmedLine.replace(/^[ ]+/, '');
}
if (!isLastLine) {
trimmedLine = trimmedLine.replace(/[ ]+$/, '');
}
utils.append(line.match(/^[ \t]*/)[0], state);
if (trimmedLine || isLastNonEmptyLine) {
utils.append(
JSON.stringify(trimmedLine) +
(!isLastNonEmptyLine ? "+' '+" : ''),
state);
if (isLastNonEmptyLine) {
if (end) {
utils.append(end, state);
}
if (!isLast) {
utils.append(',', state);
}
}
// only restore tail whitespace if line had literals
if (trimmedLine) {
utils.append(line.match(/[ \t]*$/)[0], state);
}
}
if (!isLastLine) {
utils.append('\n', state);
}
});
utils.move(object.range[1], state);
}
function renderXJSExpressionContainer(traverse, object, isLast, path, state) {
// Plus 1 to skip `{`.
utils.move(object.range[0] + 1, state);
traverse(object.expression, path, state);
if (!isLast && object.expression.type !== Syntax.XJSEmptyExpression) {
// If we need to append a comma, make sure to do so after the expression.
utils.catchup(object.expression.range[1], state);
utils.append(',', state);
}
// Minus 1 to skip `}`.
utils.catchup(object.range[1] - 1, state);
utils.move(object.range[1], state);
return false;
}
function quoteAttrName(attr) {
// Quote invalid JS identifiers.
if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) {
return "'" + attr + "'";
}
return attr;
}
exports.knownTags = knownTags;
exports.renderXJSExpressionContainer = renderXJSExpressionContainer;
exports.renderXJSLiteral = renderXJSLiteral;
exports.quoteAttrName = quoteAttrName;
},{"esprima-fb":6,"jstransform/src/utils":20}],30:[function(_dereq_,module,exports){
/*global exports:true*/
var es6ArrowFunctions = _dereq_('jstransform/visitors/es6-arrow-function-visitors');
var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors');
var es6ObjectShortNotation = _dereq_('jstransform/visitors/es6-object-short-notation-visitors');
var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors');
var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors');
var react = _dereq_('./transforms/react');
var reactDisplayName = _dereq_('./transforms/reactDisplayName');
/**
* Map from transformName => orderedListOfVisitors.
*/
var transformVisitors = {
'es6-arrow-functions': es6ArrowFunctions.visitorList,
'es6-classes': es6Classes.visitorList,
'es6-object-short-notation': es6ObjectShortNotation.visitorList,
'es6-rest-params': es6RestParameters.visitorList,
'es6-templates': es6Templates.visitorList,
'react': react.visitorList.concat(reactDisplayName.visitorList)
};
/**
* Specifies the order in which each transform should run.
*/
var transformRunOrder = [
'es6-arrow-functions',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'react'
];
/**
* Given a list of transform names, return the ordered list of visitors to be
* passed to the transform() function.
*
* @param {array?} excludes
* @return {array}
*/
function getAllVisitors(excludes) {
var ret = [];
for (var i = 0, il = transformRunOrder.length; i < il; i++) {
if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) {
ret = ret.concat(transformVisitors[transformRunOrder[i]]);
}
}
return ret;
}
exports.getAllVisitors = getAllVisitors;
exports.transformVisitors = transformVisitors;
},{"./transforms/react":27,"./transforms/reactDisplayName":28,"jstransform/visitors/es6-arrow-function-visitors":21,"jstransform/visitors/es6-class-visitors":22,"jstransform/visitors/es6-object-short-notation-visitors":23,"jstransform/visitors/es6-rest-param-visitors":24,"jstransform/visitors/es6-template-visitors":25}]},{},[26])
(26)
}); |
src/containers/EventListContainer.js | chrisfitkin/cf-event-planner-3 | import { connect } from 'react-redux'
import { toggleEvent } from '../actions'
import EventList from '../components/EventList'
const getVisibleEvents = (events, filter) => {
events.sort(function(a, b){
return b.id-a.id
})
switch (filter) {
case 'SHOW_ALL':
return events
case 'SHOW_FAVORITE':
return events.filter(t => t.favorite)
default:
// throw new Error('Unknown filter: ' + filter)
console.log('Unknown filter: ' + filter)
return events
}
}
const mapStateToProps = (state) => {
// console.log("------------")
// console.log(state)
return ({
events: getVisibleEvents(state.events, state.visibilityFilter)
})
}
const mapDispatchToProps = ({
onEventClick: toggleEvent
})
const EventListContainer = connect(
mapStateToProps,
mapDispatchToProps
)(EventList)
export default EventListContainer
|
app/components/admin/step5/before.js | 7hci/surfboard | import React from 'react';
import { Page, InputGroupCheckbox } from '../../shared/index';
const Step5Before = (props) => {
const { tasks, spinner, handleClickSkip, handleClickStart } = props;
return (
<Page
model="form.onboarding"
content={
<div className="card-block">
{tasks.map(task => <InputGroupCheckbox model={`form.onboarding.${task.name}`} label={task.text} />)}
</div>
}
buttons={
<div>
<button className="btn btn-secondary" type="button" onClick={handleClickSkip}>Skip</button>
<button className="btn btn-success" type="button" onClick={handleClickStart}>Start</button>
</div>
}
header="Onboarding Tasks"
spinner={spinner}
/>
);
};
export default Step5Before;
|
ajax/libs/primereact/7.0.0/selectbutton/selectbutton.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames, ObjectUtils } from 'primereact/utils';
import { Ripple } from 'primereact/ripple';
import { tip } from 'primereact/tooltip';
function _arrayLikeToArray$1(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray$1(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var SelectButtonItem = /*#__PURE__*/function (_Component) {
_inherits(SelectButtonItem, _Component);
var _super = _createSuper$1(SelectButtonItem);
function SelectButtonItem(props) {
var _this;
_classCallCheck(this, SelectButtonItem);
_this = _super.call(this, props);
_this.state = {
focused: false
};
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this));
_this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this));
_this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(SelectButtonItem, [{
key: "onClick",
value: function onClick(event) {
if (this.props.onClick) {
this.props.onClick({
originalEvent: event,
option: this.props.option
});
}
}
}, {
key: "onFocus",
value: function onFocus() {
this.setState({
focused: true
});
}
}, {
key: "onBlur",
value: function onBlur() {
this.setState({
focused: false
});
}
}, {
key: "onKeyDown",
value: function onKeyDown(event) {
var keyCode = event.which;
if (keyCode === 32 || keyCode === 13) {
//space and enter
this.onClick(event);
event.preventDefault();
}
}
}, {
key: "renderContent",
value: function renderContent() {
if (this.props.template) {
return this.props.template(this.props.option);
} else {
return /*#__PURE__*/React.createElement("span", {
className: "p-button-label p-c"
}, this.props.label);
}
}
}, {
key: "render",
value: function render() {
var className = classNames('p-button p-component', {
'p-highlight': this.props.selected,
'p-disabled': this.props.disabled,
'p-focus': this.state.focused
}, this.props.className);
var content = this.renderContent();
return /*#__PURE__*/React.createElement("div", {
className: className,
role: "button",
"aria-label": this.props.label,
"aria-pressed": this.props.selected,
"aria-labelledby": this.props.ariaLabelledBy,
onClick: this.onClick,
onKeyDown: this.onKeyDown,
tabIndex: this.props.tabIndex,
onFocus: this.onFocus,
onBlur: this.onBlur
}, content, !this.props.disabled && /*#__PURE__*/React.createElement(Ripple, null));
}
}]);
return SelectButtonItem;
}(Component);
_defineProperty(SelectButtonItem, "defaultProps", {
option: null,
label: null,
className: null,
selected: null,
tabIndex: null,
ariaLabelledBy: null,
template: null,
onClick: null
});
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var SelectButton = /*#__PURE__*/function (_Component) {
_inherits(SelectButton, _Component);
var _super = _createSuper(SelectButton);
function SelectButton(props) {
var _this;
_classCallCheck(this, SelectButton);
_this = _super.call(this, props);
_this.onOptionClick = _this.onOptionClick.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(SelectButton, [{
key: "onOptionClick",
value: function onOptionClick(event) {
var _this2 = this;
if (this.props.disabled || this.isOptionDisabled(event.option)) {
return;
}
var selected = this.isSelected(event.option);
if (selected && !this.props.unselectable) {
return;
}
var optionValue = this.getOptionValue(event.option);
var newValue;
if (this.props.multiple) {
var currentValue = this.props.value ? _toConsumableArray(this.props.value) : [];
if (selected) newValue = currentValue.filter(function (val) {
return !ObjectUtils.equals(val, optionValue, _this2.props.dataKey);
});else newValue = [].concat(_toConsumableArray(currentValue), [optionValue]);
} else {
if (selected) newValue = null;else newValue = optionValue;
}
if (this.props.onChange) {
this.props.onChange({
originalEvent: event.originalEvent,
value: newValue,
stopPropagation: function stopPropagation() {},
preventDefault: function preventDefault() {},
target: {
name: this.props.name,
id: this.props.id,
value: newValue
}
});
}
}
}, {
key: "getOptionLabel",
value: function getOptionLabel(option) {
return this.props.optionLabel ? ObjectUtils.resolveFieldData(option, this.props.optionLabel) : option && option['label'] !== undefined ? option['label'] : option;
}
}, {
key: "getOptionValue",
value: function getOptionValue(option) {
return this.props.optionValue ? ObjectUtils.resolveFieldData(option, this.props.optionValue) : option && option['value'] !== undefined ? option['value'] : option;
}
}, {
key: "isOptionDisabled",
value: function isOptionDisabled(option) {
if (this.props.optionDisabled) {
return ObjectUtils.isFunction(this.props.optionDisabled) ? this.props.optionDisabled(option) : ObjectUtils.resolveFieldData(option, this.props.optionDisabled);
}
return option && option['disabled'] !== undefined ? option['disabled'] : false;
}
}, {
key: "isSelected",
value: function isSelected(option) {
var selected = false;
var optionValue = this.getOptionValue(option);
if (this.props.multiple) {
if (this.props.value && this.props.value.length) {
var _iterator = _createForOfIteratorHelper(this.props.value),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var val = _step.value;
if (ObjectUtils.equals(val, optionValue, this.props.dataKey)) {
selected = true;
break;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
} else {
selected = ObjectUtils.equals(this.props.value, optionValue, this.props.dataKey);
}
return selected;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.props.tooltip) {
this.renderTooltip();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) {
if (this.tooltip) this.tooltip.update(_objectSpread({
content: this.props.tooltip
}, this.props.tooltipOptions || {}));else this.renderTooltip();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.tooltip) {
this.tooltip.destroy();
this.tooltip = null;
}
}
}, {
key: "renderTooltip",
value: function renderTooltip() {
this.tooltip = tip({
target: this.element,
content: this.props.tooltip,
options: this.props.tooltipOptions
});
}
}, {
key: "renderItems",
value: function renderItems() {
var _this3 = this;
if (this.props.options && this.props.options.length) {
return this.props.options.map(function (option, index) {
var isDisabled = _this3.props.disabled || _this3.isOptionDisabled(option);
var optionLabel = _this3.getOptionLabel(option);
var tabIndex = isDisabled ? null : 0;
return /*#__PURE__*/React.createElement(SelectButtonItem, {
key: "".concat(optionLabel, "_").concat(index),
label: optionLabel,
className: option.className,
option: option,
onClick: _this3.onOptionClick,
template: _this3.props.itemTemplate,
selected: _this3.isSelected(option),
tabIndex: tabIndex,
disabled: isDisabled,
ariaLabelledBy: _this3.props.ariaLabelledBy
});
});
}
return null;
}
}, {
key: "render",
value: function render() {
var _this4 = this;
var className = classNames('p-selectbutton p-buttonset p-component', this.props.className);
var items = this.renderItems();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
ref: function ref(el) {
return _this4.element = el;
},
className: className,
style: this.props.style,
role: "group"
}, items);
}
}]);
return SelectButton;
}(Component);
_defineProperty(SelectButton, "defaultProps", {
id: null,
value: null,
options: null,
optionLabel: null,
optionValue: null,
optionDisabled: null,
tabIndex: null,
multiple: false,
unselectable: true,
disabled: false,
style: null,
className: null,
dataKey: null,
tooltip: null,
tooltipOptions: null,
ariaLabelledBy: null,
itemTemplate: null,
onChange: null
});
export { SelectButton };
|
nailgun/static/views/controls.js | huntxu/fuel-web | /*
* Copyright 2014 Mirantis, 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.
**/
/*
* Copyright (с) 2014 Stephen J. Collings, Matthew Honnibal, Pieter Vanderwerff
*
* Based on https://github.com/react-bootstrap/react-bootstrap/blob/master/src/Input.jsx
**/
import $ from 'jquery';
import _ from 'underscore';
import i18n from 'i18n';
import React from 'react';
import ReactDOM from 'react-dom';
import utils from 'utils';
import {outerClickMixin} from 'component_mixins';
export var Input = React.createClass({
propTypes: {
type: React.PropTypes.oneOf(['text', 'password', 'textarea', 'checkbox', 'radio', 'select', 'hidden', 'number', 'range', 'file']).isRequired,
name: React.PropTypes.node,
label: React.PropTypes.node,
debounce: React.PropTypes.bool,
description: React.PropTypes.node,
disabled: React.PropTypes.bool,
inputClassName: React.PropTypes.node,
wrapperClassName: React.PropTypes.node,
tooltipPlacement: React.PropTypes.oneOf(['left', 'right', 'top', 'bottom']),
tooltipIcon: React.PropTypes.node,
tooltipText: React.PropTypes.node,
toggleable: React.PropTypes.bool,
onChange: React.PropTypes.func,
extraContent: React.PropTypes.node
},
getInitialState() {
return {
visible: false,
fileName: this.props.defaultValue && this.props.defaultValue.name || null,
content: this.props.defaultValue && this.props.defaultValue.content || null
};
},
getDefaultProps() {
return {
tooltipIcon: 'glyphicon-warning-sign',
tooltipPlacement: 'right'
};
},
togglePassword() {
this.setState({visible: !this.state.visible});
},
isCheckboxOrRadio() {
return this.props.type == 'radio' || this.props.type == 'checkbox';
},
getInputDOMNode() {
return ReactDOM.findDOMNode(this.refs.input);
},
debouncedChange: _.debounce(function() {
return this.onChange();
}, 200, {leading: true}),
pickFile() {
if (!this.props.disabled) {
this.getInputDOMNode().click();
}
},
saveFile(fileName, content) {
this.setState({
fileName: fileName,
content: content
});
return this.props.onChange(
this.props.name,
{name: fileName, content: content}
);
},
removeFile() {
if (!this.props.disabled) {
ReactDOM.findDOMNode(this.refs.form).reset();
this.saveFile(null, null);
}
},
readFile() {
var reader = new FileReader();
var input = this.getInputDOMNode();
if (input.files.length) {
reader.onload = () => this.saveFile(input.value.replace(/^.*[\\\/]/g, ''), reader.result);
reader.readAsBinaryString(input.files[0]);
}
},
onChange() {
if (this.props.onChange) {
var input = this.getInputDOMNode();
return this.props.onChange(
this.props.name,
this.props.type == 'checkbox' ? input.checked : input.value
);
}
},
handleFocus(e) {
e.target.select();
},
renderInput() {
var classes = {'form-control': this.props.type != 'range'};
classes[this.props.inputClassName] = this.props.inputClassName;
var props = {
ref: 'input',
key: 'input',
onFocus: this.props.selectOnFocus && this.handleFocus,
type: (this.props.toggleable && this.state.visible) ? 'text' : this.props.type,
className: utils.classNames(classes)
};
if (this.props.type == 'file') {
props.onChange = this.readFile;
} else {
props.onChange = this.props.debounce ? this.debouncedChange : this.onChange;
}
var Tag = _.contains(['select', 'textarea'], this.props.type) ? this.props.type : 'input';
var input = <Tag {...this.props} {...props}>{this.props.children}</Tag>;
var isCheckboxOrRadio = this.isCheckboxOrRadio();
var inputWrapperClasses = {
'input-group': this.props.toggleable,
'custom-tumbler': isCheckboxOrRadio,
textarea: this.props.type == 'textarea'
};
if (this.props.type == 'file') {
input = <form ref='form'>{input}</form>;
}
return (
<div key='input-group' className={utils.classNames(inputWrapperClasses)}>
{input}
{this.props.type == 'file' &&
<div className='input-group'>
<input
className='form-control file-name'
type='text'
placeholder={i18n('file.placeholder')}
value={this.state.fileName && '[' + utils.showSize(this.state.content.length) + '] ' + this.state.fileName}
onClick={this.pickFile}
disabled={this.props.disabled}
readOnly
/>
<div className='input-group-addon' onClick={this.state.fileName ? this.removeFile : this.pickFile}>
<i className={this.state.fileName && !this.props.disabled ? 'glyphicon glyphicon-remove' : 'glyphicon glyphicon-file'} />
</div>
</div>
}
{this.props.toggleable &&
<div className='input-group-addon' onClick={this.togglePassword}>
<i className={this.state.visible ? 'glyphicon glyphicon-eye-close' : 'glyphicon glyphicon-eye-open'} />
</div>
}
{isCheckboxOrRadio && <span> </span>}
{this.props.extraContent}
</div>
);
},
renderLabel(children) {
if (!this.props.label && !children) return null;
return (
<label key='label' htmlFor={this.props.id}>
{children}
{this.props.label}
{this.props.tooltipText &&
<Tooltip text={this.props.tooltipText} placement={this.props.tooltipPlacement}>
<i className={utils.classNames('glyphicon tooltip-icon', this.props.tooltipIcon)} />
</Tooltip>
}
</label>
);
},
renderDescription() {
var text = !_.isUndefined(this.props.error) && !_.isNull(this.props.error) ? this.props.error : this.props.description || '';
return <span key='description' className='help-block'>{text}</span>;
},
renderWrapper(children) {
var isCheckboxOrRadio = this.isCheckboxOrRadio();
var classes = {
'form-group': !isCheckboxOrRadio,
'checkbox-group': isCheckboxOrRadio,
'has-error': !_.isUndefined(this.props.error) && !_.isNull(this.props.error),
disabled: this.props.disabled
};
classes[this.props.wrapperClassName] = this.props.wrapperClassName;
return (<div className={utils.classNames(classes)}>{children}</div>);
},
render() {
if (this.props.type == 'hidden' && !this.props.description && !this.props.label) return null;
return this.renderWrapper(this.isCheckboxOrRadio() ?
[
this.renderLabel(this.renderInput()),
this.renderDescription()
] : [
this.renderLabel(),
this.renderInput(),
this.renderDescription()
]
);
}
});
export var RadioGroup = React.createClass({
propTypes: {
name: React.PropTypes.string,
values: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
label: React.PropTypes.node,
tooltipText: React.PropTypes.node
},
render() {
return (
<div className='radio-group'>
{this.props.label &&
<h4>
{this.props.label}
{this.props.tooltipText &&
<Tooltip text={this.props.tooltipText} placement='right'>
<i className='glyphicon glyphicon-warning-sign tooltip-icon' />
</Tooltip>
}
</h4>
}
{_.map(this.props.values, (value) => {
return <Input
{...this.props}
{...value}
type='radio'
key={value.data}
value={value.data}
/>;
})}
</div>
);
}
});
export var ProgressBar = React.createClass({
propTypes: {
wrapperClassName: React.PropTypes.node,
progress: React.PropTypes.number
},
render() {
var wrapperClasses = {
progress: true
};
wrapperClasses[this.props.wrapperClassName] = this.props.wrapperClassName;
var isInfinite = !_.isNumber(this.props.progress);
var progressClasses = {
'progress-bar': true,
'progress-bar-striped active': isInfinite
};
return (
<div className={utils.classNames(wrapperClasses)}>
<div
className={utils.classNames(progressClasses)}
role='progressbar'
style={{width: isInfinite ? '100%' : _.max([this.props.progress, 3]) + '%'}}
>
{!isInfinite && this.props.progress + '%'}
</div>
</div>
);
}
});
export var Table = React.createClass({
propTypes: {
tableClassName: React.PropTypes.node,
head: React.PropTypes.array,
body: React.PropTypes.array
},
render() {
var tableClasses = {'table table-bordered': true, 'table-striped': !this.props.noStripes};
tableClasses[this.props.tableClassName] = this.props.tableClassName;
return (
<table className={utils.classNames(tableClasses)}>
<thead>
<tr>
{_.map(this.props.head, (column, index) => {
var classes = {};
classes[column.className] = column.className;
return <th key={index} className={utils.classNames(classes)}>{column.label}</th>;
})}
</tr>
</thead>
<tbody>
{_.map(this.props.body, (row, rowIndex) => {
return <tr key={rowIndex}>
{_.map(row, (column, columnIndex) => {
return <td key={columnIndex} className='enable-selection'>{column}</td>;
})}
</tr>;
})}
</tbody>
</table>
);
}
});
export var Popover = React.createClass({
mixins: [outerClickMixin],
propTypes: {
className: React.PropTypes.node,
placement: React.PropTypes.node
},
getDefaultProps() {
return {placement: 'bottom'};
},
render() {
var classes = {'popover in': true};
classes[this.props.placement] = true;
classes[this.props.className] = true;
return (
<div className={utils.classNames(classes)}>
<div className='arrow' />
<div className='popover-content'>{this.props.children}</div>
</div>
);
}
});
export var Tooltip = React.createClass({
propTypes: {
container: React.PropTypes.node,
placement: React.PropTypes.node,
text: React.PropTypes.node
},
getDefaultProps() {
return {
placement: 'top',
container: 'body',
wrapperClassName: 'tooltip-wrapper'
};
},
componentDidMount() {
if (this.props.text) this.addTooltip();
},
componentDidUpdate() {
if (this.props.text) {
this.updateTooltipTitle();
} else {
this.removeTooltip();
}
},
componentWillUnmount() {
this.removeTooltip();
},
addTooltip() {
$(ReactDOM.findDOMNode(this.refs.tooltip)).tooltip({
container: this.props.container,
placement: this.props.placement,
title: this.props.text
});
},
updateTooltipTitle() {
$(ReactDOM.findDOMNode(this.refs.tooltip)).attr('title', this.props.text).tooltip('fixTitle');
},
removeTooltip() {
$(ReactDOM.findDOMNode(this.refs.tooltip)).tooltip('destroy');
},
render() {
if (!this.props.wrap) return React.cloneElement(React.Children.only(this.props.children), {ref: 'tooltip'});
return (
<div className={this.props.wrapperClassName} ref='tooltip'>
{this.props.children}
</div>
);
}
});
|
src/components/views/settings/ChangeDisplayName.js | aperezdc/matrix-react-sdk | /*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2018 New Vector Ltd
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.
*/
import React from 'react';
import sdk from '../../../index';
import MatrixClientPeg from '../../../MatrixClientPeg';
import { _t } from '../../../languageHandler';
module.exports = React.createClass({
displayName: 'ChangeDisplayName',
_getDisplayName: async function() {
const cli = MatrixClientPeg.get();
try {
const res = await cli.getProfileInfo(cli.getUserId());
return res.displayname;
} catch (e) {
throw new Error("Failed to fetch display name");
}
},
_changeDisplayName: function(newDisplayname) {
const cli = MatrixClientPeg.get();
return cli.setDisplayName(newDisplayname).catch(function(e) {
throw new Error("Failed to set display name", e);
});
},
render: function() {
const EditableTextContainer = sdk.getComponent('elements.EditableTextContainer');
return (
<EditableTextContainer
getInitialValue={this._getDisplayName}
placeholder={_t("No display name")}
blurToSubmit={true}
onSubmit={this._changeDisplayName} />
);
},
});
|
test/CollapsibleNavSpec.js | adampickeral/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Navbar from '../src/Navbar';
import CollapsibleNav from '../src/CollapsibleNav';
import Nav from '../src/Nav';
import NavItem from '../src/NavItem';
describe('CollapsibleNav', function () {
it('Should create div and add collapse class', function () {
let Parent = React.createClass({
render() {
return (
<Navbar toggleNavKey={1}>
<CollapsibleNav eventKey={1}>
<Nav>
<NavItem eventKey={1} ref='item1'>Item 1 content</NavItem>
<NavItem eventKey={2} ref='item2'>Item 2 content</NavItem>
</Nav>
</CollapsibleNav>
</Navbar>
);
}
});
let instance = ReactTestUtils.renderIntoDocument(<Parent />);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-collapse'));
});
it('Should handle multiple Nav elements', function () {
let Parent = React.createClass({
render() {
return (
<Navbar toggleNavKey={1}>
<CollapsibleNav eventKey={1} ref='collapsible_object'>
<Nav>
<NavItem eventKey={1} ref='item1'>Item 1 content</NavItem>
<NavItem eventKey={2} ref='item2'>Item 2 content</NavItem>
</Nav>
<Nav>
<NavItem eventKey={1} ref='item1'>Item 1 content</NavItem>
<NavItem eventKey={2} ref='item2'>Item 2 content</NavItem>
</Nav>
</CollapsibleNav>
</Navbar>
);
}
});
let instance = ReactTestUtils.renderIntoDocument(<Parent />);
assert.ok(ReactTestUtils.findRenderedComponentWithType(instance.refs.collapsible_object.refs.collapsible_0, Nav));
assert.ok(ReactTestUtils.findRenderedComponentWithType(instance.refs.collapsible_object.refs.collapsible_1, Nav));
});
it('Should just render children and move along if not in <Navbar>', function () {
let Parent = React.createClass({
render() {
return (
<CollapsibleNav eventKey={1}>
<Nav>
<NavItem eventKey={1} ref='item1'>Item 1 content</NavItem>
<NavItem eventKey={2} ref='item2'>Item 2 content</NavItem>
</Nav>
</CollapsibleNav>
);
}
});
let instance = ReactTestUtils.renderIntoDocument(<Parent />);
let collapsibleNav = ReactTestUtils.findRenderedComponentWithType(instance, CollapsibleNav);
assert.notOk(React.findDOMNode(collapsibleNav).className.match(/\navbar-collapse\b/));
let nav = ReactTestUtils.findRenderedComponentWithType(collapsibleNav.refs.nocollapse_0, Nav);
assert.ok(nav);
});
it('Should retain childrens classes set by className', function () {
let Parent = React.createClass({
render() {
return (
<Navbar toggleNavKey={1}>
<CollapsibleNav eventKey={1} ref='collapsible_object'>
<Nav>
<NavItem eventKey={1} ref='item1' className='foo bar'>Item 1 content</NavItem>
<NavItem eventKey={2} ref='item2' className='baz'>Item 2 content</NavItem>
</Nav>
</CollapsibleNav>
</Navbar>
);
}
});
let instance = ReactTestUtils.renderIntoDocument(<Parent />);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.collapsible_object.refs.collapsible_0, 'foo'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.collapsible_object.refs.collapsible_0, 'bar'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.collapsible_object.refs.collapsible_0, 'baz'));
});
});
|
src/Slider/testkit/Slider.js | skyiea/wix-style-react | import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils';
import $ from 'jquery';
import Slider from '../Slider';
const sliderDriverFactory = component => {
const $component = $(component);
const $sliderHandles = $(component).find('.slider-handle');
const $sliderDots = $(component).find('.rc-slider-dot');
return {
exists: () => !!component,
isDotSelected: index => $sliderDots.filter(`:nth-child(${index})`).hasClass('rc-slider-dot-active'),
numOfSliderDots: () => $sliderDots.length,
numOfSLiderHandles: () => $sliderHandles.length,
getToolTipValue: () => {
const tooltip = $component.find('.slider-tooltip')[0];
return tooltip && tooltip.innerHTML;
},
hoverHandle: ({handleIndex}) => {
const handle = $sliderHandles[handleIndex];
ReactTestUtils.Simulate.mouseEnter(handle);
},
unHoverHandle: ({handleIndex}) => {
const handle = $sliderHandles[handleIndex];
ReactTestUtils.Simulate.mouseLeave(handle);
}
};
};
const componentFactory = (props = {}) => {
let component;
const wrapper = document.createElement('div');
ReactDOM.render(<div ref={r => component = r}><Slider onChange={() => {}} {...props}/></div>, wrapper);
return component.childNodes[0];
};
const sliderTestkitFactory = ({component}) => {
return sliderDriverFactory(component);
};
export {componentFactory, sliderDriverFactory, sliderTestkitFactory};
|
frontend/app_v2/src/common/icons/UnfoldMore.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
/**
* @summary UnfoldMore
* @component
*
* @param {object} props
*
* @returns {node} jsx markup
*/
function UnfoldMore({ styling }) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" className={styling}>
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M12 5.83L15.17 9l1.41-1.41L12 3 7.41 7.59 8.83 9 12 5.83zm0 12.34L8.83 15l-1.41 1.41L12 21l4.59-4.59L15.17 15 12 18.17z" />
</svg>
)
}
// PROPTYPES
const { string } = PropTypes
UnfoldMore.propTypes = {
styling: string,
}
export default UnfoldMore
|
curator-web/src/js/components/common/filmBubble.js | rajeshnaroth/curator | import React from 'react'
import { Link } from 'react-router'
import Title from './title'
import Ratings from './ratings'
import Views from './views'
import Description from './description'
import { getVideoDetails } from '../../actions'
const FilmBubble = React.createClass({
componentWillMount: function() {
//this.props.getVideoDetails(this.props.videoId)
console.log("filmBubble.js: componentWillMount ");
},
componentWillUpdate: function(nextProps, nextState) { // prepare for an upcoming update
if (nextProps.filmBubble.videoId) {
// console.log("filmBubble.js: componentWillUpdate 2 getVideoDetails", nextProps);
this.props.getVideoDetails(nextProps.filmBubble.videoId)
}
},
componentWillReceiveProps(nextProps) {
// console.log("filmBubble.js: componentWillReceiveProps ", nextProps);
},
render() {
// console.log("filmBubble.js render: ", this.props);
let iStyle = { visibility:this.props.filmBubble.visibility }
return (
<div className="filmBubble" style={iStyle}>
<div className="videoDetailOverlay"></div>
<div className="bubbleDetails">
<figure><img src={'https://i.ytimg.com/vi/' + this.props.filmDetails.id + '/hqdefault.jpg'}/></figure>
<Title text={this.props.filmDetails.title} />
<Ratings value={this.props.filmDetails.rating} />
<Views value={this.props.filmDetails.views} />
<Description text={this.props.filmDetails.description} />
</div>
</div>
)
}
})
export default FilmBubble |
api/index.js | IniZio/USTFetch | import React from 'react'
import { AsyncStorage } from 'react-native'
import io from 'socket.io-client'
const SERVER_URL = 'http://192.168.31.144'
// const SERVER_URL = 'http://10.89.80.125'
// const SERVER_URL = 'http://10.89.151.157'
export const SOCKET_URL = `${SERVER_URL}:8081`
const API_URL = `${SERVER_URL}:8080`
const jsonHeader = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
// Login
export function loginUser (form) {
return fetch(`${API_URL}/login`, {
method: 'POST',
headers: { ...jsonHeader },
body: JSON.stringify(form)
})
.then(response => response.json())
.catch(err => console.error(err))
}
export async function logoutUser () {
return AsyncStorage.removeItem('Authorization')
.catch(err => console.error(err))
}
export function registerUser (form) {
return fetch(`${API_URL}/user`, {
method: 'POST',
headers: { ...jsonHeader },
body: JSON.stringify(form)
})
.then(response => response.json())
.catch(err => console.error(err))
}
export async function fetchUserProfile (itsc) {
let token = await AsyncStorage.getItem('Authorization')
return fetch(`${API_URL}/user/${itsc}`, {
headers: { Authorization: token }
})
.then(response => response.json())
.catch(err => console.error(err))
}
// Task
export async function fetchTasks ({page, status, rfid, keyword}) {
let token = await AsyncStorage.getItem('Authorization')
console.log()
return fetch(`${API_URL}/task?` + (page ? `page=${page}&` : '') + (status ? `status=${status}&` : '') + (rfid ? `rfid=${rfid}&` : '') + (keyword ? `keyword=${keyword}&` : ''), {
headers: { Authorization: token, ...jsonHeader }
})
.then(response => response.json())
.catch(err => console.error(err))
}
export async function fetchTaskByID (taskID) {
let token = await AsyncStorage.getItem('Authorization')
return fetch(`${API_URL}/task/${taskID}`, {
headers: { Authorization: token, ...jsonHeader }
})
.then(response => response.json())
.catch(err => console.error(err))
}
export async function fetchChats () {
let token = await AsyncStorage.getItem('Authorization')
let itsc = await AsyncStorage.getItem('itsc')
return fetch(`${API_URL}/task?rfid=${itsc}&nstatus=COMPLETED`, {
headers: { Authorization: token, ...jsonHeader }
})
.then(response => response.json())
.catch(err => console.error(err))
}
export async function createTask (task) {
let token = await AsyncStorage.getItem('Authorization')
return fetch(`${API_URL}/task`, {
method: 'POST',
headers: { Authorization: token, ...jsonHeader },
body: JSON.stringify(task)
})
.then(response => response.json())
.catch(err => console.error(err))
}
export async function updateTask (task, change) {
let token = await AsyncStorage.getItem('Authorization')
return fetch(`${API_URL}/task/${task._id}`, {
method: 'PUT',
headers: { Authorization: token, ...jsonHeader },
body: JSON.stringify(change)
})
.then(response => console.log(response))
.catch(err => console.error(err))
}
|
src/components/about.js | jorgerobles/LaserWeb4 | /**
* About module.
* @module
*/
// React
import React from 'react'
import { ButtonToolbar, Button } from 'react-bootstrap'
import Icon from './font-awesome'
/**
* About component.
*
* @extends module:react~React~Component
* @param {Object} props Component properties.
*/
class About extends React.Component {
/**
* Render the component.
* @return {String}
*/
render() {
return (
<div>
<h3>Support Communities</h3>
<dl>
<dt><Icon name="users"/> <a href="https://github.com/LaserWeb">LaserWeb Github Organisation</a></dt>
<dd><small>- developer community</small></dd><p/>
<dt><Icon name="users"/> <a href="https://plus.google.com/communities/115879488566665599508">LaserWeb G+ Community</a></dt>
<dd><small>- support Community for this software itself</small></dd><p/>
<dt><Icon name="users"/> <a href="https://plus.google.com/communities/118113483589382049502">K40 Laser G+ Community</a></dt>
<dd><small>- support community for popular K40 CO2 Lasers</small></dd><p/>
<dt><Icon name="users"/> <a href="https://plus.google.com/communities/109476961016291692936">Eleksmaker G+ Community</a></dt>
<dd><small>- support community for chinese diode engravers</small></dd><p/>
</dl>
<h3>Developers</h3>
<dl>
<dt><Icon name="user"/> <a href="https://plus.google.com/101442607030198502072">Todd Fleming</a> <a target="_blank" href="https://paypal.me/tbfleming"><Icon name="paypal"/></a></dt>
<dd><small>- G-Code Generation, 3D viewer, Simulator</small></dd><p/>
<dt><Icon name="user"/> <a href="https://plus.google.com/+S%C3%A9bastienMischler-Skarab">Sebastien Mischler</a> <a target="_blank" href="https://paypal.me/skarab"><Icon name="paypal"/></a></dt>
<dd><small>- Backend + Dev environment</small></dd><p/>
<dt><Icon name="user"/> <a href="https://plus.google.com/113562432484049167641">Jorge Robles</a> <a target="_blank" href="https://paypal.me/JorgeDiegoRobles"><Icon name="paypal"/></a></dt>
<dd><small>- Settings modules, UI tweaks, Workspace Export</small></dd><p/>
<dt><Icon name="user"/> <a href="https://plus.google.com/+ClaudioPrezzi">Claudio Prezzi</a> <a target="_blank" href="https://paypal.me/cprezzi"><Icon name="paypal"/></a></dt>
<dd><small>- Communications</small></dd><p/>
<dt><Icon name="user"/> <a href="https://plus.google.com/+PetervanderWalt">Peter van der Walt</a> <a target="_blank" href="https://paypal.me/openhardwarecoza"><Icon name="paypal"/></a></dt>
<dd><small>- Support + User Interface</small></dd><p/>
</dl>
<div><i>LaserWeb and CNCWeb is <kbd>free software</kbd>. The team of developers have spent countless hours coding, testing and supporting this application. If you enjoy using this application, consider donating a coffee or a beer towards the developers to show your appreciation, by clicking the <Icon name="paypal"/> icon next to the developers you want to support</i></div>
</div>
)
}
}
// Exports
export default About
|
src/CollapsibleMixin.js | Cellule/react-bootstrap | import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
const CollapsibleMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState(){
let defaultExpanded = this.props.defaultExpanded != null ?
this.props.defaultExpanded :
this.props.expanded != null ?
this.props.expanded :
false;
return {
expanded: defaultExpanded,
collapsing: false
};
},
componentWillUpdate(nextProps, nextState){
let willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded;
if (willExpanded === this.isExpanded()) {
return;
}
// if the expanded state is being toggled, ensure node has a dimension value
// this is needed for the animation to work and needs to be set before
// the collapsing class is applied (after collapsing is applied the in class
// is removed and the node's dimension will be wrong)
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = '0';
if(!willExpanded){
value = this.getCollapsibleDimensionValue();
}
node.style[dimension] = value + 'px';
this._afterWillUpdate();
},
componentDidUpdate(prevProps, prevState){
// check if expanded is being toggled; if so, set collapsing
this._checkToggleCollapsing(prevProps, prevState);
// check if collapsing was turned on; if so, start animation
this._checkStartAnimation();
},
// helps enable test stubs
_afterWillUpdate(){
},
_checkStartAnimation(){
if(!this.state.collapsing) {
return;
}
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = this.getCollapsibleDimensionValue();
// setting the dimension here starts the transition animation
let result;
if(this.isExpanded()) {
result = value + 'px';
} else {
result = '0px';
}
node.style[dimension] = result;
},
_checkToggleCollapsing(prevProps, prevState){
let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded;
let isExpanded = this.isExpanded();
if(wasExpanded !== isExpanded){
if(wasExpanded) {
this._handleCollapse();
} else {
this._handleExpand();
}
}
},
_handleExpand(){
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let complete = () => {
this._removeEndEventListener(node, complete);
// remove dimension value - this ensures the collapsible item can grow
// in dimension after initial display (such as an image loading)
node.style[dimension] = '';
this.setState({
collapsing:false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
_handleCollapse(){
let node = this.getCollapsibleDOMNode();
let complete = () => {
this._removeEndEventListener(node, complete);
this.setState({
collapsing: false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
// helps enable test stubs
_addEndEventListener(node, complete){
TransitionEvents.addEndEventListener(node, complete);
},
// helps enable test stubs
_removeEndEventListener(node, complete){
TransitionEvents.removeEndEventListener(node, complete);
},
dimension(){
return (typeof this.getCollapsibleDimension === 'function') ?
this.getCollapsibleDimension() :
'height';
},
isExpanded(){
return this.props.expanded != null ? this.props.expanded : this.state.expanded;
},
getCollapsibleClassSet(className) {
let classes = {};
if (typeof className === 'string') {
className.split(' ').forEach(subClasses => {
if (subClasses) {
classes[subClasses] = true;
}
});
}
classes.collapsing = this.state.collapsing;
classes.collapse = !this.state.collapsing;
classes.in = this.isExpanded() && !this.state.collapsing;
return classes;
}
};
export default CollapsibleMixin;
|
packages/material-ui-icons/src/PowerOffSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M18 14.49V9c0-1.1-.9-2-2-2V3h-2v4h-3.88l7.69 7.69.19-.2zM10 3H8v1.88l2 2zM4.12 3.84L2.71 5.25l3.34 3.34c-.03.13-.05.27-.05.4v5.51L9.5 18v3h5v-3l.48-.48 4.47 4.47 1.41-1.41L4.12 3.84z" /></g></React.Fragment>
, 'PowerOffSharp');
|
Pillion_nik/Pillion_files/jquery.min.js | nikz99/sample | /*! jQuery v1.7.2 jquery.com | jquery.org/license */
(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+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(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},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(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(
a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.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(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.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(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.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|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={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,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f
.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[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","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); |
app/components/PocketOverview.js | thirdicrypto/darkwallet-electron-ui | import React, { Component } from 'react';
import SendFormSimple from './SendFormSimple';
import StealthAddress from './StealthAddress';
import PendingPayments from './PendingPayments';
export default class PocketOverview extends Component {
render() {
return (
<div className="columns">
<SendFormSimple />
<PendingPayments />
<StealthAddress />
</div>
);
}
}
|
template/app/components/clicker/index.js | andreasrs/roc-base-web-react | import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { click } from '../../redux/clicker';
import styles from './style.scss';
function mapStateToProps(state) {
return {
clicker: state.clicker
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ click }, dispatch);
}
@connect(mapStateToProps, mapDispatchToProps)
export default class Clicker extends React.Component {
static propTypes = {
clicker: React.PropTypes.number.isRequired,
click: React.PropTypes.func.isRequired
};
render() {
return (
<div className={styles.main}>
<span className={styles.clicker}>{ this.props.clicker } +</span>
<input className={styles.input} ref='incInput' type='text' defaultValue="1" />
<button onClick={ () => {
const inputValue = this.refs.incInput.value.trim();
this.props.click(parseInt(inputValue));
} }>
Modify counter!
</button>
</div>
);
}
}
|
frontend/src/screens/selection-viewer/selection-viewer.js | linea-it/qlf | import React from 'react';
import Paper from '@material-ui/core/Paper';
import { withStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import Petals from '../../components/petals/petals';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormLabel from '@material-ui/core/FormLabel';
import { FadeLoader } from 'halogenium';
import Button from '@material-ui/core/Button';
import PNGViewer from './png-viewer/png-viewer';
import LogViewer from './log-viewer/log-viewer';
import GlobalViewer from './global-viewer/global-viewer';
import SpectraViewer from './spectra-viewer/spectra-viewer';
const styles = {
controlsContainer: {
display: 'grid',
alignItems: 'center',
width: '12vw',
justifyContent: 'space-evenly',
borderRight: '1px solid darkgrey',
overflowY: 'auto',
paddingRight: '10px',
boxSizing: 'border-box',
},
column: {
display: 'flex',
flexDirection: 'column',
},
gridRow: {
display: 'grid',
gridTemplateColumns: '12vw calc(100vw - 64px - 12vw)',
width: 'calc(100vw - 64px)',
height: 'calc(100vh - 135px)',
},
viewer: {
width: 'calc(100vw - 64px - 12vw)',
},
fadeLoaderFull: {
position: 'absolute',
paddingLeft: 'calc((100vw - 40px) / 2)',
paddingTop: 'calc(25vh)',
},
fadeLoader: {
position: 'absolute',
paddingLeft: 'calc((100vw - 300px) / 2)',
paddingTop: 'calc(25vh)',
},
selection: {
textAlign: 'center',
},
buttons: {
display: 'grid',
width: '10vw',
},
button: {
float: 'right',
fontSize: '1.2vw',
margin: '10px 0',
},
buttonGreen: {
backgroundColor: 'green',
color: 'white',
},
spectrographLabel: {
paddingBottom: 10,
},
main: {
margin: '16px',
padding: '16px',
height: 'calc(100vh - 135px)',
},
title: {
fontSize: '1.2vw',
},
text: {
fontSize: '1.1vw',
marginLeft: '0.5vw',
},
lineH: {
height: '4.87vh',
marginLeft: 0,
},
wh: {
width: '1.7vw',
height: '3.5vh',
},
};
class SelectionViewer extends React.Component {
constructor(props) {
super(props);
this.state = {
selectArm: '',
selectProcessing: '',
selectSpectrograph: [],
arm: '',
spectrograph: [],
processing: '',
loading: false,
preview: false,
};
}
static propTypes = {
classes: PropTypes.object,
spectrograph: PropTypes.bool,
armAll: PropTypes.bool,
arm: PropTypes.bool,
processing: PropTypes.bool,
};
handleChangeSpectrograph = spectrograph => {
this.setState({
spectrograph: [spectrograph],
preview: false,
loading: false,
});
};
handleChangeArm = evt => {
this.setState({ arm: evt.target.value, preview: false, loading: false });
};
handleChangeProcessing = evt => {
this.setState({
processing: evt.target.value,
preview: false,
loading: false,
});
};
loadStart = () => {
this.setState({ loading: true });
};
loadEnd = () => {
this.setState({ loading: false });
};
renderLoading = () => {
if (!this.state.loading) return null;
const showControls =
this.props.arm || this.props.spectrograph || this.props.processing;
const classLoading = showControls
? styles.fadeLoader
: styles.fadeLoaderFull;
return (
<div className={this.props.classes.loading}>
<FadeLoader
style={classLoading}
color="#424242"
size="16px"
margin="4px"
/>
</div>
);
};
handleSubmit = () => {
this.setState({
selectProcessing: this.state.processing,
selectSpectrograph: this.state.spectrograph,
selectArm: this.state.arm,
preview: true,
});
this.loadStart();
};
clearSelection = () => {
this.setState({
selectArm: '',
selectProcessing: '',
selectSpectrograph: [],
processing: '',
spectrograph: [],
arm: '',
loading: false,
});
};
renderSpectrographSelection = () => {
const { classes } = this.props;
if (this.props.spectrograph)
return (
<div>
<FormLabel
className={this.props.classes.spectrographLabel}
component="legend"
classes={{ root: classes.title }}
>
Spectrograph:
</FormLabel>
<Petals
selected={this.state.spectrograph}
onClick={this.handleChangeSpectrograph}
size={22}
/>
</div>
);
};
renderArmSelection = () => {
const { classes } = this.props;
if (this.props.arm)
return (
<div className={this.props.classes.selection}>
<FormLabel component="legend" classes={{ root: classes.title }}>
Arm:
</FormLabel>
<div className={this.props.classes.row}>
<RadioGroup
className={this.props.classes.column}
value={this.state.arm}
onChange={this.handleChangeArm}
>
{this.props.armAll ? (
<FormControlLabel
value="all"
control={<Radio classes={{ root: classes.wh }} />}
label="All"
classes={{ label: classes.text, root: classes.lineH }}
/>
) : null}
<FormControlLabel
value="b"
control={<Radio classes={{ root: classes.wh }} />}
label="b"
classes={{ label: classes.text, root: classes.lineH }}
/>
<FormControlLabel
value="r"
control={<Radio classes={{ root: classes.wh }} />}
label="r"
classes={{ label: classes.text, root: classes.lineH }}
/>
<FormControlLabel
value="z"
control={<Radio classes={{ root: classes.wh }} />}
label="z"
classes={{ label: classes.text, root: classes.lineH }}
/>
</RadioGroup>
</div>
</div>
);
};
renderProcessingSelection = () => {
const { classes } = this.props;
if (this.props.processing)
return (
<div className={this.props.classes.selection}>
<FormLabel component="legend" classes={{ root: classes.title }}>
Processing:
</FormLabel>
<RadioGroup
value={this.state.processing}
onChange={this.handleChangeProcessing}
>
<FormControlLabel
value="raw"
control={<Radio classes={{ root: classes.wh }} />}
label="raw"
classes={{ label: classes.text, root: classes.lineH }}
/>
<FormControlLabel
value="reduced"
control={<Radio classes={{ root: classes.wh }} />}
label="reduced"
classes={{ label: classes.text, root: classes.lineH }}
/>
</RadioGroup>
</div>
);
};
renderControls = () => {
const { classes } = this.props;
if (this.props.arm || this.props.spectrograph || this.props.processing)
return (
<div className={classes.controlsContainer}>
{this.renderSpectrographSelection()}
{this.renderArmSelection()}
{this.renderProcessingSelection()}
<div className={classes.buttons}>
{this.renderSubmit()}
{this.renderClear()}
</div>
</div>
);
};
renderClear = () => (
<Button
onClick={this.clearSelection}
variant="raised"
size="small"
className={this.props.classes.button}
>
Clear
</Button>
);
renderSubmit = () => (
<Button
onClick={this.handleSubmit}
variant="raised"
size="small"
className={this.props.classes.button}
classes={{ raised: this.props.classes.buttonGreen }}
disabled={!this.isValid()}
>
Submit
</Button>
);
isValid = () => {
let valid = true;
if (this.props.arm) {
valid = this.state.arm !== '';
}
if (this.props.spectrograph) {
valid = valid && this.state.spectrograph.length !== 0;
}
if (this.props.processing) {
valid = valid && this.state.processing !== '';
}
return valid;
};
renderViewer = () => {
if (!this.state.preview) return;
switch (window.location.pathname) {
case '/ccd-viewer':
return (
<PNGViewer
processing={this.state.selectProcessing}
arm={this.state.selectArm}
spectrograph={this.state.selectSpectrograph}
loadEnd={this.loadEnd}
/>
);
case '/log-viewer':
return (
<LogViewer
arm={this.state.selectArm}
spectrograph={this.state.selectSpectrograph}
loadEnd={this.loadEnd}
loadStart={this.loadStart}
/>
);
case '/fiber-viewer':
return (
<GlobalViewer
screen={'globalfiber'}
loadEnd={this.loadEnd}
loadStart={this.loadStart}
arm={this.state.selectArm}
/>
);
case '/focus-viewer':
return (
<GlobalViewer
screen={'globalfocus'}
loadEnd={this.loadEnd}
loadStart={this.loadStart}
arm={this.state.selectArm}
/>
);
case '/snr-viewer':
return (
<GlobalViewer
screen={'globalsnr'}
loadEnd={this.loadEnd}
loadStart={this.loadStart}
arm={this.state.selectArm}
/>
);
case '/spectra-viewer':
return (
<SpectraViewer
loadEnd={this.loadEnd}
loadStart={this.loadStart}
arm={this.state.selectArm}
/>
);
default:
return null;
}
};
render() {
const { classes } = this.props;
const showControls =
this.props.arm || this.props.spectrograph || this.props.processing;
return (
<Paper elevation={4} className={classes.main}>
<div className={showControls ? classes.gridRow : null}>
{this.renderControls()}
<div className={showControls ? classes.viewer : null}>
{this.renderLoading()}
{this.renderViewer()}
</div>
</div>
</Paper>
);
}
}
export default withStyles(styles)(SelectionViewer);
|
docs/pages/components/image-list.js | lgollut/material-ui | import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'components/image-list';
const requireDemo = require.context('docs/src/pages/components/image-list', false, /\.(js|tsx)$/);
const requireRaw = require.context(
'!raw-loader!../../src/pages/components/image-list',
false,
/\.(js|md|tsx)$/,
);
export default function Page({ demos, docs }) {
return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
frontend/src/DiscoverMovie/DiscoverMovieFooterLabel.js | Radarr/Radarr | import PropTypes from 'prop-types';
import React from 'react';
import SpinnerIcon from 'Components/SpinnerIcon';
import { icons } from 'Helpers/Props';
import styles from './DiscoverMovieFooterLabel.css';
function DiscoverMovieFooterLabel(props) {
const {
className,
label,
isSaving
} = props;
return (
<div className={className}>
{label}
{
isSaving &&
<SpinnerIcon
className={styles.savingIcon}
name={icons.SPINNER}
isSpinning={true}
/>
}
</div>
);
}
DiscoverMovieFooterLabel.propTypes = {
className: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
isSaving: PropTypes.bool.isRequired
};
DiscoverMovieFooterLabel.defaultProps = {
className: styles.label
};
export default DiscoverMovieFooterLabel;
|
ui/kirk/src/Dashboard/index.js | socx/Kirk | import React from 'react'
const Dashboard = (props) => (
<div>
<h1>Dashboard</h1>
<p>{console.log(props)}</p>
</div>
)
export default Dashboard |
example/src/screens/Actions.js | luggit/react-native-navigation | import React from 'react';
import {StyleSheet, ScrollView} from 'react-native';
import Row from '../components/Row';
class Actions extends React.Component {
constructor(props) {
super(props);
this._fab = false;
this._rightButton = null;
this._contextualMenu = false;
this._toggleTabs = 'shown';
this._toggleNavBar = 'shown';
this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
}
onNavigatorEvent(event) {
if (event.id === 'contextualMenuDismissed') {
this._contextualMenu = false;
}
}
setTitle = () => {
this.props.navigator.setTitle({
title: 'New Title!',
});
};
toggleTabs = () => {
const to = this._toggleTabs === 'shown' ? 'hidden' : 'shown';
this.props.navigator.toggleTabs({
to,
animated: true,
});
this._toggleTabs = to;
};
setTabBadge = () => {
this.props.navigator.setTabBadge({
tabIndex: 1,
badge: Math.floor(Math.random() * 20) + 1,
});
};
switchToTab = () => {
this.props.navigator.switchToTab({
tabIndex: 0,
});
};
toggleNavBar = () => {
const to = this._toggleNavBar === 'shown' ? 'hidden' : 'shown';
this.props.navigator.toggleNavBar({
to,
animated: true,
});
this._toggleNavBar = to;
};
showSnackbar = () => {
this.props.navigator.showSnackbar({
title: 'Woo Snacks!',
});
};
toggleContextualMenu = () => {
if (!this._contextualMenu) {
this.props.navigator.showContextualMenu({
rightButtons: [{
title: 'Edit',
icon: require('../../img/edit.png'),
}, {
title: 'Delete',
icon: require('../../img/delete.png'),
}],
onButtonPressed: (index) => console.log(`Button ${index} tapped`)
});
this._contextualMenu = true;
} else {
this.props.navigator.dismissContextualMenu();
this._contextualMenu = false;
}
};
setButtons = () => {
let title = '';
if (!this._rightButton) {
title = 'Hello';
} else if (this._rightButton === 'Hello') {
title = 'Its Me';
}
this.props.navigator.setButtons({
rightButtons: [{
title,
id: 'topRight',
}],
animated: true,
});
this._rightButton = title;
};
toggleFAB = () => {
if (this._fab) {
this.props.navigator.setButtons({
fab: {},
});
this._fab = false;
} else {
this.props.navigator.setButtons({
fab: {
collapsedId: 'share',
collapsedIcon: require('../../img/edit@1x.png'),
expendedId: 'clear',
expendedIcon: require('../../img/edit@1x.png'),
backgroundColor: '#ff505c',
actions: [
{
id: 'mail',
icon: require('../../img/edit@1x.png'),
backgroundColor: '#03A9F4'
},
{
id: 'delete',
icon: require('../../img/delete@1x.png'),
backgroundColor: '#4CAF50'
}
]
},
animated: true,
});
this._fab = true;
}
};
render() {
return (
<ScrollView style={styles.container}>
<Row title={'Set Title'} onPress={this.setTitle}/>
<Row title={'Toggle Tabs'} onPress={this.toggleTabs}/>
<Row title={'Set Tab Badge'} onPress={this.setTabBadge}/>
<Row title={'Switch To Tab 0'} onPress={this.switchToTab}/>
<Row title={'Toggle Nav Bar'} onPress={this.toggleNavBar}/>
<Row title={'Show Snackbar'} onPress={this.showSnackbar} platform={'android'}/>
<Row title={'Toggle Contextual Menu'} onPress={this.toggleContextualMenu} platform={'android'}/>
<Row title={'Set Right Buttons'} onPress={this.setButtons}/>
<Row title={'Toggle FAB'} onPress={this.toggleFAB} platform={'android'}/>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {},
});
export default Actions;
|
definitions/npm/expo-camera_v4.x.x/flow_v0.104.x-/test_expo-camera.js | splodingsocks/FlowTyped | // @flow
import React from 'react';
import { it, describe } from 'flow-typed-test';
import { Camera, Constants } from 'expo-camera';
describe('opaque props', () => {
it('should passes when used properly', () => {
<Camera
type={Constants.Type.front}
flashMode={Constants.FlashMode.off}
autoFocus={Constants.AutoFocus.on}
whiteBalance={Constants.WhiteBalance.incandescent}
videoStabilizationMode={Constants.VideoStabilization.cinematic}
/>;
});
it('should raises an error when pass not supported type', () => {
<Camera
// $FlowExpectedError
type={0}
// $FlowExpectedError
flashMode={0}
// $FlowExpectedError
autoFocus={0}
// $FlowExpectedError
whiteBalance={0}
// $FlowExpectedError
videoStabilizationMode={0}
/>;
});
});
describe('primitive props', () => {
it('should passes when used properly', () => {
<Camera
useCamera2Api={false}
ratio={'str'}
zoom={1}
focusDepth={1}
pictureSize={'str'}
/>;
});
it('should raises an error when passed incompatible types', () => {
<Camera
// $FlowExpectedError
useCamera2Api={'need boolean'}
// $FlowExpectedError: need string
ratio={1}
// $FlowExpectedError
zoom={'need number'}
// $FlowExpectedError
focusDepth={'need number'}
// $FlowExpectedError: need string
pictureSize={1}
/>;
});
});
describe('other props', () => {
it('should passes when used properly', () => {
<Camera
children={[<div />]}
onCameraReady={async () => {}}
onMountError={async ({ message }) => {
(message: string);
// $FlowExpectedError: check any
(message: boolean);
}}
onBarCodeScanned={async ({ data, type }) => {
(data: string);
(type: string);
// $FlowExpectedError: check any
(type: boolean);
// $FlowExpectedError: check any
(data: boolean);
}}
onFacesDetected={async ({ faces }) => {
(faces: Array<mixed>);
// $FlowExpectedError: check any
(faces: boolean);
}}
/>;
<Camera
onCameraReady={() => {}}
onMountError={() => {}}
onBarCodeScanned={() => {}}
onFacesDetected={() => {}}
/>;
});
it('should raises an error when pass not supported type', () => {
// $FlowExpectedError: children must be a valid react node
<Camera>{() => {}}</Camera>;
<Camera
// $FlowExpectedError
onCameraReady={'need function'}
// $FlowExpectedError
onMountError={'need function'}
// $FlowExpectedError
onBarCodeScanned={'need function'}
// $FlowExpectedError
onFacesDetected={'need function'}
/>;
});
});
describe('class methods', () => {
declare var camera: Camera;
describe('takePictureAsync', () => {
it('should pass when call without options object', () => {
camera.takePictureAsync();
});
it('should pass when call with valid options object', () => {
camera.takePictureAsync({
quality: 1,
base64: false,
exif: false,
onPictureSaved: async () => {},
skipProcessing: false,
});
});
it('should raises an error when call with invalid options', () => {
camera.takePictureAsync({
// $FlowExpectedError
quality: 'need number',
// $FlowExpectedError
base64: 'need boolean',
// $FlowExpectedError
exif: 'need boolean',
// $FlowExpectedError
onPictureSaved: 'need function',
// $FlowExpectedError
skipProcessing: 'need boolean',
});
});
it('should raises an error when pass missing options prop', () => {
// $FlowExpectedError
camera.takePictureAsync({
abscd: 'missing prop',
});
});
it('should return Picture', () => {
camera.takePictureAsync().then(pic => {
(pic.width: number);
(pic.height: number);
(pic.uri: string);
(pic.base64: ?string);
// $FlowExpectedError: check any
(pic.width: boolean);
// $FlowExpectedError: check any
(pic.height: boolean);
// $FlowExpectedError: check any
(pic.uri: boolean);
// $FlowExpectedError: check any
(pic.base64: ?boolean);
});
});
});
describe('recordAsync', () => {
it('should pass when call without options object', () => {
camera.recordAsync();
});
it('should pass when call with valid options object', () => {
camera.recordAsync({
quality: Constants.VideoQuality['720p'],
maxDuration: 1,
maxFileSize: 1,
mute: true,
});
});
it('should raises an error when call with invalid options', () => {
camera.recordAsync({
// $FlowExpectedError: need opaque value type
quality: `Constants.VideoQuality['720p']`,
// $FlowExpectedError:
maxDuration: 'need number',
// $FlowExpectedError:
maxFileSize: 'need number',
// $FlowExpectedError:
mute: 'need boolean',
});
});
it('should raises an error when pass missing options prop', () => {
// $FlowExpectedError
camera.recordAsync({
abscd: 'missing prop',
});
});
it('should return Video', () => {
camera.recordAsync().then(vid => {
(vid.uri: string);
// $FlowExpectedError: check any
(vid.uri: boolean);
});
});
});
describe('getAvailablePictureSizesAsync', () => {
it('should pass when call without options object', () => {
camera.getAvailablePictureSizesAsync();
});
it('should pass when call with string', () => {
camera.getAvailablePictureSizesAsync('str');
});
it('should raises an error when call with invalid ratio', () => {
// $FlowExpectedError: radio argument must be string
camera.getAvailablePictureSizesAsync(123);
});
it('should return array string', () => {
camera.getAvailablePictureSizesAsync().then(result => {
(result: Array<string>);
// $FlowExpectedError: check any
(result: boolean);
});
});
});
describe('getSupportedRatiosAsync', () => {
it('should pass when call without options object', () => {
camera.getSupportedRatiosAsync();
});
it('should raises an error when pass argument', () => {
// $FlowExpectedError: arguments did not need
camera.getSupportedRatiosAsync('str');
});
it('should return array string', () => {
camera.getSupportedRatiosAsync().then(result => {
(result: Array<string>);
// $FlowExpectedError: check any
(result: boolean);
});
});
});
describe('stopRecording', () => {
it('should return nothing', () => {
(camera.stopRecording(): void);
});
});
describe('pausePreview', () => {
it('should return nothing', () => {
(camera.pausePreview(): void);
});
});
describe('resumePreview', () => {
it('should return nothing', () => {
(camera.resumePreview(): void);
});
});
});
|
app/components/add-variable-button.js | BrackCurly/qwery-me | import React from 'react';
import Toggle from '../containers/toggle';
import ToggleButton from './toggle-button';
import VariableTypeSelect from './variable-type-select';
export default class AddVariableButton extends React.Component {
render () {
return (
<div className="add-variable-button">
<Toggle initial={true}>
<ToggleButton>add</ToggleButton>
<VariableTypeSelect></VariableTypeSelect>
</Toggle>
</div>
);
}
} |
node_modules/react-native/Libraries/CustomComponents/Navigator/Navigator.js | aspanu/threeSeaShells | /**
* Copyright (c) 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.
*
* Facebook, Inc. ("Facebook") owns all right, title and interest, including
* all intellectual property and other proprietary rights, in and to the React
* Native CustomComponents software (the "Software"). Subject to your
* compliance with these terms, you are hereby granted a non-exclusive,
* worldwide, royalty-free copyright license to (1) use and copy the Software;
* and (2) reproduce and distribute the Software as part of your own software
* ("Your Software"). Facebook reserves all rights not expressly granted to
* you in this license agreement.
*
* THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
* IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR
* EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @providesModule Navigator
*/
/* eslint-disable no-extra-boolean-cast*/
'use strict';
var AnimationsDebugModule = require('NativeModules').AnimationsDebugModule;
var Dimensions = require('Dimensions');
var InteractionMixin = require('InteractionMixin');
var NavigationContext = require('NavigationContext');
var NavigatorBreadcrumbNavigationBar = require('NavigatorBreadcrumbNavigationBar');
var NavigatorNavigationBar = require('NavigatorNavigationBar');
var NavigatorSceneConfigs = require('NavigatorSceneConfigs');
var PanResponder = require('PanResponder');
var React = require('React');
var StyleSheet = require('StyleSheet');
var Subscribable = require('Subscribable');
var TimerMixin = require('react-timer-mixin');
var View = require('View');
var clamp = require('clamp');
var flattenStyle = require('flattenStyle');
var invariant = require('fbjs/lib/invariant');
var rebound = require('rebound');
var PropTypes = React.PropTypes;
// TODO: this is not ideal because there is no guarantee that the navigator
// is full screen, however we don't have a good way to measure the actual
// size of the navigator right now, so this is the next best thing.
var SCREEN_WIDTH = Dimensions.get('window').width;
var SCREEN_HEIGHT = Dimensions.get('window').height;
var SCENE_DISABLED_NATIVE_PROPS = {
pointerEvents: 'none',
style: {
top: SCREEN_HEIGHT,
bottom: -SCREEN_HEIGHT,
opacity: 0,
},
};
var __uid = 0;
function getuid() {
return __uid++;
}
function getRouteID(route) {
if (route === null || typeof route !== 'object') {
return String(route);
}
var key = '__navigatorRouteID';
if (!route.hasOwnProperty(key)) {
Object.defineProperty(route, key, {
enumerable: false,
configurable: false,
writable: false,
value: getuid(),
});
}
return route[key];
}
// styles moved to the top of the file so getDefaultProps can refer to it
var styles = StyleSheet.create({
container: {
flex: 1,
overflow: 'hidden',
},
defaultSceneStyle: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
top: 0,
},
baseScene: {
position: 'absolute',
overflow: 'hidden',
left: 0,
right: 0,
bottom: 0,
top: 0,
},
disabledScene: {
top: SCREEN_HEIGHT,
bottom: -SCREEN_HEIGHT,
},
transitioner: {
flex: 1,
backgroundColor: 'transparent',
overflow: 'hidden',
}
});
var GESTURE_ACTIONS = [
'pop',
'jumpBack',
'jumpForward',
];
/**
* `Navigator` handles the transition between different scenes in your app.
* It is implemented in JavaScript and is available on both iOS and Android. If
* you are targeting iOS only, you may also want to consider using
* [`NavigatorIOS`](docs/navigatorios.html) as it leverages native UIKit
* navigation.
*
* To set up the `Navigator` you provide one or more objects called routes,
* to identify each scene. You also provide a `renderScene` function that
* renders the scene for each route object.
*
* ```
* import React, { Component } from 'react';
* import { Text, Navigator } from 'react-native';
*
* export default class NavAllDay extends Component {
* render() {
* return (
* <Navigator
* initialRoute={{ title: 'Awesome Scene', index: 0 }}
* renderScene={(route, navigator) =>
* <Text>Hello {route.title}!</Text>
* }
* style={{padding: 100}}
* />
* );
* }
* }
* ```
*
* In the above example, `initialRoute` is used to specify the first route. It
* contains a `title` property that identifies the route. The `renderScene`
* prop returns a function that displays text based on the route's title.
*
* ### Additional Scenes
*
* The first example demonstrated one scene. To set up multiple scenes, you pass
* the `initialRouteStack` prop to `Navigator`:
*
* ```
* render() {
* const routes = [
* {title: 'First Scene', index: 0},
* {title: 'Second Scene', index: 1},
* ];
* return (
* <Navigator
* initialRoute={routes[0]}
* initialRouteStack={routes}
* renderScene={(route, navigator) =>
* <TouchableHighlight onPress={() => {
* if (route.index === 0) {
* navigator.push(routes[1]);
* } else {
* navigator.pop();
* }
* }}>
* <Text>Hello {route.title}!</Text>
* </TouchableHighlight>
* }
* style={{padding: 100}}
* />
* );
* }
* ```
*
* In the above example, a `routes` variable is defined with two route objects
* representing two scenes. Each route has an `index` property that is used to
* manage the scene being rendered. The `renderScene` method is changed to
* either push or pop the navigator depending on the current route's index.
* Finally, the `Text` component in the scene is now wrapped in a
* `TouchableHighlight` component to help trigger the navigator transitions.
*
* ### Navigation Bar
*
* You can optionally pass in your own navigation bar by returning a
* `Navigator.NavigationBar` component to the `navigationBar` prop in
* `Navigator`. You can configure the navigation bar properties, through
* the `routeMapper` prop. There you set up the left, right, and title
* properties of the navigation bar:
*
* ```
* <Navigator
* renderScene={(route, navigator) =>
* // ...
* }
* navigationBar={
* <Navigator.NavigationBar
* routeMapper={{
* LeftButton: (route, navigator, index, navState) =>
* { return (<Text>Cancel</Text>); },
* RightButton: (route, navigator, index, navState) =>
* { return (<Text>Done</Text>); },
* Title: (route, navigator, index, navState) =>
* { return (<Text>Awesome Nav Bar</Text>); },
* }}
* style={{backgroundColor: 'gray'}}
* />
* }
* />
* ```
*
* When configuring the left, right, and title items for the navigation bar,
* you have access to info such as the current route object and navigation
* state. This allows you to customize the title for each scene as well as
* the buttons. For example, you can choose to hide the left button for one of
* the scenes.
*
* Typically you want buttons to represent the left and right buttons. Building
* on the previous example, you can set this up as follows:
*
* ```
* LeftButton: (route, navigator, index, navState) =>
* {
* if (route.index === 0) {
* return null;
* } else {
* return (
* <TouchableHighlight onPress={() => navigator.pop()}>
* <Text>Back</Text>
* </TouchableHighlight>
* );
* }
* },
* ```
*
* This sets up a left navigator bar button that's visible on scenes after the
* the first one. When the button is tapped the navigator is popped.
*
* Another type of navigation bar, with breadcrumbs, is provided by
* `Navigator.BreadcrumbNavigationBar`. You can also provide your own navigation
* bar by passing it through the `navigationBar` prop. See the
* [UIExplorer](https://github.com/facebook/react-native/tree/master/Examples/UIExplorer)
* demo to try out both built-in navigation bars out and see how to use them.
*
* ### Scene Transitions
*
* To change the animation or gesture properties of the scene, provide a
* `configureScene` prop to get the config object for a given route:
*
* ```
* <Navigator
* renderScene={(route, navigator) =>
* // ...
* }
* configureScene={(route, routeStack) =>
* Navigator.SceneConfigs.FloatFromBottom}
* />
* ```
* In the above example, the newly pushed scene will float up from the bottom.
* See `Navigator.SceneConfigs` for default animations and more info on
* available [scene config options](/react-native/docs/navigator.html#configurescene).
*/
var Navigator = React.createClass({
propTypes: {
/**
* Optional function where you can configure scene animations and
* gestures. Will be invoked with `route` and `routeStack` parameters,
* where `route` corresponds to the current scene being rendered by the
* `Navigator` and `routeStack` is the set of currently mounted routes
* that the navigator could transition to.
*
* The function should return a scene configuration object.
*
* ```
* (route, routeStack) => Navigator.SceneConfigs.FloatFromRight
* ```
*
* Available scene configutation options are:
*
* - Navigator.SceneConfigs.PushFromRight (default)
* - Navigator.SceneConfigs.FloatFromRight
* - Navigator.SceneConfigs.FloatFromLeft
* - Navigator.SceneConfigs.FloatFromBottom
* - Navigator.SceneConfigs.FloatFromBottomAndroid
* - Navigator.SceneConfigs.FadeAndroid
* - Navigator.SceneConfigs.HorizontalSwipeJump
* - Navigator.SceneConfigs.HorizontalSwipeJumpFromRight
* - Navigator.SceneConfigs.VerticalUpSwipeJump
* - Navigator.SceneConfigs.VerticalDownSwipeJump
*
*/
configureScene: PropTypes.func,
/**
* Required function which renders the scene for a given route. Will be
* invoked with the `route` and the `navigator` object.
*
* ```
* (route, navigator) =>
* <MySceneComponent title={route.title} navigator={navigator} />
* ```
*/
renderScene: PropTypes.func.isRequired,
/**
* The initial route for navigation. A route is an object that the navigator
* will use to identify each scene it renders.
*
* If both `initialRoute` and `initialRouteStack` props are passed to
* `Navigator`, then `initialRoute` must be in a route in
* `initialRouteStack`. If `initialRouteStack` is passed as a prop but
* `initialRoute` is not, then `initialRoute` will default internally to
* the last item in `initialRouteStack`.
*/
initialRoute: PropTypes.object,
/**
* Pass this in to provide a set of routes to initially mount. This prop
* is required if `initialRoute` is not provided to the navigator. If this
* prop is not passed in, it will default internally to an array
* containing only `initialRoute`.
*/
initialRouteStack: PropTypes.arrayOf(PropTypes.object),
/**
* Pass in a function to get notified with the target route when
* the navigator component is mounted and before each navigator transition.
*/
onWillFocus: PropTypes.func,
/**
* Will be called with the new route of each scene after the transition is
* complete or after the initial mounting.
*/
onDidFocus: PropTypes.func,
/**
* Use this to provide an optional component representing a navigation bar
* that is persisted across scene transitions. This component will receive
* two props: `navigator` and `navState` representing the navigator
* component and its state. The component is re-rendered when the route
* changes.
*/
navigationBar: PropTypes.node,
/**
* Optionally pass in the navigator object from a parent `Navigator`.
*/
navigator: PropTypes.object,
/**
* Styles to apply to the container of each scene.
*/
sceneStyle: View.propTypes.style,
},
statics: {
BreadcrumbNavigationBar: NavigatorBreadcrumbNavigationBar,
NavigationBar: NavigatorNavigationBar,
SceneConfigs: NavigatorSceneConfigs,
},
mixins: [TimerMixin, InteractionMixin, Subscribable.Mixin],
getDefaultProps: function() {
return {
configureScene: () => NavigatorSceneConfigs.PushFromRight,
sceneStyle: styles.defaultSceneStyle,
};
},
getInitialState: function() {
this._navigationBarNavigator = this.props.navigationBarNavigator || this;
this._renderedSceneMap = new Map();
var routeStack = this.props.initialRouteStack || [this.props.initialRoute];
invariant(
routeStack.length >= 1,
'Navigator requires props.initialRoute or props.initialRouteStack.'
);
var initialRouteIndex = routeStack.length - 1;
if (this.props.initialRoute) {
initialRouteIndex = routeStack.indexOf(this.props.initialRoute);
invariant(
initialRouteIndex !== -1,
'initialRoute is not in initialRouteStack.'
);
}
return {
sceneConfigStack: routeStack.map(
(route) => this.props.configureScene(route, routeStack)
),
routeStack,
presentedIndex: initialRouteIndex,
transitionFromIndex: null,
activeGesture: null,
pendingGestureProgress: null,
transitionQueue: [],
};
},
componentWillMount: function() {
// TODO(t7489503): Don't need this once ES6 Class landed.
this.__defineGetter__('navigationContext', this._getNavigationContext);
this._subRouteFocus = [];
this.parentNavigator = this.props.navigator;
this._handlers = {};
this.springSystem = new rebound.SpringSystem();
this.spring = this.springSystem.createSpring();
this.spring.setRestSpeedThreshold(0.05);
this.spring.setCurrentValue(0).setAtRest();
this.spring.addListener({
onSpringEndStateChange: () => {
if (!this._interactionHandle) {
this._interactionHandle = this.createInteractionHandle();
}
},
onSpringUpdate: () => {
this._handleSpringUpdate();
},
onSpringAtRest: () => {
this._completeTransition();
},
});
this.panGesture = PanResponder.create({
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
onPanResponderRelease: this._handlePanResponderRelease,
onPanResponderMove: this._handlePanResponderMove,
onPanResponderTerminate: this._handlePanResponderTerminate,
});
this._interactionHandle = null;
this._emitWillFocus(this.state.routeStack[this.state.presentedIndex]);
},
componentDidMount: function() {
this._handleSpringUpdate();
this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]);
},
componentWillUnmount: function() {
if (this._navigationContext) {
this._navigationContext.dispose();
this._navigationContext = null;
}
this.spring.destroy();
if (this._interactionHandle) {
this.clearInteractionHandle(this._interactionHandle);
}
},
/**
* Reset every scene with an array of routes.
*
* @param {RouteStack} nextRouteStack Next route stack to reinitialize.
* All existing route stacks are destroyed an potentially recreated. There
* is no accompanying animation and this method immediately replaces and
* re-renders the navigation bar and the stack items.
*/
immediatelyResetRouteStack: function(nextRouteStack) {
var destIndex = nextRouteStack.length - 1;
this.setState({
routeStack: nextRouteStack,
sceneConfigStack: nextRouteStack.map(
route => this.props.configureScene(route, nextRouteStack)
),
presentedIndex: destIndex,
activeGesture: null,
transitionFromIndex: null,
transitionQueue: [],
}, () => {
this._handleSpringUpdate();
this._navBar && this._navBar.immediatelyRefresh();
this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]);
});
},
_transitionTo: function(destIndex, velocity, jumpSpringTo, cb) {
if (this.state.presentedIndex === destIndex) {
cb && cb();
return;
}
if (this.state.transitionFromIndex !== null) {
// Navigation is still transitioning, put the `destIndex` into queue.
this.state.transitionQueue.push({
destIndex,
velocity,
cb,
});
return;
}
this.state.transitionFromIndex = this.state.presentedIndex;
this.state.presentedIndex = destIndex;
this.state.transitionCb = cb;
this._onAnimationStart();
if (AnimationsDebugModule) {
AnimationsDebugModule.startRecordingFps();
}
var sceneConfig = this.state.sceneConfigStack[this.state.transitionFromIndex] ||
this.state.sceneConfigStack[this.state.presentedIndex];
invariant(
sceneConfig,
'Cannot configure scene at index ' + this.state.transitionFromIndex
);
if (jumpSpringTo != null) {
this.spring.setCurrentValue(jumpSpringTo);
}
this.spring.setOvershootClampingEnabled(true);
this.spring.getSpringConfig().friction = sceneConfig.springFriction;
this.spring.getSpringConfig().tension = sceneConfig.springTension;
this.spring.setVelocity(velocity || sceneConfig.defaultTransitionVelocity);
this.spring.setEndValue(1);
},
/**
* This happens for each frame of either a gesture or a transition. If both are
* happening, we only set values for the transition and the gesture will catch up later
*/
_handleSpringUpdate: function() {
if (!this.isMounted()) {
return;
}
// Prioritize handling transition in progress over a gesture:
if (this.state.transitionFromIndex != null) {
this._transitionBetween(
this.state.transitionFromIndex,
this.state.presentedIndex,
this.spring.getCurrentValue()
);
} else if (this.state.activeGesture != null) {
var presentedToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._transitionBetween(
this.state.presentedIndex,
presentedToIndex,
this.spring.getCurrentValue()
);
}
},
/**
* This happens at the end of a transition started by transitionTo, and when the spring catches up to a pending gesture
*/
_completeTransition: function() {
if (!this.isMounted()) {
return;
}
if (this.spring.getCurrentValue() !== 1 && this.spring.getCurrentValue() !== 0) {
// The spring has finished catching up to a gesture in progress. Remove the pending progress
// and we will be in a normal activeGesture state
if (this.state.pendingGestureProgress) {
this.state.pendingGestureProgress = null;
}
return;
}
this._onAnimationEnd();
var presentedIndex = this.state.presentedIndex;
var didFocusRoute = this._subRouteFocus[presentedIndex] || this.state.routeStack[presentedIndex];
if (AnimationsDebugModule) {
AnimationsDebugModule.stopRecordingFps(Date.now());
}
this.state.transitionFromIndex = null;
this.spring.setCurrentValue(0).setAtRest();
this._hideScenes();
if (this.state.transitionCb) {
this.state.transitionCb();
this.state.transitionCb = null;
}
this._emitDidFocus(didFocusRoute);
if (this._interactionHandle) {
this.clearInteractionHandle(this._interactionHandle);
this._interactionHandle = null;
}
if (this.state.pendingGestureProgress) {
// A transition completed, but there is already another gesture happening.
// Enable the scene and set the spring to catch up with the new gesture
var gestureToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._enableScene(gestureToIndex);
this.spring.setEndValue(this.state.pendingGestureProgress);
return;
}
if (this.state.transitionQueue.length) {
var queuedTransition = this.state.transitionQueue.shift();
this._enableScene(queuedTransition.destIndex);
this._emitWillFocus(this.state.routeStack[queuedTransition.destIndex]);
this._transitionTo(
queuedTransition.destIndex,
queuedTransition.velocity,
null,
queuedTransition.cb
);
}
},
_emitDidFocus: function(route) {
this.navigationContext.emit('didfocus', {route: route});
if (this.props.onDidFocus) {
this.props.onDidFocus(route);
}
},
_emitWillFocus: function(route) {
this.navigationContext.emit('willfocus', {route: route});
var navBar = this._navBar;
if (navBar && navBar.handleWillFocus) {
navBar.handleWillFocus(route);
}
if (this.props.onWillFocus) {
this.props.onWillFocus(route);
}
},
/**
* Hides all scenes that we are not currently on, gesturing to, or transitioning from
*/
_hideScenes: function() {
var gesturingToIndex = null;
if (this.state.activeGesture) {
gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
}
for (var i = 0; i < this.state.routeStack.length; i++) {
if (i === this.state.presentedIndex ||
i === this.state.transitionFromIndex ||
i === gesturingToIndex) {
continue;
}
this._disableScene(i);
}
},
/**
* Push a scene off the screen, so that opacity:0 scenes will not block touches sent to the presented scenes
*/
_disableScene: function(sceneIndex) {
this.refs['scene_' + sceneIndex] &&
this.refs['scene_' + sceneIndex].setNativeProps(SCENE_DISABLED_NATIVE_PROPS);
},
/**
* Put the scene back into the state as defined by props.sceneStyle, so transitions can happen normally
*/
_enableScene: function(sceneIndex) {
// First, determine what the defined styles are for scenes in this navigator
var sceneStyle = flattenStyle([styles.baseScene, this.props.sceneStyle]);
// Then restore the pointer events and top value for this scene
var enabledSceneNativeProps = {
pointerEvents: 'auto',
style: {
top: sceneStyle.top,
bottom: sceneStyle.bottom,
},
};
if (sceneIndex !== this.state.transitionFromIndex &&
sceneIndex !== this.state.presentedIndex) {
// If we are not in a transition from this index, make sure opacity is 0
// to prevent the enabled scene from flashing over the presented scene
enabledSceneNativeProps.style.opacity = 0;
}
this.refs['scene_' + sceneIndex] &&
this.refs['scene_' + sceneIndex].setNativeProps(enabledSceneNativeProps);
},
_onAnimationStart: function() {
var fromIndex = this.state.presentedIndex;
var toIndex = this.state.presentedIndex;
if (this.state.transitionFromIndex != null) {
fromIndex = this.state.transitionFromIndex;
} else if (this.state.activeGesture) {
toIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
}
this._setRenderSceneToHardwareTextureAndroid(fromIndex, true);
this._setRenderSceneToHardwareTextureAndroid(toIndex, true);
var navBar = this._navBar;
if (navBar && navBar.onAnimationStart) {
navBar.onAnimationStart(fromIndex, toIndex);
}
},
_onAnimationEnd: function() {
var max = this.state.routeStack.length - 1;
for (var index = 0; index <= max; index++) {
this._setRenderSceneToHardwareTextureAndroid(index, false);
}
var navBar = this._navBar;
if (navBar && navBar.onAnimationEnd) {
navBar.onAnimationEnd();
}
},
_setRenderSceneToHardwareTextureAndroid: function(sceneIndex, shouldRenderToHardwareTexture) {
var viewAtIndex = this.refs['scene_' + sceneIndex];
if (viewAtIndex === null || viewAtIndex === undefined) {
return;
}
viewAtIndex.setNativeProps({renderToHardwareTextureAndroid: shouldRenderToHardwareTexture});
},
_handleTouchStart: function() {
this._eligibleGestures = GESTURE_ACTIONS;
},
_handleMoveShouldSetPanResponder: function(e, gestureState) {
var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
if (!sceneConfig) {
return false;
}
this._expectingGestureGrant =
this._matchGestureAction(this._eligibleGestures, sceneConfig.gestures, gestureState);
return !!this._expectingGestureGrant;
},
_doesGestureOverswipe: function(gestureName) {
var wouldOverswipeBack = this.state.presentedIndex <= 0 &&
(gestureName === 'pop' || gestureName === 'jumpBack');
var wouldOverswipeForward = this.state.presentedIndex >= this.state.routeStack.length - 1 &&
gestureName === 'jumpForward';
return wouldOverswipeForward || wouldOverswipeBack;
},
_deltaForGestureAction: function(gestureAction) {
switch (gestureAction) {
case 'pop':
case 'jumpBack':
return -1;
case 'jumpForward':
return 1;
default:
invariant(false, 'Unsupported gesture action ' + gestureAction);
return;
}
},
_handlePanResponderRelease: function(e, gestureState) {
var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
var releaseGestureAction = this.state.activeGesture;
if (!releaseGestureAction) {
// The gesture may have been detached while responder, so there is no action here
return;
}
var releaseGesture = sceneConfig.gestures[releaseGestureAction];
var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
if (this.spring.getCurrentValue() === 0) {
// The spring is at zero, so the gesture is already complete
this.spring.setCurrentValue(0).setAtRest();
this._completeTransition();
return;
}
var isTravelVertical = releaseGesture.direction === 'top-to-bottom' || releaseGesture.direction === 'bottom-to-top';
var isTravelInverted = releaseGesture.direction === 'right-to-left' || releaseGesture.direction === 'bottom-to-top';
var velocity, gestureDistance;
if (isTravelVertical) {
velocity = isTravelInverted ? -gestureState.vy : gestureState.vy;
gestureDistance = isTravelInverted ? -gestureState.dy : gestureState.dy;
} else {
velocity = isTravelInverted ? -gestureState.vx : gestureState.vx;
gestureDistance = isTravelInverted ? -gestureState.dx : gestureState.dx;
}
var transitionVelocity = clamp(-10, velocity, 10);
if (Math.abs(velocity) < releaseGesture.notMoving) {
// The gesture velocity is so slow, is "not moving"
var hasGesturedEnoughToComplete = gestureDistance > releaseGesture.fullDistance * releaseGesture.stillCompletionRatio;
transitionVelocity = hasGesturedEnoughToComplete ? releaseGesture.snapVelocity : -releaseGesture.snapVelocity;
}
if (transitionVelocity < 0 || this._doesGestureOverswipe(releaseGestureAction)) {
// This gesture is to an overswiped region or does not have enough velocity to complete
// If we are currently mid-transition, then this gesture was a pending gesture. Because this gesture takes no action, we can stop here
if (this.state.transitionFromIndex == null) {
// There is no current transition, so we need to transition back to the presented index
var transitionBackToPresentedIndex = this.state.presentedIndex;
// slight hack: change the presented index for a moment in order to transitionTo correctly
this.state.presentedIndex = destIndex;
this._transitionTo(
transitionBackToPresentedIndex,
-transitionVelocity,
1 - this.spring.getCurrentValue()
);
}
} else {
// The gesture has enough velocity to complete, so we transition to the gesture's destination
this._emitWillFocus(this.state.routeStack[destIndex]);
this._transitionTo(
destIndex,
transitionVelocity,
null,
() => {
if (releaseGestureAction === 'pop') {
this._cleanScenesPastIndex(destIndex);
}
}
);
}
this._detachGesture();
},
_handlePanResponderTerminate: function(e, gestureState) {
if (this.state.activeGesture == null) {
return;
}
var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._detachGesture();
var transitionBackToPresentedIndex = this.state.presentedIndex;
// slight hack: change the presented index for a moment in order to transitionTo correctly
this.state.presentedIndex = destIndex;
this._transitionTo(
transitionBackToPresentedIndex,
null,
1 - this.spring.getCurrentValue()
);
},
_attachGesture: function(gestureId) {
this.state.activeGesture = gestureId;
var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._enableScene(gesturingToIndex);
},
_detachGesture: function() {
this.state.activeGesture = null;
this.state.pendingGestureProgress = null;
this._hideScenes();
},
_handlePanResponderMove: function(e, gestureState) {
if (this._isMoveGestureAttached !== undefined) {
invariant(
this._expectingGestureGrant,
'Responder granted unexpectedly.'
);
this._attachGesture(this._expectingGestureGrant);
this._onAnimationStart();
this._expectingGestureGrant = undefined;
}
var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
if (this.state.activeGesture) {
var gesture = sceneConfig.gestures[this.state.activeGesture];
return this._moveAttachedGesture(gesture, gestureState);
}
var matchedGesture = this._matchGestureAction(GESTURE_ACTIONS, sceneConfig.gestures, gestureState);
if (matchedGesture) {
this._attachGesture(matchedGesture);
}
},
_moveAttachedGesture: function(gesture, gestureState) {
var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top';
var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top';
var distance = isTravelVertical ? gestureState.dy : gestureState.dx;
distance = isTravelInverted ? -distance : distance;
var gestureDetectMovement = gesture.gestureDetectMovement;
var nextProgress = (distance - gestureDetectMovement) /
(gesture.fullDistance - gestureDetectMovement);
if (nextProgress < 0 && gesture.isDetachable) {
var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._transitionBetween(this.state.presentedIndex, gesturingToIndex, 0);
this._detachGesture();
if (this.state.pendingGestureProgress != null) {
this.spring.setCurrentValue(0);
}
return;
}
if (this._doesGestureOverswipe(this.state.activeGesture)) {
var frictionConstant = gesture.overswipe.frictionConstant;
var frictionByDistance = gesture.overswipe.frictionByDistance;
var frictionRatio = 1 / ((frictionConstant) + (Math.abs(nextProgress) * frictionByDistance));
nextProgress *= frictionRatio;
}
nextProgress = clamp(0, nextProgress, 1);
if (this.state.transitionFromIndex != null) {
this.state.pendingGestureProgress = nextProgress;
} else if (this.state.pendingGestureProgress) {
this.spring.setEndValue(nextProgress);
} else {
this.spring.setCurrentValue(nextProgress);
}
},
_matchGestureAction: function(eligibleGestures, gestures, gestureState) {
if (!gestures || !eligibleGestures || !eligibleGestures.some) {
return null;
}
var matchedGesture = null;
eligibleGestures.some((gestureName, gestureIndex) => {
var gesture = gestures[gestureName];
if (!gesture) {
return;
}
if (gesture.overswipe == null && this._doesGestureOverswipe(gestureName)) {
// cannot swipe past first or last scene without overswiping
return false;
}
var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top';
var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top';
var startedLoc = isTravelVertical ? gestureState.y0 : gestureState.x0;
var currentLoc = isTravelVertical ? gestureState.moveY : gestureState.moveX;
var travelDist = isTravelVertical ? gestureState.dy : gestureState.dx;
var oppositeAxisTravelDist =
isTravelVertical ? gestureState.dx : gestureState.dy;
var edgeHitWidth = gesture.edgeHitWidth;
if (isTravelInverted) {
startedLoc = -startedLoc;
currentLoc = -currentLoc;
travelDist = -travelDist;
oppositeAxisTravelDist = -oppositeAxisTravelDist;
edgeHitWidth = isTravelVertical ?
-(SCREEN_HEIGHT - edgeHitWidth) :
-(SCREEN_WIDTH - edgeHitWidth);
}
if (startedLoc === 0) {
startedLoc = currentLoc;
}
var moveStartedInRegion = gesture.edgeHitWidth == null ||
startedLoc < edgeHitWidth;
if (!moveStartedInRegion) {
return false;
}
var moveTravelledFarEnough = travelDist >= gesture.gestureDetectMovement;
if (!moveTravelledFarEnough) {
return false;
}
var directionIsCorrect = Math.abs(travelDist) > Math.abs(oppositeAxisTravelDist) * gesture.directionRatio;
if (directionIsCorrect) {
matchedGesture = gestureName;
return true;
} else {
this._eligibleGestures = this._eligibleGestures.slice().splice(gestureIndex, 1);
}
});
return matchedGesture || null;
},
_transitionSceneStyle: function(fromIndex, toIndex, progress, index) {
var viewAtIndex = this.refs['scene_' + index];
if (viewAtIndex === null || viewAtIndex === undefined) {
return;
}
// Use toIndex animation when we move forwards. Use fromIndex when we move back
var sceneConfigIndex = fromIndex < toIndex ? toIndex : fromIndex;
var sceneConfig = this.state.sceneConfigStack[sceneConfigIndex];
// this happens for overswiping when there is no scene at toIndex
if (!sceneConfig) {
sceneConfig = this.state.sceneConfigStack[sceneConfigIndex - 1];
}
var styleToUse = {};
var useFn = index < fromIndex || index < toIndex ?
sceneConfig.animationInterpolators.out :
sceneConfig.animationInterpolators.into;
var directionAdjustedProgress = fromIndex < toIndex ? progress : 1 - progress;
var didChange = useFn(styleToUse, directionAdjustedProgress);
if (didChange) {
viewAtIndex.setNativeProps({style: styleToUse});
}
},
_transitionBetween: function(fromIndex, toIndex, progress) {
this._transitionSceneStyle(fromIndex, toIndex, progress, fromIndex);
this._transitionSceneStyle(fromIndex, toIndex, progress, toIndex);
var navBar = this._navBar;
if (navBar && navBar.updateProgress && toIndex >= 0 && fromIndex >= 0) {
navBar.updateProgress(progress, fromIndex, toIndex);
}
},
_handleResponderTerminationRequest: function() {
return false;
},
_getDestIndexWithinBounds: function(n) {
var currentIndex = this.state.presentedIndex;
var destIndex = currentIndex + n;
invariant(
destIndex >= 0,
'Cannot jump before the first route.'
);
var maxIndex = this.state.routeStack.length - 1;
invariant(
maxIndex >= destIndex,
'Cannot jump past the last route.'
);
return destIndex;
},
_jumpN: function(n) {
var destIndex = this._getDestIndexWithinBounds(n);
this._enableScene(destIndex);
this._emitWillFocus(this.state.routeStack[destIndex]);
this._transitionTo(destIndex);
},
/**
* Transition to an existing scene without unmounting.
* @param {object} route Route to transition to. The specified route must
* be in the currently mounted set of routes defined in `routeStack`.
*/
jumpTo: function(route) {
var destIndex = this.state.routeStack.indexOf(route);
invariant(
destIndex !== -1,
'Cannot jump to route that is not in the route stack'
);
this._jumpN(destIndex - this.state.presentedIndex);
},
/**
* Jump forward to the next scene in the route stack.
*/
jumpForward: function() {
this._jumpN(1);
},
/**
* Jump backward without unmounting the current scene.
*/
jumpBack: function() {
this._jumpN(-1);
},
/**
* Navigate forward to a new scene, squashing any scenes that you could
* jump forward to.
* @param {object} route Route to push into the navigator stack.
*/
push: function(route) {
invariant(!!route, 'Must supply route to push');
var activeLength = this.state.presentedIndex + 1;
var activeStack = this.state.routeStack.slice(0, activeLength);
var activeAnimationConfigStack = this.state.sceneConfigStack.slice(0, activeLength);
var nextStack = activeStack.concat([route]);
var destIndex = nextStack.length - 1;
var nextSceneConfig = this.props.configureScene(route, nextStack);
var nextAnimationConfigStack = activeAnimationConfigStack.concat([nextSceneConfig]);
this._emitWillFocus(nextStack[destIndex]);
this.setState({
routeStack: nextStack,
sceneConfigStack: nextAnimationConfigStack,
}, () => {
this._enableScene(destIndex);
this._transitionTo(destIndex, nextSceneConfig.defaultTransitionVelocity);
});
},
_popN: function(n) {
if (n === 0) {
return;
}
invariant(
this.state.presentedIndex - n >= 0,
'Cannot pop below zero'
);
var popIndex = this.state.presentedIndex - n;
var presentedRoute = this.state.routeStack[this.state.presentedIndex];
var popSceneConfig = this.props.configureScene(presentedRoute); // using the scene config of the currently presented view
this._enableScene(popIndex);
this._emitWillFocus(this.state.routeStack[popIndex]);
this._transitionTo(
popIndex,
popSceneConfig.defaultTransitionVelocity,
null, // no spring jumping
() => {
this._cleanScenesPastIndex(popIndex);
}
);
},
/**
* Transition back and unmount the current scene.
*/
pop: function() {
if (this.state.transitionQueue.length) {
// This is the workaround to prevent user from firing multiple `pop()`
// calls that may pop the routes beyond the limit.
// Because `this.state.presentedIndex` does not update until the
// transition starts, we can't reliably use `this.state.presentedIndex`
// to know whether we can safely keep popping the routes or not at this
// moment.
return;
}
if (this.state.presentedIndex > 0) {
this._popN(1);
}
},
/**
* Replace a scene as specified by an index.
* @param {object} route Route representing the new scene to render.
* @param {number} index The route in the stack that should be replaced.
* If negative, it counts from the back of the stack.
* @param {Function} cb Callback function when the scene has been replaced.
*/
replaceAtIndex: function(route, index, cb) {
invariant(!!route, 'Must supply route to replace');
if (index < 0) {
index += this.state.routeStack.length;
}
if (this.state.routeStack.length <= index) {
return;
}
var nextRouteStack = this.state.routeStack.slice();
var nextAnimationModeStack = this.state.sceneConfigStack.slice();
nextRouteStack[index] = route;
nextAnimationModeStack[index] = this.props.configureScene(route, nextRouteStack);
if (index === this.state.presentedIndex) {
this._emitWillFocus(route);
}
this.setState({
routeStack: nextRouteStack,
sceneConfigStack: nextAnimationModeStack,
}, () => {
if (index === this.state.presentedIndex) {
this._emitDidFocus(route);
}
cb && cb();
});
},
/**
* Replace the current scene with a new route.
* @param {object} route Route that replaces the current scene.
*/
replace: function(route) {
this.replaceAtIndex(route, this.state.presentedIndex);
},
/**
* Replace the previous scene.
* @param {object} route Route that replaces the previous scene.
*/
replacePrevious: function(route) {
this.replaceAtIndex(route, this.state.presentedIndex - 1);
},
/**
* Pop to the first scene in the stack, unmounting every other scene.
*/
popToTop: function() {
this.popToRoute(this.state.routeStack[0]);
},
/**
* Pop to a particular scene, as specified by its route.
* All scenes after it will be unmounted.
* @param {object} route Route to pop to.
*/
popToRoute: function(route) {
var indexOfRoute = this.state.routeStack.indexOf(route);
invariant(
indexOfRoute !== -1,
'Calling popToRoute for a route that doesn\'t exist!'
);
var numToPop = this.state.presentedIndex - indexOfRoute;
this._popN(numToPop);
},
/**
* Replace the previous scene and pop to it.
* @param {object} route Route that replaces the previous scene.
*/
replacePreviousAndPop: function(route) {
if (this.state.routeStack.length < 2) {
return;
}
this.replacePrevious(route);
this.pop();
},
/**
* Navigate to a new scene and reset route stack.
* @param {object} route Route to navigate to.
*/
resetTo: function(route) {
invariant(!!route, 'Must supply route to push');
this.replaceAtIndex(route, 0, () => {
// Do not use popToRoute here, because race conditions could prevent the
// route from existing at this time. Instead, just go to index 0
if (this.state.presentedIndex > 0) {
this._popN(this.state.presentedIndex);
}
});
},
/**
* Returns the current list of routes.
*/
getCurrentRoutes: function() {
// Clone before returning to avoid caller mutating the stack
return this.state.routeStack.slice();
},
_cleanScenesPastIndex: function(index) {
var newStackLength = index + 1;
// Remove any unneeded rendered routes.
if (newStackLength < this.state.routeStack.length) {
this.setState({
sceneConfigStack: this.state.sceneConfigStack.slice(0, newStackLength),
routeStack: this.state.routeStack.slice(0, newStackLength),
});
}
},
_renderScene: function(route, i) {
var disabledSceneStyle = null;
var disabledScenePointerEvents = 'auto';
if (i !== this.state.presentedIndex) {
disabledSceneStyle = styles.disabledScene;
disabledScenePointerEvents = 'none';
}
return (
<View
key={'scene_' + getRouteID(route)}
ref={'scene_' + i}
onStartShouldSetResponderCapture={() => {
return (this.state.transitionFromIndex != null) || (this.state.transitionFromIndex != null);
}}
pointerEvents={disabledScenePointerEvents}
style={[styles.baseScene, this.props.sceneStyle, disabledSceneStyle]}>
{this.props.renderScene(
route,
this
)}
</View>
);
},
_renderNavigationBar: function() {
let { navigationBar } = this.props;
if (!navigationBar) {
return null;
}
return React.cloneElement(navigationBar, {
ref: (navBar) => {
this._navBar = navBar;
if (navigationBar && typeof navigationBar.ref === 'function') {
navigationBar.ref(navBar);
}
},
navigator: this._navigationBarNavigator,
navState: this.state,
});
},
render: function() {
var newRenderedSceneMap = new Map();
var scenes = this.state.routeStack.map((route, index) => {
var renderedScene;
if (this._renderedSceneMap.has(route) &&
index !== this.state.presentedIndex) {
renderedScene = this._renderedSceneMap.get(route);
} else {
renderedScene = this._renderScene(route, index);
}
newRenderedSceneMap.set(route, renderedScene);
return renderedScene;
});
this._renderedSceneMap = newRenderedSceneMap;
return (
<View style={[styles.container, this.props.style]}>
<View
style={styles.transitioner}
{...this.panGesture.panHandlers}
onTouchStart={this._handleTouchStart}
onResponderTerminationRequest={
this._handleResponderTerminationRequest
}>
{scenes}
</View>
{this._renderNavigationBar()}
</View>
);
},
_getNavigationContext: function() {
if (!this._navigationContext) {
this._navigationContext = new NavigationContext();
}
return this._navigationContext;
}
});
module.exports = Navigator;
|
pathfinder/architecturestack/src/Report.js | leanix/leanix-custom-reports | import React, { Component } from 'react';
import CommonQueries from './common/CommonGraphQLQueries';
import DataIndex from './common/DataIndex';
import Utilities from './common/Utilities';
import SelectField from './SelectField';
import Checkbox from './Checkbox';
import Legend from './Legend';
import Matrix from './Matrix';
import MissingDataAlert from './MissingDataAlert';
import ModalDialog from './ModalDialog';
const LOADING_INIT = 0;
const LOADING_NEW_DATA = 1;
const LOADING_SUCCESSFUL = 2;
const LOADING_ERROR = 3;
const SELECT_FIELD_STYLE = {
width: '250px',
display: 'inline-block',
verticalAlign: 'top',
marginRight: '1em'
};
const SWAP_BUTTON_STYLE = {
display: 'inline-block',
verticalAlign: 'top',
marginTop: '1.5em',
marginRight: '1em'
};
class Report extends Component {
constructor(props) {
super(props);
this.index = new DataIndex();
this._initReport = this._initReport.bind(this);
this._createConfig = this._createConfig.bind(this);
this._resetState = this._resetState.bind(this);
this._handleRestoreError = this._handleRestoreError.bind(this);
this._restoreStateFromFramework = this._restoreStateFromFramework.bind(this);
this._publishStateToFramework = this._publishStateToFramework.bind(this);
this._handleError = this._handleError.bind(this);
this._getAndHandleAdditionalData = this._getAndHandleAdditionalData.bind(this);
this._createAllViewsQuery = this._createAllViewsQuery.bind(this);
this._getAndHandleViewData = this._getAndHandleViewData.bind(this);
this._computeData = this._computeData.bind(this);
this._getValue = this._getValue.bind(this);
this._getViewModel = this._getViewModel.bind(this);
this._getDataValues = this._getDataValues.bind(this);
this._handleViewSelect = this._handleViewSelect.bind(this);
this._handleXAxisSelect = this._handleXAxisSelect.bind(this);
this._handleYAxisSelect = this._handleYAxisSelect.bind(this);
this._handleDismissAlertButton = this._handleDismissAlertButton.bind(this);
this._handleConfig = this._handleConfig.bind(this);
this._handleFactsheetTypeSelect = this._handleFactsheetTypeSelect.bind(this);
this._handleShowMissingDataWarningCheck = this._handleShowMissingDataWarningCheck.bind(this);
this._handleShowEmptyRowsCheck = this._handleShowEmptyRowsCheck.bind(this);
this._handleShowEmptyColumnsCheck = this._handleShowEmptyColumnsCheck.bind(this);
this._handleSwapAxes = this._handleSwapAxes.bind(this);
this._getSelectedViewOption = this._getSelectedViewOption.bind(this);
this._getSelectedXAxisOption = this._getSelectedXAxisOption.bind(this);
this._getSelectedYAxisOption = this._getSelectedYAxisOption.bind(this);
this._renderLoading = this._renderLoading.bind(this);
this._renderError = this._renderError.bind(this);
this._renderSuccessful = this._renderSuccessful.bind(this);
this._renderConfigContent = this._renderConfigContent.bind(this);
this._renderSelectFields = this._renderSelectFields.bind(this);
this._resetUIState = this._resetUIState.bind(this);
this.state = {
loadingState: LOADING_INIT,
legendData: [],
matrixData: [],
matrixDataAvailable: false,
missingData: [],
showMissingDataWarning: true,
showEmptyRows: false,
showEmptyColumns: false,
showConfigure: false
};
this.reportState = {
configStore: {},
factsheetModels: [],
selectedFactsheetType: null,
selectedView: null,
selectedXAxis: null,
selectedYAxis: null,
viewOptions: {},
lastFacetData: [],
viewModel: {}
};
}
componentDidMount() {
lx.init().then(this._initReport).catch(this._handleError);
}
_initReport(setup) {
this.setup = setup;
lx.showSpinner('Loading data...');
// get all factsheet defs from dataModel
this.reportState.factsheetModels = Object.keys(Utilities.getFrom(setup, 'settings.dataModel.factSheets'));
this.reportState.factsheetModels.sort();
// get all tags, then the data from facet config
lx.executeGraphQL(CommonQueries.tagGroups).then((tagGroups) => {
this.index.put(tagGroups);
// get the views
lx.executeGraphQL(this._createAllViewsQuery()).then((allViewData) => {
// extract viewInfos
for (let key in allViewData) {
const fieldModels = Utilities.getFrom(setup, 'settings.dataModel.factSheets.' + key + '.fields');
this.reportState.viewOptions[key] = allViewData[key].viewInfos.filter((e) => {
switch (e.type) {
case 'FIELD':
// check if field type can be handled
return this._checkFieldType(fieldModels[e.key].type);
case 'TAG':
// only single selectable tag groups are allowed
const tagGroup = this.index.tagGroups.byID[e.key.slice(5)];
return tagGroup && tagGroup.mode === 'SINGLE';
default:
return false;
}
}).map((e) => {
if (e.type === 'TAG') {
return {
type: e.type,
key: e.key,
value: e.key.slice(5),
label: 'Tag group: ' + e.label,
originalLabel: e.label
};
}
return {
type: fieldModels[e.key].type,
key: e.key,
value: e.key,
label: lx.translateField(key, e.key),
originalLabel: e.label
};
});
}
// filter out all that have less than 2 elements
Object.keys(this.reportState.viewOptions).forEach((e) => {
if (this.reportState.viewOptions[e].length < 2) {
delete this.reportState.viewOptions[e];
}
});
// re-assign updated factsheetModels
this.reportState.factsheetModels = Object.keys(this.reportState.viewOptions);
// load default state
this._resetState();
// then may restore saved state
if (this.setup.savedState && this.setup.savedState.customState) {
const result = this._restoreStateFromFramework(this.setup.savedState.customState);
if (result) {
this._handleRestoreError(result);
lx.hideSpinner();
return;
}
}
if (!this.reportState.selectedFactsheetType) {
// error, since there is no factsheet type with enough data
this._handleError('There is no factsheet type with enough data.');
lx.hideSpinner();
return;
}
lx.hideSpinner();
lx.ready(this._createConfig());
}).catch(this._handleError);
}).catch(this._handleError);
}
_createConfig() {
return {
allowEditing: false,
facets: [{
key: this.reportState.selectedFactsheetType,
label: lx.translateFactSheetType(this.reportState.selectedFactsheetType, 'plural'),
fixedFactSheetType: this.reportState.selectedFactsheetType,
attributes: ['id', 'displayName'],
sorting: [{
key: 'displayName',
mode: 'BY_FIELD',
order: 'asc'
}
],
callback: (facetData) => {
if (this.state.loadingState === LOADING_SUCCESSFUL) {
this.setState({
loadingState: LOADING_NEW_DATA
});
}
this.reportState.lastFacetData = facetData;
this._getAndHandleAdditionalData();
}
}],
menuActions: {
showConfigure: true,
configureCallback: () => {
if (this.state.loadingState !== LOADING_SUCCESSFUL) {
return;
}
this.reportState.configStore = {
factsheetType: this.reportState.selectedFactsheetType,
showMissingDataWarning: this.state.showMissingDataWarning,
showEmptyRows: this.state.showEmptyRows,
showEmptyColumns: this.state.showEmptyColumns
};
this.setState({
showConfigure: true
});
}
},
export: {
autoScale: true,
exportElementSelector: '#content',
format: 'a1',
inputType: 'HTML',
orientation: 'landscape'
},
restoreStateCallback: (state) => {
console.log('Callback:');
console.log(state);
const result = this._restoreStateFromFramework(state);
if (result) {
this._handleRestoreError(result);
return;
}
// get new data and re-render
this._getAndHandleAdditionalData();
}
};
}
_handleRestoreError(result) {
switch (result.loadingState) {
case LOADING_ERROR:
this._handleError(result.msg);
return;
default:
console.error('Unknown loading state after an unsuccessful restore op: '
+ result.loadingState);
this._handleError(result.msg);
return;
}
}
_resetState() {
// first one should be Application, fallback: use first entry
this.reportState.selectedFactsheetType = this.reportState.factsheetModels.find((e) => {
return e === 'Application';
});
if (!this.reportState.selectedFactsheetType) {
this.reportState.selectedFactsheetType = this.reportState.factsheetModels[0];
}
this.reportState.selectedView = null;
this.reportState.selectedXAxis = null;
this.reportState.selectedYAxis = null;
this.state.showMissingDataWarning = true;
this.state.showEmptyRows = false;
this.state.showEmptyColumns = false;
}
_restoreStateFromFramework(newState) {
// check if the state can be restored
// if not then provide fallbacks or goto error screen
this.reportState.selectedFactsheetType = newState.selectedFactsheetType;
const viewOptions = this.reportState.viewOptions[newState.selectedFactsheetType];
if (!viewOptions) {
return {
loadingState: LOADING_ERROR,
msg: 'There isn\'t enough data for the factsheet type "' + newState.selectedFactsheetType
+ '". Please delete this bookmark.'
};
}
this.reportState.selectedView = viewOptions.find((e) => {
return e.key === newState.selectedView.key;
});
if (!this.reportState.selectedView) {
return {
loadingState: LOADING_ERROR,
msg: 'There is no view with the name "' + newState.selectedView.label
+ '" defined. Please delete this bookmark.'
};
}
this.reportState.selectedXAxis = viewOptions.find((e) => {
return e.key === newState.selectedXAxis.key;
});
if (!this.reportState.selectedXAxis) {
return {
loadingState: LOADING_ERROR,
msg: 'There is no X-Axis with the name "' + newState.selectedXAxis.label
+ '" defined. Please delete this bookmark.'
};
}
this.reportState.selectedYAxis = viewOptions.find((e) => {
return e.key === newState.selectedYAxis.key;
});
if (!this.reportState.selectedYAxis) {
return {
loadingState: LOADING_ERROR,
msg: 'There is no X-Axis with the name "' + newState.selectedYAxis.label
+ '" defined. Please delete this bookmark.'
};
}
this.state.showMissingDataWarning = newState.showMissingDataWarning;
this.state.showEmptyRows = newState.showEmptyRows;
this.state.showEmptyColumns = newState.showEmptyColumns;
}
_publishStateToFramework() {
const factsheetType = this.reportState.selectedFactsheetType;
const state = {
selectedFactsheetType: factsheetType,
selectedView: this._getSelectedViewOption(factsheetType),
selectedXAxis: this._getSelectedXAxisOption(factsheetType),
selectedYAxis: this._getSelectedYAxisOption(factsheetType),
showMissingDataWarning: this.state.showMissingDataWarning,
showEmptyRows: this.state.showEmptyRows,
showEmptyColumns: this.state.showEmptyColumns
};
lx.publishState(state);
}
_handleError(err) {
console.error(err);
this.setState({
loadingState: LOADING_ERROR
});
}
_getAndHandleAdditionalData() {
// remove previous data
this.index.remove('additionalData');
const factsheetType = this.reportState.selectedFactsheetType;
// get current selected values from SelectFields
const viewOption = this._getSelectedViewOption(factsheetType);
const xAxisOption = this._getSelectedXAxisOption(factsheetType);
const yAxisOption = this._getSelectedYAxisOption(factsheetType);
// get remaining data based on selected combobox values
lx.showSpinner('Loading data...');
const attributes = [];
attributes.push(this._getQueryAttribute(viewOption.value, viewOption.type));
attributes.push(this._getQueryAttribute(xAxisOption.value, xAxisOption.type));
attributes.push(this._getQueryAttribute(yAxisOption.value, yAxisOption.type));
lx.executeGraphQL(this._createAdditionalDataQuery(this.reportState.lastFacetData, factsheetType, attributes)).then((additionalData) => {
this.index.put(additionalData);
this._getAndHandleViewData();
}).catch(this._handleError);
}
_createAllViewsQuery() {
const query = this.reportState.factsheetModels.map((e) => {
return `${e}:view(
filter: {facetFilters: [{facetKey: "FactSheetTypes", keys: ["${e}"]}]}
) {
viewInfos { key label type }
}`;
}).join('\n');
return `{${query}}`;
}
_createViewQuery(factsheetType, viewKey) {
return `{view(
key: "${viewKey}",
filter: {facetFilters: [{facetKey: "FactSheetTypes", keys: ["${factsheetType}"]}]}
) {
legendItems { id value bgColor color transparency inLegend }
}}`;
}
_createAdditionalDataQuery(ids, factsheetType, attributes) {
// create ids string, but pay attention to server-side limitation of 1024 entries
const idsString = ids.length < 1025 ? ids.map((e) => {
return '"' + e.id + '"';
}).join(',') : undefined;
// use either ids or at least the factsheet type for the filter
const idFilter = idsString ? `(filter: { ids: [${idsString}] })`
: (factsheetType ? `(filter: {facetFilters: [{facetKey: "FactSheetTypes", keys: ["${factsheetType}"]}]})` : '');
let attributeDef = 'id ' + attributes.filter((e, i) => {
// avoid duplicates
return attributes.indexOf(e, i + 1) < 0;
}).join(' ');
if (factsheetType) {
attributeDef = `...on ${factsheetType} { ${attributeDef} }`;
}
return `{additionalData: allFactSheets${idFilter} {
edges { node {
${attributeDef}
}}
}}`;
}
_getAndHandleViewData() {
const factsheetType = this.reportState.selectedFactsheetType;
const viewOption = this._getSelectedViewOption(factsheetType);
if (this.reportState.viewModel && this.reportState.viewModel._key === viewOption.value) {
// no need to query the same data again
this._computeData();
return;
}
lx.executeGraphQL(this._createViewQuery(factsheetType, viewOption.key)).then((viewData) => {
const legendItems = Utilities.getFrom(viewData, 'view.legendItems');
this.reportState.viewModel = legendItems.reduce((acc, e) => {
acc[e.value] = e;
return acc;
}, {});
this.reportState.viewModel._rawLegendItems = legendItems;
this.reportState.viewModel._key = viewOption.value;
this._computeData();
}).catch(this._handleError);
}
_computeData() {
const setup = this.setup;
const index = this.index;
const facetData = this.reportState.lastFacetData;
const factsheetType = this.reportState.selectedFactsheetType;
const viewOption = this._getSelectedViewOption(factsheetType);
const viewModel = this.reportState.viewModel;
const xAxisOption = this._getSelectedXAxisOption(factsheetType);
const yAxisOption = this._getSelectedYAxisOption(factsheetType);
// create legend data
const legendData = [];
viewModel._rawLegendItems.forEach((e) => {
if (!e.inLegend) {
return;
}
legendData.push({
label: () => {
// TODO remove hack
// see https://github.com/leanix/leanix-reporting/issues/7
if (e.value === '__missing__') {
return 'n/a';
}
return lx.translateFieldValue(factsheetType, viewOption.value, e.value);
},
bgColor: e.bgColor,
color: e.color
});
});
// create matrixData
const xAxisValues = this._getDataValues(xAxisOption);
const yAxisValues = this._getDataValues(yAxisOption);
const matrixData = []; // position (0,0) will always be empty
// the first row contains the values from the x axis option
if (xAxisOption.type === 'TAG') {
matrixData.push([undefined].concat(xAxisValues.map((e) => {
return e;
})));
} else {
matrixData.push([undefined].concat(xAxisValues.map((e) => {
return lx.translateFieldValue(factsheetType, xAxisOption.value, e);
})));
}
if (yAxisOption.type === 'TAG') {
yAxisValues.forEach((e) => {
// extend the row with empty arrays for later use
matrixData.push([e].concat(xAxisValues.map(() => {
// all other rows contain the values from the y axis option as their first value
return [];
})));
});
} else {
yAxisValues.forEach((e) => {
// extend the row with empty arrays for later use
matrixData.push([lx.translateFieldValue(factsheetType, yAxisOption.value, e)].concat(xAxisValues.map(() => {
// all other rows contain the values from the y axis option as their first value
return [];
})));
});
}
// now add the data
let matrixDataAvailable = false;
const missingData = [];
facetData.forEach((e) => {
const id = e.id;
const additionalData = index.additionalData.byID[id];
// get the data values
const xValue = this._getValue(xAxisOption, additionalData);
const yValue = this._getValue(yAxisOption, additionalData);
if (!xValue || !yValue) {
missingData.push({
id: e.id,
name: e.displayName,
reason: this._createMissingDataMsgForValues(xValue, yValue, xAxisOption.label, yAxisOption.label)
});
return;
}
// determine the coordinates (+1 for both since 0 positions are reserved)
let x = xAxisValues.indexOf(xValue) + 1;
let y = yAxisValues.indexOf(yValue) + 1;
if (x < 1 || y < 1) {
missingData.push({
id: e.id,
name: e.displayName,
reason: this._createMissingDataMsgForCoordinates(x, y, xValue, yValue, xAxisOption.label, yAxisOption.label)
});
return;
}
// determine view model for the label
const itemViewModel = this._getViewModel(viewOption, additionalData);
if (!itemViewModel || !itemViewModel.inLegend) {
missingData.push({
id: e.id,
name: e.displayName,
reason: this._createMissingDataMsgForIVMs(viewOption, itemViewModel ? itemViewModel.inLegend : true)
});
return;
}
matrixDataAvailable = true;
matrixData[y][x].push({
id: id,
name: e.displayName,
viewModel: itemViewModel
});
});
lx.hideSpinner();
this.setState({
legendData: legendData,
matrixData: matrixData,
matrixDataAvailable: matrixDataAvailable,
missingData: missingData,
loadingState: LOADING_SUCCESSFUL
});
// everytime save the state, b/c this method is called, when something
// changes which needs to be published
this._publishStateToFramework();
}
_createMissingDataMsgForValues(xValue, yValue, xAxisName, yAxisName) {
if (!xValue && !yValue) {
return 'Values for ' + xAxisName + ' & '
+ yAxisName + ' are missing.';
}
if (!xValue) {
return 'Value for ' + xAxisName + ' is missing.';
} else {
return 'Value for ' + yAxisName + ' is missing.';
}
}
_createMissingDataMsgForCoordinates(x, y, xValue, yValue, xAxisName, yAxisName) {
if (x < 1 && y < 1) {
return 'Unknown values for ' + xAxisName + ' (' + xValue + ') & '
+ yAxisName + ' (' + yValue + ').';
}
if (x < 1) {
return 'Unknown value for ' + xAxisName + ' (' + xValue + ').';
} else {
return 'Unknown value for ' + yAxisName + ' (' + yValue + ').';
}
}
_createMissingDataMsgForIVMs(viewOption, inLegend) {
if (!inLegend) {
return 'Value for view is marked as hidden.';
}
return 'There are no values defined for the selected view (' + viewOption.label + ').';
}
_checkFieldType(type) {
switch (type) {
case 'LIFECYCLE':
case 'PROJECT_STATUS':
case 'TAG':
case 'SINGLE_SELECT':
return true;
default:
console.error('_checkFieldType: Unknown type "' + type + '", which can not be handled by this report!');
return false;
}
}
_getQueryAttribute(fieldName, type) {
switch (type) {
case 'LIFECYCLE':
case 'PROJECT_STATUS':
return fieldName + ' { asString }';
case 'TAG':
return 'tags { name }';
case 'SINGLE_SELECT':
return fieldName;
default:
console.error('_getQueryAttribute: Unknown type "' + type + '" of data field "' + fieldName + '"!');
return fieldName;
}
}
_getValue(option, additionalData) {
const index = this.index;
switch (option.type) {
case 'LIFECYCLE':
case 'PROJECT_STATUS':
const lifecycleData = additionalData[option.value];
if (!lifecycleData) {
return;
}
return lifecycleData.asString;
case 'SINGLE_SELECT':
const dataValue = additionalData[option.value];
if (!dataValue) {
return;
}
return dataValue;
case 'TAG':
const tags = index.getTagsFromGroup(additionalData, option.originalLabel);
if (tags.length === 0) {
return;
}
return tags[0].name;
default:
console.error('_getValue: Unknown type in "' + option.type + '" of data field "' + option.value + '"!');
return;
}
}
_getViewModel(viewOption, additionalData) {
const index = this.index;
const viewModel = this.reportState.viewModel;
switch (viewOption.type) {
case 'LIFECYCLE':
case 'PROJECT_STATUS':
const lifecycleData = additionalData[viewOption.value];
if (!lifecycleData) {
return viewModel['__missing__'];
}
return viewModel[lifecycleData.asString];
case 'SINGLE_SELECT':
const dataValue = additionalData[viewOption.value];
if (!dataValue) {
return viewModel['__missing__'];
}
return viewModel[dataValue];
case 'TAG':
const tags = index.getTagsFromGroup(additionalData, viewOption.originalLabel);
if (tags.length === 0) {
return viewModel['__missing__'];
}
return viewModel[tags[0].name];
default:
console.error('_getViewModel: Unknown type in "' + viewOption.type + '" of data field "' + viewOption.value + '"!');
return viewModel['__missing__'];
}
}
_getDataValues(option) {
const factsheetType = this.reportState.selectedFactsheetType;
const index = this.index;
const setup = this.setup;
switch (option.type) {
case 'LIFECYCLE':
case 'PROJECT_STATUS':
case 'SINGLE_SELECT':
return Utilities.getFrom(setup, 'settings.dataModel.factSheets.'
+ factsheetType + '.fields.' + option.value + '.values');
case 'TAG':
const tagGroup = index.tagGroups.byID[option.value];
if (!tagGroup) {
return [];
}
const tags = tagGroup.tags;
if (!tags) {
return [];
}
return tags.nodes.map((e) => {
return e.name;
});
default:
console.error('_getDataValues: Unknown type in "' + option.type + '" of data field "' + option.value + '"!');
return Utilities.getFrom(setup, 'settings.dataModel.factSheets.'
+ factsheetType + '.fields.' + option.value + '.values');
}
}
_handleViewSelect(val) {
const factsheetType = this.reportState.selectedFactsheetType;
const viewOption = this._getSelectedViewOption(factsheetType);
if (viewOption.value === val.value) {
return;
}
this.reportState.selectedView = val;
this._resetUIState();
this._getAndHandleAdditionalData();
}
_resetUIState() {
// do not reset all states!
this.setState({
loadingState: LOADING_NEW_DATA,
legendData: [],
matrixData: [],
matrixDataAvailable: false,
missingData: []
});
}
_handleXAxisSelect(val) {
const factsheetType = this.reportState.selectedFactsheetType;
const xAxisOption = this._getSelectedXAxisOption(factsheetType);
if (xAxisOption.value === val.value) {
return;
}
this.reportState.selectedXAxis = val;
this._resetUIState();
this._getAndHandleAdditionalData();
}
_handleYAxisSelect(val) {
const factsheetType = this.reportState.selectedFactsheetType;
const yAxisOption = this._getSelectedYAxisOption(factsheetType);
if (yAxisOption.value === val.value) {
return;
}
this.reportState.selectedYAxis = val;
this._resetUIState();
this._getAndHandleAdditionalData();
}
_handleDismissAlertButton() {
// set directly b/c 'setState' works async
this.state.showMissingDataWarning = false;
// publish call is special here, b/c this action doesn't trigger '_computeData'
this._publishStateToFramework();
// now trigger rendering
this.setState({
showMissingDataWarning: false
});
}
_handleConfig(forClose) {
if (forClose) {
// close or cancel: do not update values
return () => {
this.reportState.configStore = {};
this.setState({
showConfigure: false
});
};
} else {
// OK: update values
return () => {
const oldSFT = this.reportState.selectedFactsheetType;
this.reportState.selectedFactsheetType = this.reportState.configStore.factsheetType;
// set directly b/c 'setState' works async
this.state.showMissingDataWarning = this.reportState.configStore.showMissingDataWarning;
this.state.showEmptyRows = this.reportState.configStore.showEmptyRows;
this.state.showEmptyColumns = this.reportState.configStore.showEmptyColumns;
this.setState({
showConfigure: false
});
if (oldSFT === this.reportState.selectedFactsheetType) {
// publish call is special here, b/c this action doesn't trigger '_computeData'
this._publishStateToFramework();
return;
}
// reset all select states, b/c factsheet type changed
this.reportState.selectedView = null;
this.reportState.selectedXAxis = null;
this.reportState.selectedYAxis = null;
// update report config, this will trigger the facet callback automatically
lx.updateConfiguration(this._createConfig());
};
}
}
_handleFactsheetTypeSelect(val) {
if (this.reportState.configStore.factsheetType === val.value) {
return;
}
this.reportState.configStore.factsheetType = val.value;
this.forceUpdate();
}
_handleShowMissingDataWarningCheck(val) {
if (this.reportState.configStore.showMissingDataWarning === val) {
return;
}
this.reportState.configStore.showMissingDataWarning = val;
this.forceUpdate();
}
_handleShowEmptyRowsCheck(val) {
if (this.reportState.configStore.showEmptyRows === !val) {
return;
}
this.reportState.configStore.showEmptyRows = !val;
this.forceUpdate();
}
_handleShowEmptyColumnsCheck(val) {
if (this.reportState.configStore.showEmptyColumns === !val) {
return;
}
this.reportState.configStore.showEmptyColumns = !val;
this.forceUpdate();
}
_handleSwapAxes() {
const factsheetType = this.reportState.selectedFactsheetType;
const xAxisOption = this._getSelectedXAxisOption(factsheetType);
const yAxisOption = this._getSelectedYAxisOption(factsheetType);
this.reportState.selectedXAxis = yAxisOption;
this.reportState.selectedYAxis = xAxisOption;
this._computeData();
}
_getSelectedViewOption(factsheetType) {
if (!this.reportState.selectedView) {
// always fallback to the first one
return this.reportState.viewOptions[factsheetType][0];
}
return this.reportState.selectedView;
}
_getSelectedXAxisOption(factsheetType) {
if (!this.reportState.selectedXAxis) {
const viewOptions = this.reportState.viewOptions[factsheetType];
// view options have at least 2 elements, see '_initReport'
switch (viewOptions.length) {
case 2:
return viewOptions[0];
default:
return viewOptions[1];
}
}
return this.reportState.selectedXAxis;
}
_getSelectedYAxisOption(factsheetType) {
if (!this.reportState.selectedYAxis) {
const viewOptions = this.reportState.viewOptions[factsheetType];
// view options have at least 2 elements, see '_initReport'
// choose an option which is different from x-axis
switch (viewOptions.length) {
case 2:
return viewOptions[1];
default:
return viewOptions[2];
}
}
return this.reportState.selectedYAxis;
}
render() {
switch (this.state.loadingState) {
case LOADING_INIT:
return this._renderInit();
case LOADING_NEW_DATA:
return this._renderLoading();
case LOADING_SUCCESSFUL:
return this._renderSuccessful();
case LOADING_ERROR:
return this._renderError();
default:
throw new Error('Unknown loading state: ' + this.state.loadingState);
}
}
_renderInit() {
return (
<div>
{this._renderSelectFields()}
<h4 className='text-center' style={{ width: '100%' }}>Initialise report...</h4>
<div id='content' />
</div>
);
}
_renderLoading() {
return (
<div>
{this._renderSelectFields()}
<h4 className='text-center' style={{ width: '100%' }}>Loading data...</h4>
<div id='content' />
</div>
);
}
_renderError() {
return (<div id='content' />);
}
_renderSuccessful() {
const factsheetType = this.reportState.selectedFactsheetType;
return (
<div>
<ModalDialog show={this.state.showConfigure}
width='500px'
title='Configure'
content={this._renderConfigContent}
onClose={this._handleConfig(true)}
onOK={this._handleConfig(false)}
/>
{this._renderSelectFields()}
<MissingDataAlert
show={this.state.showMissingDataWarning}
missingData={this.state.missingData}
onClose={this._handleDismissAlertButton}
factsheetType={factsheetType}
setup={this.setup} />
<div id='content'>
<Legend items={this.state.legendData} itemWidth='150px' />
<Matrix setup={this.setup} cellWidth='180px'
factsheetType={factsheetType}
data={this.state.matrixData}
dataAvailable={this.state.matrixDataAvailable}
showEmptyRows={this.state.showEmptyRows}
showEmptyColumns={this.state.showEmptyColumns}
/>
</div>
</div>
);
}
_renderConfigContent() {
const options = this.reportState.factsheetModels.map((e) => {
return {
value: e,
label: lx.translateFactSheetType(e, 'plural')
};
});
return (
<div>
<SelectField id='factsheetType' label='Type'
options={options}
useSmallerFontSize
value={this.reportState.configStore.factsheetType}
onChange={this._handleFactsheetTypeSelect} />
<Checkbox id='showEmptyRows' label='Hide empty rows'
useSmallerFontSize
value={!this.reportState.configStore.showEmptyRows}
onChange={this._handleShowEmptyRowsCheck} />
<Checkbox id='showEmptyColumns' label='Hide empty columns'
useSmallerFontSize
value={!this.reportState.configStore.showEmptyColumns}
onChange={this._handleShowEmptyColumnsCheck} />
<Checkbox id='showMissingDataWarning' label='Show missing data warning'
useSmallerFontSize
value={this.reportState.configStore.showMissingDataWarning}
onChange={this._handleShowMissingDataWarningCheck} />
</div>
);
}
_renderSelectFields() {
const factsheetType = this.reportState.selectedFactsheetType;
let viewOptions = [];
let xAxisOptions = [];
let yAxisOptions = [];
let selectedViewOption = undefined;
let selectedXAxisOption = undefined;
let selectedYAxisOption = undefined;
if (factsheetType) {
viewOptions = this.reportState.viewOptions[factsheetType];
selectedViewOption = this._getSelectedViewOption(factsheetType).value;
selectedXAxisOption = this._getSelectedXAxisOption(factsheetType).value;
selectedYAxisOption = this._getSelectedYAxisOption(factsheetType).value;
xAxisOptions = Utilities.copyArray(viewOptions).filter((e) => {
// remove selected options from y axis options
return e.value !== selectedYAxisOption;
});
yAxisOptions = Utilities.copyArray(viewOptions).filter((e) => {
// remove selected options from x axis options
return e.value !== selectedXAxisOption;
});
}
return (
<div>
<span style={SELECT_FIELD_STYLE}>
<SelectField id='view' label='View' options={viewOptions} useSmallerFontSize
value={selectedViewOption} onChange={viewOptions && viewOptions.length === 0 ? undefined : this._handleViewSelect} />
</span>
<span style={SELECT_FIELD_STYLE}>
<SelectField id='x-axis' label='X-Axis' options={xAxisOptions} useSmallerFontSize
value={selectedXAxisOption} onChange={xAxisOptions && xAxisOptions.length === 0 ? undefined : this._handleXAxisSelect} />
</span>
<span style={SWAP_BUTTON_STYLE}>
<button type='button' className='btn btn-default btn-xs'
aria-label='Swap axes' title='Swap axes'
disabled={(xAxisOptions && xAxisOptions.length < 1) || (yAxisOptions && yAxisOptions.length < 1)}
onClick={this._handleSwapAxes}
>
<span className='glyphicon glyphicon-retweet' aria-hidden='true' />
<span className='sr-only'>Swap axes</span>
</button>
</span>
<span style={SELECT_FIELD_STYLE}>
<SelectField id='y-axis' label='Y-Axis' options={yAxisOptions} useSmallerFontSize
value={selectedYAxisOption} onChange={yAxisOptions && yAxisOptions.length === 0 ? undefined : this._handleYAxisSelect} />
</span>
</div>
);
}
}
export default Report;
|
src/components/listen/soundPlayerContainer.js | cannoneyed/tmm-glare | import React from 'react'
import { stopAllOther, addToPlayedStore } from './utils/audioStore.js'
import { connect } from 'react-redux'
import * as listenActions from 'src/core/listen'
import { getNextUnlockedTrack } from 'src/core/selectors/listen'
let { PropTypes, Component } = React
class SoundPlayerContainer extends Component {
constructor(props, context) {
super(props, context)
}
componentDidMount() {
const { soundCloudAudio } = this.props
// https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
soundCloudAudio.on('playing', this.onAudioStarted)
soundCloudAudio.on('timeupdate', this.setCurrentTime)
soundCloudAudio.on('loadedmetadata', this.setDuration)
soundCloudAudio.on('seeking', this.onSeekingTrack)
soundCloudAudio.on('seeked', this.onSeekedTrack)
soundCloudAudio.on('pause', this.onAudioPaused)
soundCloudAudio.on('ended', this.onAudioEnded)
}
componentWillReceiveProps(nextProps) {
const {
resolveUrl,
setPlaylist,
soundCloudAudio,
} = this.props
const playedBefore = this.props.playing
function restartIfPlayed() {
if (playedBefore) {
soundCloudAudio.play()
}
}
if (resolveUrl !== nextProps.resolveUrl) {
soundCloudAudio.stop()
soundCloudAudio.resolve(nextProps.resolveUrl, (data) => {
setPlaylist(data)
restartIfPlayed()
})
}
}
componentWillUnmount() {
this.props.soundCloudAudio.unbindAll()
}
onSeekingTrack = () => {
const { setSeeking } = this.props
setSeeking(true)
}
onSeekedTrack = () => {
const { setSeeking } = this.props
setSeeking(false)
}
onAudioStarted = () => {
const { soundCloudAudio, setPlaying } = this.props
setPlaying(true)
stopAllOther(soundCloudAudio.playing)
addToPlayedStore(soundCloudAudio)
}
onAudioPaused = () => {
const { setPlaying } = this.props
setPlaying(false)
}
onAudioEnded = () => {
let {
activeIndex,
getNextUnlockedTrack,
playTrackAtIndex,
setPlaying,
} = this.props
const nextUnlockedTrack = getNextUnlockedTrack(activeIndex)
if (nextUnlockedTrack === null) {
setPlaying(false)
} else {
playTrackAtIndex(nextUnlockedTrack)
}
}
setCurrentTime = () => {
const { soundCloudAudio, setTime } = this.props
setTime(soundCloudAudio.audio.currentTime)
}
setDuration = () => {
const { soundCloudAudio, setDuration } = this.props
setDuration(soundCloudAudio.audio.duration)
}
wrapChild = (child) => {
const { soundCloudAudio } = this.props
const newProps = Object.assign({}, {
soundCloudAudio,
}, this.props)
return React.cloneElement(child, newProps)
}
render() {
const { children } = this.props
if (!children) {
return null
}
if (!Array.isArray(children)) {
const child = children
return this.wrapChild(child)
} else {
return (
<span>
{React.Children.map(children, this.wrapChild)}
</span>
)
}
}
}
SoundPlayerContainer.propTypes = {
activeIndex: PropTypes.number.isRequired,
children: PropTypes.node,
clientId: PropTypes.string,
currentTime: PropTypes.number.isRequired,
duration: PropTypes.number.isRequired,
getNextUnlockedTrack: PropTypes.func.isRequired,
playTrackAtIndex: PropTypes.func.isRequired,
playing: PropTypes.bool.isRequired,
playlist: PropTypes.object,
resolveUrl: PropTypes.string,
seeking: PropTypes.bool.isRequired,
setDuration: PropTypes.func.isRequired,
setPlaying: PropTypes.func.isRequired,
setPlaylist: PropTypes.func.isRequired,
setSeeking: PropTypes.func.isRequired,
setTime: PropTypes.func.isRequired,
soundCloudAudio: PropTypes.object,
streamUrl: PropTypes.string,
}
export default connect(state => ({
...state.listen,
getNextUnlockedTrack: getNextUnlockedTrack(state),
}), listenActions)(SoundPlayerContainer)
|
src/MixMenu/MixMenu.js | znewton/myxx-client | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import './MixMenu.scss';
import Mix from './Mix/Mix.js';
import ClassNameBuilder from '../lib/ClassNameBuilder/ClassNameBuilder';
export default class MixMenu extends Component {
constructor () {
super();
this.state = {
mixes: [],
searchTerm: ''
};
}
/**
* Life-cycle functions
*/
componentDidMount() {
if (firebase.auth().currentUser) {
this.setUpList();
}
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setUpList();
} else {
this.setState({mixes: []});
}
});
}
render () {
let classNameBuilder = new ClassNameBuilder('MixMenu');
classNameBuilder.add('open', this.props.open);
classNameBuilder.add('part-open', this.props.partialOpen);
return (
<div className={classNameBuilder.className}>
{this.state.mixes.length > 0 &&
<div className="mix-search-wrapper">
<input
name="mixes-search"
placeholder="Search mixes..."
type="string"
className="search"
value={this.state.searchTerm}
onChange={this.handleSearchChange.bind(this)} />
<span className="material-icons searchIcon">search</span>
</div>
}
<div className="mixes-wrapper">
{this.mixes()}
</div>
</div>
);
}
/**
* Miscellaneous Functions
*/
mixComparator(a,b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
/**
* Build the list of user mixes.
*/
setUpList() {
let mixesRef = firebase.database().ref(`/mixes/${firebase.auth().currentUser.uid}`);
mixesRef.on('child_added', data => {
let mixes = this.state.mixes;
let mix = data.val();
mix.id = data.key;
mixes.unshift(mix);
mixes.sort(this.mixComparator);
this.setState({mixes});
});
mixesRef.on('child_changed', data => {
let mixes = this.state.mixes;
let mix = data.val();
mix.id = data.key;
let index = mixes.findIndex((m) => m.id === data.key);
mixes.splice(index, 1);
mixes.unshift(mix);
mixes.sort(this.mixComparator);
this.setState({mixes});
});
mixesRef.on('child_removed', data => {
let mixes = this.state.mixes;
let index = mixes.findIndex((m) => m.id === data.key);
mixes.splice(index, 1);
this.setState({mixes});
});
mixesRef.orderByChild('name').once('value', snapshot => {
let mixes = [];
snapshot.forEach(childSnapshot => {
let mix = childSnapshot.val();
mix.id = childSnapshot.key;
mixes.unshift(mix);
});
mixes.sort(this.mixComparator);
this.setState({mixes});
});
}
/**
* Update the search term on input.
*
* @param {Object} event
*/
handleSearchChange(event) {
this.setState({searchTerm: event.target.value.toLowerCase()});
}
/**
* Build the mix react elements, filtering by serach term.
*
* @return {Object[]}
*/
mixes() {
let mixes = this.state.searchTerm ?
this.state.mixes : this.state.mixes
.filter(mix =>
mix.name.toLowerCase().includes(this.state.searchTerm) ||
mix.channels.filter(channel => channel.toLowerCase().includes(this.state.searchTerm)).length);
return mixes.map(mix => (
<Mix
key={mix.id}
id={mix.id}
onClick={() => this.props.onSelect(mix.id)}
onEdit={(e) => this.props.onEdit(e, 'edit', mix.id)}
onDelete={(e) => this.props.onDelete(e, 'delete', mix.id)}
name={mix.name}
channels={mix.channels}
selected={mix.id === this.props.activeMix}
/>
));
}
}
MixMenu.propTypes = {
activeMix: PropTypes.string,
onSelect: PropTypes.func,
open: PropTypes.bool,
partialOpen: PropTypes.bool,
onEdit: PropTypes.func,
onDelete: PropTypes.func,
};
MixMenu.defaultProps = {
onSelect: () => {}
};
|
admin/client/App/screens/Item/components/FooterBar.js | pr1ntr/keystone | import React from 'react';
import blacklist from 'blacklist';
import assign from 'object-assign';
var FooterBar = React.createClass({
propTypes: {
style: React.PropTypes.object,
},
getDefaultProps () {
return {
style: {},
};
},
getInitialState () {
return {
position: 'relative',
width: 'auto',
height: 'auto',
top: 0,
};
},
componentDidMount () {
// Bail in IE8 because React doesn't support the onScroll event in that browser
// Conveniently (!) IE8 doesn't have window.getComputedStyle which we also use here
if (!window.getComputedStyle) return;
var footer = this.refs.footer;
this.windowSize = this.getWindowSize();
var footerStyle = window.getComputedStyle(footer);
this.footerSize = {
x: footer.offsetWidth,
y: footer.offsetHeight + parseInt(footerStyle.marginTop || '0'),
};
window.addEventListener('scroll', this.recalcPosition, false);
window.addEventListener('resize', this.recalcPosition, false);
this.recalcPosition();
},
componentWillUnmount () {
window.removeEventListener('scroll', this.recalcPosition, false);
window.removeEventListener('resize', this.recalcPosition, false);
},
getWindowSize () {
return {
x: window.innerWidth,
y: window.innerHeight,
};
},
recalcPosition () {
var wrapper = this.refs.wrapper;
this.footerSize.x = wrapper.offsetWidth;
var offsetTop = 0;
var offsetEl = wrapper;
while (offsetEl) {
offsetTop += offsetEl.offsetTop;
offsetEl = offsetEl.offsetParent;
}
var maxY = offsetTop + this.footerSize.y;
var viewY = window.scrollY + window.innerHeight;
var newSize = this.getWindowSize();
var sizeChanged = (newSize.x !== this.windowSize.x || newSize.y !== this.windowSize.y);
this.windowSize = newSize;
var newState = {
width: this.footerSize.x,
height: this.footerSize.y,
};
if (viewY > maxY && (sizeChanged || this.mode !== 'inline')) {
this.mode = 'inline';
newState.top = 0;
newState.position = 'absolute';
this.setState(newState);
} else if (viewY <= maxY && (sizeChanged || this.mode !== 'fixed')) {
this.mode = 'fixed';
newState.top = window.innerHeight - this.footerSize.y;
newState.position = 'fixed';
this.setState(newState);
}
},
render () {
var wrapperStyle = {
height: this.state.height,
marginTop: 60,
position: 'relative',
};
var footerProps = blacklist(this.props, 'children', 'style');
var footerStyle = assign({}, this.props.style, {
position: this.state.position,
top: this.state.top,
width: this.state.width,
height: this.state.height,
});
return (
<div ref="wrapper" style={wrapperStyle}>
<div ref="footer" style={footerStyle} {...footerProps}>{this.props.children}</div>
</div>
);
},
});
module.exports = FooterBar;
|
packages/material-ui-icons/src/SettingsVoiceRounded.js | allanalexandre/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 24h2v-2H7v2zm5-11c1.66 0 2.99-1.34 2.99-3L15 4c0-1.66-1.34-3-3-3S9 2.34 9 4v6c0 1.66 1.34 3 3 3zm-1 11h2v-2h-2v2zm4 0h2v-2h-2v2zm3.08-14c-.42 0-.77.3-.83.71-.37 2.61-2.72 4.39-5.25 4.39s-4.88-1.77-5.25-4.39c-.06-.41-.42-.71-.83-.71-.52 0-.92.46-.85.97.46 2.96 2.96 5.3 5.93 5.75V19c0 .55.45 1 1 1s1-.45 1-1v-2.28c2.96-.44 5.47-2.79 5.93-5.75.07-.51-.33-.97-.85-.97z" /></React.Fragment>
, 'SettingsVoiceRounded');
|
app/main.js | longgame/koa-react-demo | import React from 'react';
import { render } from 'react-dom';
import { Router, Route, Link } from 'react-router';
import './styles/main.scss';
import Counter from './components/Counter';
import TodoList from './components/TodoList';
import About from './components/About';
import Navbar from './components/Navbar';
import { LoginForm, RegistrationForm } from './components/Forms';
class App extends React.Component {
render() {
return (
<div id='app'>
<div id='app-header'>
<Navbar />
</div>
<div id='app-body'>
{ this.props.children }
</div>
<div id='app-footer'>
</div>
</div>
);
}
}
var routes = (
<Router>
<Route component={App}>
<Route path='/' component={TodoList}>
<Route path='/all' />
<Route path='/active' />
<Route path='/complete' />
</Route>
<Route path='/about' component={About} />
<Route path='/login' component={LoginForm} />
<Route path='/register' component={RegistrationForm} />
</Route>
</Router>
);
render(routes, document.getElementById('content'));
|
src/components/AutoComplete/AutoCompleteList.js | mrc535s/react-autocomplete | import React from 'react';
import AutoCompleteListItem from './AutoCompleteListItem';
export default class AutoCompleteList extends React.Component {
constructor(props) {
super(props);
}
render() {
const styles = {
borderRight: 'solid 1px grey',
borderLeft: 'solid 1px grey',
borderBottom: 'solid 1px grey',
width: '155px',
padding: "1px",
margin: 0,
height: 'auto',
listStyle: 'none'
};
const itemsExist = this.props.items && this.props.items.length;
const listStyle = itemsExist > 0 ? styles : {};
const listItems = itemsExist > 0 ? this.props.items.map((item) =>
<AutoCompleteListItem key={item.key} item={item} hoveredItem = {this.props.hoveredItem} handleItemSelect={this.props.handleItemSelect}
handleItemMouseHover = {this.props.handleItemMouseHover}/>
) : '';
return (
<ul style={listStyle}>
{listItems}
</ul>
);
}
} |
lib-module/layout/DefaultLayout.js | turacojs/fody | import React from 'react';
import { Html, Head, Body } from './index';
export default (function (_ref) {
var helmet = _ref.helmet,
content = _ref.content;
return React.createElement(
Html,
{ helmet: helmet },
React.createElement(Head, { helmet: helmet }),
React.createElement(
Body,
null,
React.createElement('div', { id: 'app', dangerouslySetInnerHTML: { __html: content } })
)
);
});
//# sourceMappingURL=DefaultLayout.js.map |
third_party/seasocks/src/main/web/_jquery.min.js | FRC1296/CheezyDriver2016 | /*!
* jQuery JavaScript Library v1.5.2
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu Mar 31 15:28:23 2011 -0400
*/
(function(a,b){function ci(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cf(a){if(!b_[a]){var b=d("<"+a+">").appendTo("body"),c=b.css("display");b.remove();if(c==="none"||c==="")c="block";b_[a]=c}return b_[a]}function ce(a,b){var c={};d.each(cd.concat.apply([],cd.slice(0,b)),function(){c[this]=a});return c}function b$(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function bZ(){try{return new a.XMLHttpRequest}catch(b){}}function bY(){d(a).unload(function(){for(var a in bW)bW[a](0,1)})}function bS(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var e=a.dataTypes,f={},g,h,i=e.length,j,k=e[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h==="string"&&(f[h.toLowerCase()]=a.converters[h]);l=k,k=e[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=f[m]||f["* "+k];if(!n){p=b;for(o in f){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=f[j[1]+" "+k];if(p){o=f[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&d.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bR(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bQ(a,b,c,e){if(d.isArray(b)&&b.length)d.each(b,function(b,f){c||bs.test(a)?e(a,f):bQ(a+"["+(typeof f==="object"||d.isArray(f)?b:"")+"]",f,c,e)});else if(c||b==null||typeof b!=="object")e(a,b);else if(d.isArray(b)||d.isEmptyObject(b))e(a,"");else for(var f in b)bQ(a+"["+f+"]",b[f],c,e)}function bP(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bJ,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l==="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bP(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bP(a,c,d,e,"*",g));return l}function bO(a){return function(b,c){typeof b!=="string"&&(c=b,b="*");if(d.isFunction(c)){var e=b.toLowerCase().split(bD),f=0,g=e.length,h,i,j;for(;f<g;f++)h=e[f],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bq(a,b,c){var e=b==="width"?bk:bl,f=b==="width"?a.offsetWidth:a.offsetHeight;if(c==="border")return f;d.each(e,function(){c||(f-=parseFloat(d.css(a,"padding"+this))||0),c==="margin"?f+=parseFloat(d.css(a,"margin"+this))||0:f-=parseFloat(d.css(a,"border"+this+"Width"))||0});return f}function bc(a,b){b.src?d.ajax({url:b.src,async:!1,dataType:"script"}):d.globalEval(b.text||b.textContent||b.innerHTML||""),b.parentNode&&b.parentNode.removeChild(b)}function bb(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function ba(a,b){if(b.nodeType===1){var c=b.nodeName.toLowerCase();b.clearAttributes(),b.mergeAttributes(a);if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(d.expando)}}function _(a,b){if(b.nodeType===1&&d.hasData(a)){var c=d.expando,e=d.data(a),f=d.data(b,e);if(e=e[c]){var g=e.events;f=f[c]=d.extend({},e);if(g){delete f.handle,f.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)d.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function $(a,b){return d.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Q(a,b,c){if(d.isFunction(b))return d.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return d.grep(a,function(a,d){return a===b===c});if(typeof b==="string"){var e=d.grep(a,function(a){return a.nodeType===1});if(L.test(b))return d.filter(b,e,!c);b=d.filter(b,e)}return d.grep(a,function(a,e){return d.inArray(a,b)>=0===c})}function P(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function H(a,b){return(a&&a!=="*"?a+".":"")+b.replace(t,"`").replace(u,"&")}function G(a){var b,c,e,f,g,h,i,j,k,l,m,n,o,p=[],q=[],s=d._data(this,"events");if(a.liveFired!==this&&s&&s.live&&!a.target.disabled&&(!a.button||a.type!=="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var t=s.live.slice(0);for(i=0;i<t.length;i++)g=t[i],g.origType.replace(r,"")===a.type?q.push(g.selector):t.splice(i--,1);f=d(a.target).closest(q,a.currentTarget);for(j=0,k=f.length;j<k;j++){m=f[j];for(i=0;i<t.length;i++){g=t[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,e=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,e=d(a.relatedTarget).closest(g.selector)[0];(!e||e!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){f=p[j];if(c&&f.level>c)break;a.currentTarget=f.elem,a.data=f.handleObj.data,a.handleObj=f.handleObj,o=f.handleObj.origHandler.apply(f.elem,arguments);if(o===!1||a.isPropagationStopped()){c=f.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function E(a,c,e){var f=d.extend({},e[0]);f.type=a,f.originalEvent={},f.liveFired=b,d.event.handle.call(c,f),f.isDefaultPrevented()&&e[0].preventDefault()}function y(){return!0}function x(){return!1}function i(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function h(a,c,e){if(e===b&&a.nodeType===1){e=a.getAttribute("data-"+c);if(typeof e==="string"){try{e=e==="true"?!0:e==="false"?!1:e==="null"?null:d.isNaN(e)?g.test(e)?d.parseJSON(e):e:parseFloat(e)}catch(f){}d.data(a,c,e)}else e=b}return e}var c=a.document,d=function(){function G(){if(!d.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(G,1);return}d.ready()}}var d=function(a,b){return new d.fn.init(a,b,g)},e=a.jQuery,f=a.$,g,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,i=/\S/,j=/^\s+/,k=/\s+$/,l=/\d/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=navigator.userAgent,w,x,y,z=Object.prototype.toString,A=Object.prototype.hasOwnProperty,B=Array.prototype.push,C=Array.prototype.slice,D=String.prototype.trim,E=Array.prototype.indexOf,F={};d.fn=d.prototype={constructor:d,init:function(a,e,f){var g,i,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!e&&c.body){this.context=c,this[0]=c.body,this.selector="body",this.length=1;return this}if(typeof a==="string"){g=h.exec(a);if(!g||!g[1]&&e)return!e||e.jquery?(e||f).find(a):this.constructor(e).find(a);if(g[1]){e=e instanceof d?e[0]:e,k=e?e.ownerDocument||e:c,j=m.exec(a),j?d.isPlainObject(e)?(a=[c.createElement(j[1])],d.fn.attr.call(a,e,!0)):a=[k.createElement(j[1])]:(j=d.buildFragment([g[1]],[k]),a=(j.cacheable?d.clone(j.fragment):j.fragment).childNodes);return d.merge(this,a)}i=c.getElementById(g[2]);if(i&&i.parentNode){if(i.id!==g[2])return f.find(a);this.length=1,this[0]=i}this.context=c,this.selector=a;return this}if(d.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return d.makeArray(a,this)},selector:"",jquery:"1.5.2",length:0,size:function(){return this.length},toArray:function(){return C.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var e=this.constructor();d.isArray(a)?B.apply(e,a):d.merge(e,a),e.prevObject=this,e.context=this.context,b==="find"?e.selector=this.selector+(this.selector?" ":"")+c:b&&(e.selector=this.selector+"."+b+"("+c+")");return e},each:function(a,b){return d.each(this,a,b)},ready:function(a){d.bindReady(),x.done(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(C.apply(this,arguments),"slice",C.call(arguments).join(","))},map:function(a){return this.pushStack(d.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:B,sort:[].sort,splice:[].splice},d.fn.init.prototype=d.fn,d.extend=d.fn.extend=function(){var a,c,e,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i==="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!=="object"&&!d.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){e=i[c],f=a[c];if(i===f)continue;l&&f&&(d.isPlainObject(f)||(g=d.isArray(f)))?(g?(g=!1,h=e&&d.isArray(e)?e:[]):h=e&&d.isPlainObject(e)?e:{},i[c]=d.extend(l,h,f)):f!==b&&(i[c]=f)}return i},d.extend({noConflict:function(b){a.$=f,b&&(a.jQuery=e);return d},isReady:!1,readyWait:1,ready:function(a){a===!0&&d.readyWait--;if(!d.readyWait||a!==!0&&!d.isReady){if(!c.body)return setTimeout(d.ready,1);d.isReady=!0;if(a!==!0&&--d.readyWait>0)return;x.resolveWith(c,[d]),d.fn.trigger&&d(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!x){x=d._Deferred();if(c.readyState==="complete")return setTimeout(d.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",y,!1),a.addEventListener("load",d.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",y),a.attachEvent("onload",d.ready);var b=!1;try{b=a.frameElement==null}catch(e){}c.documentElement.doScroll&&b&&G()}}},isFunction:function(a){return d.type(a)==="function"},isArray:Array.isArray||function(a){return d.type(a)==="array"},isWindow:function(a){return a&&typeof a==="object"&&"setInterval"in a},isNaN:function(a){return a==null||!l.test(a)||isNaN(a)},type:function(a){return a==null?String(a):F[z.call(a)]||"object"},isPlainObject:function(a){if(!a||d.type(a)!=="object"||a.nodeType||d.isWindow(a))return!1;if(a.constructor&&!A.call(a,"constructor")&&!A.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a){}return c===b||A.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!=="string"||!b)return null;b=d.trim(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return a.JSON&&a.JSON.parse?a.JSON.parse(b):(new Function("return "+b))();d.error("Invalid JSON: "+b)},parseXML:function(b,c,e){a.DOMParser?(e=new DOMParser,c=e.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),e=c.documentElement,(!e||!e.nodeName||e.nodeName==="parsererror")&&d.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(a){if(a&&i.test(a)){var b=c.head||c.getElementsByTagName("head")[0]||c.documentElement,e=c.createElement("script");d.support.scriptEval()?e.appendChild(c.createTextNode(a)):e.text=a,b.insertBefore(e,b.firstChild),b.removeChild(e)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,e){var f,g=0,h=a.length,i=h===b||d.isFunction(a);if(e){if(i){for(f in a)if(c.apply(a[f],e)===!1)break}else for(;g<h;)if(c.apply(a[g++],e)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(var j=a[0];g<h&&c.call(j,g,j)!==!1;j=a[++g]){}return a},trim:D?function(a){return a==null?"":D.call(a)}:function(a){return a==null?"":(a+"").replace(j,"").replace(k,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var e=d.type(a);a.length==null||e==="string"||e==="function"||e==="regexp"||d.isWindow(a)?B.call(c,a):d.merge(c,a)}return c},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length==="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,b,c){var d=[],e;for(var f=0,g=a.length;f<g;f++)e=b(a[f],f,c),e!=null&&(d[d.length]=e);return d.concat.apply([],d)},guid:1,proxy:function(a,c,e){arguments.length===2&&(typeof c==="string"?(e=a,a=e[c],c=b):c&&!d.isFunction(c)&&(e=c,c=b)),!c&&a&&(c=function(){return a.apply(e||this,arguments)}),a&&(c.guid=a.guid=a.guid||c.guid||d.guid++);return c},access:function(a,c,e,f,g,h){var i=a.length;if(typeof c==="object"){for(var j in c)d.access(a,j,c[j],f,g,e);return a}if(e!==b){f=!h&&f&&d.isFunction(e);for(var k=0;k<i;k++)g(a[k],c,f?e.call(a[k],k,g(a[k],c)):e,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}d.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.subclass=this.subclass,a.fn.init=function b(b,c){c&&c instanceof d&&!(c instanceof a)&&(c=a(c));return d.fn.init.call(this,b,c,e)},a.fn.init.prototype=a.fn;var e=a(c);return a},browser:{}}),d.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){F["[object "+b+"]"]=b.toLowerCase()}),w=d.uaMatch(v),w.browser&&(d.browser[w.browser]=!0,d.browser.version=w.version),d.browser.webkit&&(d.browser.safari=!0),E&&(d.inArray=function(a,b){return E.call(b,a)}),i.test(" ")&&(j=/^[\s\xA0]+/,k=/[\s\xA0]+$/),g=d(c),c.addEventListener?y=function(){c.removeEventListener("DOMContentLoaded",y,!1),d.ready()}:c.attachEvent&&(y=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",y),d.ready())});return d}(),e="then done fail isResolved isRejected promise".split(" "),f=[].slice;d.extend({_Deferred:function(){var a=[],b,c,e,f={done:function(){if(!e){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=d.type(i),j==="array"?f.done.apply(f,i):j==="function"&&a.push(i);k&&f.resolveWith(k[0],k[1])}return this},resolveWith:function(d,f){if(!e&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(d,f)}finally{b=[d,f],c=0}}return this},resolve:function(){f.resolveWith(this,arguments);return this},isResolved:function(){return c||b},cancel:function(){e=1,a=[];return this}};return f},Deferred:function(a){var b=d._Deferred(),c=d._Deferred(),f;d.extend(b,{then:function(a,c){b.done(a).fail(c);return this},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,promise:function(a){if(a==null){if(f)return f;f=a={}}var c=e.length;while(c--)a[e[c]]=b[e[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?f.call(arguments,0):c,--g||h.resolveWith(h,f.call(b,0))}}var b=arguments,c=0,e=b.length,g=e,h=e<=1&&a&&d.isFunction(a.promise)?a:d.Deferred();if(e>1){for(;c<e;c++)b[c]&&d.isFunction(b[c].promise)?b[c].promise().then(i(c),h.reject):--g;g||h.resolveWith(h,b)}else h!==a&&h.resolveWith(h,e?[a]:[]);return h.promise()}}),function(){d.support={};var b=c.createElement("div");b.style.display="none",b.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=b.getElementsByTagName("*"),f=b.getElementsByTagName("a")[0],g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=b.getElementsByTagName("input")[0];if(e&&e.length&&f){d.support={leadingWhitespace:b.firstChild.nodeType===3,tbody:!b.getElementsByTagName("tbody").length,htmlSerialize:!!b.getElementsByTagName("link").length,style:/red/.test(f.getAttribute("style")),hrefNormalized:f.getAttribute("href")==="/a",opacity:/^0.55$/.test(f.style.opacity),cssFloat:!!f.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,deleteExpando:!0,optDisabled:!1,checkClone:!1,noCloneEvent:!0,noCloneChecked:!0,boxModel:null,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableHiddenOffsets:!0,reliableMarginRight:!0},i.checked=!0,d.support.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,d.support.optDisabled=!h.disabled;var j=null;d.support.scriptEval=function(){if(j===null){var b=c.documentElement,e=c.createElement("script"),f="script"+d.now();try{e.appendChild(c.createTextNode("window."+f+"=1;"))}catch(g){}b.insertBefore(e,b.firstChild),a[f]?(j=!0,delete a[f]):j=!1,b.removeChild(e)}return j};try{delete b.test}catch(k){d.support.deleteExpando=!1}!b.addEventListener&&b.attachEvent&&b.fireEvent&&(b.attachEvent("onclick",function l(){d.support.noCloneEvent=!1,b.detachEvent("onclick",l)}),b.cloneNode(!0).fireEvent("onclick")),b=c.createElement("div"),b.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var m=c.createDocumentFragment();m.appendChild(b.firstChild),d.support.checkClone=m.cloneNode(!0).cloneNode(!0).lastChild.checked,d(function(){var a=c.createElement("div"),b=c.getElementsByTagName("body")[0];if(b){a.style.width=a.style.paddingLeft="1px",b.appendChild(a),d.boxModel=d.support.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,d.support.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",d.support.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";var e=a.getElementsByTagName("td");d.support.reliableHiddenOffsets=e[0].offsetHeight===0,e[0].style.display="",e[1].style.display="none",d.support.reliableHiddenOffsets=d.support.reliableHiddenOffsets&&e[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(a.style.width="1px",a.style.marginRight="0",d.support.reliableMarginRight=(parseInt(c.defaultView.getComputedStyle(a,null).marginRight,10)||0)===0),b.removeChild(a).style.display="none",a=e=null}});var n=function(a){var b=c.createElement("div");a="on"+a;if(!b.attachEvent)return!0;var d=a in b;d||(b.setAttribute(a,"return;"),d=typeof b[a]==="function");return d};d.support.submitBubbles=n("submit"),d.support.changeBubbles=n("change"),b=e=f=null}}();var g=/^(?:\{.*\}|\[.*\])$/;d.extend({cache:{},uuid:0,expando:"jQuery"+(d.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?d.cache[a[d.expando]]:a[d.expando];return!!a&&!i(a)},data:function(a,c,e,f){if(d.acceptData(a)){var g=d.expando,h=typeof c==="string",i,j=a.nodeType,k=j?d.cache:a,l=j?a[d.expando]:a[d.expando]&&d.expando;if((!l||f&&l&&!k[l][g])&&h&&e===b)return;l||(j?a[d.expando]=l=++d.uuid:l=d.expando),k[l]||(k[l]={},j||(k[l].toJSON=d.noop));if(typeof c==="object"||typeof c==="function")f?k[l][g]=d.extend(k[l][g],c):k[l]=d.extend(k[l],c);i=k[l],f&&(i[g]||(i[g]={}),i=i[g]),e!==b&&(i[c]=e);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[c]:i}},removeData:function(b,c,e){if(d.acceptData(b)){var f=d.expando,g=b.nodeType,h=g?d.cache:b,j=g?b[d.expando]:d.expando;if(!h[j])return;if(c){var k=e?h[j][f]:h[j];if(k){delete k[c];if(!i(k))return}}if(e){delete h[j][f];if(!i(h[j]))return}var l=h[j][f];d.support.deleteExpando||h!=a?delete h[j]:h[j]=null,l?(h[j]={},g||(h[j].toJSON=d.noop),h[j][f]=l):g&&(d.support.deleteExpando?delete b[d.expando]:b.removeAttribute?b.removeAttribute(d.expando):b[d.expando]=null)}},_data:function(a,b,c){return d.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=d.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),d.fn.extend({data:function(a,c){var e=null;if(typeof a==="undefined"){if(this.length){e=d.data(this[0]);if(this[0].nodeType===1){var f=this[0].attributes,g;for(var i=0,j=f.length;i<j;i++)g=f[i].name,g.indexOf("data-")===0&&(g=g.substr(5),h(this[0],g,e[g]))}}return e}if(typeof a==="object")return this.each(function(){d.data(this,a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(c===b){e=this.triggerHandler("getData"+k[1]+"!",[k[0]]),e===b&&this.length&&(e=d.data(this[0],a),e=h(this[0],a,e));return e===b&&k[1]?this.data(k[0]):e}return this.each(function(){var b=d(this),e=[k[0],c];b.triggerHandler("setData"+k[1]+"!",e),d.data(this,a,c),b.triggerHandler("changeData"+k[1]+"!",e)})},removeData:function(a){return this.each(function(){d.removeData(this,a)})}}),d.extend({queue:function(a,b,c){if(a){b=(b||"fx")+"queue";var e=d._data(a,b);if(!c)return e||[];!e||d.isArray(c)?e=d._data(a,b,d.makeArray(c)):e.push(c);return e}},dequeue:function(a,b){b=b||"fx";var c=d.queue(a,b),e=c.shift();e==="inprogress"&&(e=c.shift()),e&&(b==="fx"&&c.unshift("inprogress"),e.call(a,function(){d.dequeue(a,b)})),c.length||d.removeData(a,b+"queue",!0)}}),d.fn.extend({queue:function(a,c){typeof a!=="string"&&(c=a,a="fx");if(c===b)return d.queue(this[0],a);return this.each(function(b){var e=d.queue(this,a,c);a==="fx"&&e[0]!=="inprogress"&&d.dequeue(this,a)})},dequeue:function(a){return this.each(function(){d.dequeue(this,a)})},delay:function(a,b){a=d.fx?d.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){d.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var j=/[\n\t\r]/g,k=/\s+/,l=/\r/g,m=/^(?:href|src|style)$/,n=/^(?:button|input)$/i,o=/^(?:button|input|object|select|textarea)$/i,p=/^a(?:rea)?$/i,q=/^(?:radio|checkbox)$/i;d.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"},d.fn.extend({attr:function(a,b){return d.access(this,a,b,!0,d.attr)},removeAttr:function(a,b){return this.each(function(){d.attr(this,a,""),this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.addClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"){var b=(a||"").split(k);for(var c=0,e=this.length;c<e;c++){var f=this[c];if(f.nodeType===1)if(f.className){var g=" "+f.className+" ",h=f.className;for(var i=0,j=b.length;i<j;i++)g.indexOf(" "+b[i]+" ")<0&&(h+=" "+b[i]);f.className=d.trim(h)}else f.className=a}}return this},removeClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.removeClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"||a===b){var c=(a||"").split(k);for(var e=0,f=this.length;e<f;e++){var g=this[e];if(g.nodeType===1&&g.className)if(a){var h=(" "+g.className+" ").replace(j," ");for(var i=0,l=c.length;i<l;i++)h=h.replace(" "+c[i]+" "," ");g.className=d.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,e=typeof b==="boolean";if(d.isFunction(a))return this.each(function(c){var e=d(this);e.toggleClass(a.call(this,c,e.attr("class"),b),b)});return this.each(function(){if(c==="string"){var f,g=0,h=d(this),i=b,j=a.split(k);while(f=j[g++])i=e?i:!h.hasClass(f),h[i?"addClass":"removeClass"](f)}else if(c==="undefined"||c==="boolean")this.className&&d._data(this,"__className__",this.className),this.className=this.className||a===!1?"":d._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(j," ").indexOf(b)>-1)return!0;return!1},val:function(a){if(!arguments.length){var c=this[0];if(c){if(d.nodeName(c,"option")){var e=c.attributes.value;return!e||e.specified?c.value:c.text}if(d.nodeName(c,"select")){var f=c.selectedIndex,g=[],h=c.options,i=c.type==="select-one";if(f<0)return null;for(var j=i?f:0,k=i?f+1:h.length;j<k;j++){var m=h[j];if(m.selected&&(d.support.optDisabled?!m.disabled:m.getAttribute("disabled")===null)&&(!m.parentNode.disabled||!d.nodeName(m.parentNode,"optgroup"))){a=d(m).val();if(i)return a;g.push(a)}}if(i&&!g.length&&h.length)return d(h[f]).val();return g}if(q.test(c.type)&&!d.support.checkOn)return c.getAttribute("value")===null?"on":c.value;return(c.value||"").replace(l,"")}return b}var n=d.isFunction(a);return this.each(function(b){var c=d(this),e=a;if(this.nodeType===1){n&&(e=a.call(this,b,c.val())),e==null?e="":typeof e==="number"?e+="":d.isArray(e)&&(e=d.map(e,function(a){return a==null?"":a+""}));if(d.isArray(e)&&q.test(this.type))this.checked=d.inArray(c.val(),e)>=0;else if(d.nodeName(this,"select")){var f=d.makeArray(e);d("option",this).each(function(){this.selected=d.inArray(d(this).val(),f)>=0}),f.length||(this.selectedIndex=-1)}else this.value=e}})}}),d.extend({attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,e,f){if(!a||a.nodeType===3||a.nodeType===8||a.nodeType===2)return b;if(f&&c in d.attrFn)return d(a)[c](e);var g=a.nodeType!==1||!d.isXMLDoc(a),h=e!==b;c=g&&d.props[c]||c;if(a.nodeType===1){var i=m.test(c);if(c==="selected"&&!d.support.optSelected){var j=a.parentNode;j&&(j.selectedIndex,j.parentNode&&j.parentNode.selectedIndex)}if((c in a||a[c]!==b)&&g&&!i){h&&(c==="type"&&n.test(a.nodeName)&&a.parentNode&&d.error("type property can't be changed"),e===null?a.nodeType===1&&a.removeAttribute(c):a[c]=e);if(d.nodeName(a,"form")&&a.getAttributeNode(c))return a.getAttributeNode(c).nodeValue;if(c==="tabIndex"){var k=a.getAttributeNode("tabIndex");return k&&k.specified?k.value:o.test(a.nodeName)||p.test(a.nodeName)&&a.href?0:b}return a[c]}if(!d.support.style&&g&&c==="style"){h&&(a.style.cssText=""+e);return a.style.cssText}h&&a.setAttribute(c,""+e);if(!a.attributes[c]&&(a.hasAttribute&&!a.hasAttribute(c)))return b;var l=!d.support.hrefNormalized&&g&&i?a.getAttribute(c,2):a.getAttribute(c);return l===null?b:l}h&&(a[c]=e);return a[c]}});var r=/\.(.*)$/,s=/^(?:textarea|input|select)$/i,t=/\./g,u=/ /g,v=/[^\w\s.|`]/g,w=function(a){return a.replace(v,"\\$&")};d.event={add:function(c,e,f,g){if(c.nodeType!==3&&c.nodeType!==8){try{d.isWindow(c)&&(c!==a&&!c.frameElement)&&(c=a)}catch(h){}if(f===!1)f=x;else if(!f)return;var i,j;f.handler&&(i=f,f=i.handler),f.guid||(f.guid=d.guid++);var k=d._data(c);if(!k)return;var l=k.events,m=k.handle;l||(k.events=l={}),m||(k.handle=m=function(a){return typeof d!=="undefined"&&d.event.triggered!==a.type?d.event.handle.apply(m.elem,arguments):b}),m.elem=c,e=e.split(" ");var n,o=0,p;while(n=e[o++]){j=i?d.extend({},i):{handler:f,data:g},n.indexOf(".")>-1?(p=n.split("."),n=p.shift(),j.namespace=p.slice(0).sort().join(".")):(p=[],j.namespace=""),j.type=n,j.guid||(j.guid=f.guid);var q=l[n],r=d.event.special[n]||{};if(!q){q=l[n]=[];if(!r.setup||r.setup.call(c,g,p,m)===!1)c.addEventListener?c.addEventListener(n,m,!1):c.attachEvent&&c.attachEvent("on"+n,m)}r.add&&(r.add.call(c,j),j.handler.guid||(j.handler.guid=f.guid)),q.push(j),d.event.global[n]=!0}c=null}},global:{},remove:function(a,c,e,f){if(a.nodeType!==3&&a.nodeType!==8){e===!1&&(e=x);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=d.hasData(a)&&d._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(e=c.handler,c=c.type);if(!c||typeof c==="string"&&c.charAt(0)==="."){c=c||"";for(h in t)d.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+d.map(m.slice(0).sort(),w).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!e){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))d.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=d.event.special[h]||{};for(j=f||0;j<p.length;j++){q=p[j];if(e.guid===q.guid){if(l||n.test(q.namespace))f==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(f!=null)break}}if(p.length===0||f!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&d.removeEvent(a,h,s.handle),g=null,delete t[h]}if(d.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,d.isEmptyObject(s)&&d.removeData(a,b,!0)}}},trigger:function(a,c,e){var f=a.type||a,g=arguments[3];if(!g){a=typeof a==="object"?a[d.expando]?a:d.extend(d.Event(f),a):d.Event(f),f.indexOf("!")>=0&&(a.type=f=f.slice(0,-1),a.exclusive=!0),e||(a.stopPropagation(),d.event.global[f]&&d.each(d.cache,function(){var b=d.expando,e=this[b];e&&e.events&&e.events[f]&&d.event.trigger(a,c,e.handle.elem)}));if(!e||e.nodeType===3||e.nodeType===8)return b;a.result=b,a.target=e,c=d.makeArray(c),c.unshift(a)}a.currentTarget=e;var h=d._data(e,"handle");h&&h.apply(e,c);var i=e.parentNode||e.ownerDocument;try{e&&e.nodeName&&d.noData[e.nodeName.toLowerCase()]||e["on"+f]&&e["on"+f].apply(e,c)===!1&&(a.result=!1,a.preventDefault())}catch(j){}if(!a.isPropagationStopped()&&i)d.event.trigger(a,c,i,!0);else if(!a.isDefaultPrevented()){var k,l=a.target,m=f.replace(r,""),n=d.nodeName(l,"a")&&m==="click",o=d.event.special[m]||{};if((!o._default||o._default.call(e,a)===!1)&&!n&&!(l&&l.nodeName&&d.noData[l.nodeName.toLowerCase()])){try{l[m]&&(k=l["on"+m],k&&(l["on"+m]=null),d.event.triggered=a.type,l[m]())}catch(p){}k&&(l["on"+m]=k),d.event.triggered=b}}},handle:function(c){var e,f,g,h,i,j=[],k=d.makeArray(arguments);c=k[0]=d.event.fix(c||a.event),c.currentTarget=this,e=c.type.indexOf(".")<0&&!c.exclusive,e||(g=c.type.split("."),c.type=g.shift(),j=g.slice(0).sort(),h=new RegExp("(^|\\.)"+j.join("\\.(?:.*\\.)?")+"(\\.|$)")),c.namespace=c.namespace||j.join("."),i=d._data(this,"events"),f=(i||{})[c.type];if(i&&f){f=f.slice(0);for(var l=0,m=f.length;l<m;l++){var n=f[l];if(e||h.test(n.namespace)){c.handler=n.handler,c.data=n.data,c.handleObj=n;var o=n.handler.apply(this,k);o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}}return c.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 pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[d.expando])return a;var e=a;a=d.Event(e);for(var f=this.props.length,g;f;)g=this.props[--f],a[g]=e[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=c.documentElement,i=c.body;a.pageX=a.clientX+(h&&h.scrollLeft||i&&i.scrollLeft||0)-(h&&h.clientLeft||i&&i.clientLeft||0),a.pageY=a.clientY+(h&&h.scrollTop||i&&i.scrollTop||0)-(h&&h.clientTop||i&&i.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:d.proxy,special:{ready:{setup:d.bindReady,teardown:d.noop},live:{add:function(a){d.event.add(this,H(a.origType,a.selector),d.extend({},a,{handler:G,guid:a.handler.guid}))},remove:function(a){d.event.remove(this,H(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){d.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},d.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},d.Event=function(a){if(!this.preventDefault)return new d.Event(a);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?y:x):this.type=a,this.timeStamp=d.now(),this[d.expando]=!0},d.Event.prototype={preventDefault:function(){this.isDefaultPrevented=y;var a=this.originalEvent;a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=y;var a=this.originalEvent;a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=y,this.stopPropagation()},isDefaultPrevented:x,isPropagationStopped:x,isImmediatePropagationStopped:x};var z=function(a){var b=a.relatedTarget;try{if(b&&b!==c&&!b.parentNode)return;while(b&&b!==this)b=b.parentNode;b!==this&&(a.type=a.data,d.event.handle.apply(this,arguments))}catch(e){}},A=function(a){a.type=a.data,d.event.handle.apply(this,arguments)};d.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){d.event.special[a]={setup:function(c){d.event.add(this,b,c&&c.selector?A:z,a)},teardown:function(a){d.event.remove(this,b,a&&a.selector?A:z)}}}),d.support.submitBubbles||(d.event.special.submit={setup:function(a,b){if(this.nodeName&&this.nodeName.toLowerCase()!=="form")d.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&d(b).closest("form").length&&E("submit",this,arguments)}),d.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&d(b).closest("form").length&&a.keyCode===13&&E("submit",this,arguments)});else return!1},teardown:function(a){d.event.remove(this,".specialSubmit")}});if(!d.support.changeBubbles){var B,C=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?d.map(a.options,function(a){return a.selected}).join("-"):"":a.nodeName.toLowerCase()==="select"&&(c=a.selectedIndex);return c},D=function D(a){var c=a.target,e,f;if(s.test(c.nodeName)&&!c.readOnly){e=d._data(c,"_change_data"),f=C(c),(a.type!=="focusout"||c.type!=="radio")&&d._data(c,"_change_data",f);if(e===b||f===e)return;if(e!=null||f)a.type="change",a.liveFired=b,d.event.trigger(a,arguments[1],c)}};d.event.special.change={filters:{focusout:D,beforedeactivate:D,click:function(a){var b=a.target,c=b.type;(c==="radio"||c==="checkbox"||b.nodeName.toLowerCase()==="select")&&D.call(this,a)},keydown:function(a){var b=a.target,c=b.type;(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&D.call(this,a)},beforeactivate:function(a){var b=a.target;d._data(b,"_change_data",C(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in B)d.event.add(this,c+".specialChange",B[c]);return s.test(this.nodeName)},teardown:function(a){d.event.remove(this,".specialChange");return s.test(this.nodeName)}},B=d.event.special.change.filters,B.focus=B.beforeactivate}c.addEventListener&&d.each({focus:"focusin",blur:"focusout"},function(a,b){function f(a){var c=d.event.fix(a);c.type=b,c.originalEvent={},d.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var e=0;d.event.special[b]={setup:function(){e++===0&&c.addEventListener(a,f,!0)},teardown:function(){--e===0&&c.removeEventListener(a,f,!0)}}}),d.each(["bind","one"],function(a,c){d.fn[c]=function(a,e,f){if(typeof a==="object"){for(var g in a)this[c](g,e,a[g],f);return this}if(d.isFunction(e)||e===!1)f=e,e=b;var h=c==="one"?d.proxy(f,function(a){d(this).unbind(a,h);return f.apply(this,arguments)}):f;if(a==="unload"&&c!=="one")this.one(a,e,f);else for(var i=0,j=this.length;i<j;i++)d.event.add(this[i],a,h,e);return this}}),d.fn.extend({unbind:function(a,b){if(typeof a!=="object"||a.preventDefault)for(var e=0,f=this.length;e<f;e++)d.event.remove(this[e],a,b);else for(var c in a)this.unbind(c,a[c]);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){d.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var c=d.Event(a);c.preventDefault(),c.stopPropagation(),d.event.trigger(c,b,this[0]);return c.result}},toggle:function(a){var b=arguments,c=1;while(c<b.length)d.proxy(a,b[c++]);return this.click(d.proxy(a,function(e){var f=(d._data(this,"lastToggle"+a.guid)||0)%c;d._data(this,"lastToggle"+a.guid,f+1),e.preventDefault();return b[f].apply(this,arguments)||!1}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var F={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};d.each(["live","die"],function(a,c){d.fn[c]=function(a,e,f,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:d(this.context);if(typeof a==="object"&&!a.preventDefault){for(var o in a)n[c](o,e,a[o],m);return this}d.isFunction(e)&&(f=e,e=b),a=(a||"").split(" ");while((h=a[i++])!=null){j=r.exec(h),k="",j&&(k=j[0],h=h.replace(r,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,h==="focus"||h==="blur"?(a.push(F[h]+k),h=h+k):h=(F[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)d.event.add(n[p],"live."+H(h,m),{data:e,selector:m,handler:f,origType:h,origHandler:f,preType:l});else n.unbind("live."+H(h,m),f)}return this}}),d.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){d.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},d.attrFn&&(d.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!=="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,e,g){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!=="string")return e;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(f.call(n)==="[object Array]")if(u)if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&e.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&e.push(j[t]);else e.push.apply(e,n);else p(n,e);o&&(k(o,h,e,g),k.uniqueSort(e));return e};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!=="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(f){if(f===!0)continue}else g=o=!0}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.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|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b==="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1){}a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b==="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!=="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!=="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!=="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return"text"===c&&(b===c||b===null)},radio:function(a){return"radio"===a.type},checkbox:function(a){return"checkbox"===a.type},file:function(a){return"file"===a.type},password:function(a){return"password"===a.type},submit:function(a){return"submit"===a.type},image:function(a){return"image"===a.type},reset:function(a){return"reset"===a.type},button:function(a){return"button"===a.type||a.nodeName.toLowerCase()==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(f.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length==="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(a===b){g=!0;return 0}if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!=="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!=="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!=="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!=="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!=="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};d.find=k,d.expr=k.selectors,d.expr[":"]=d.expr.filters,d.unique=k.uniqueSort,d.text=k.getText,d.isXMLDoc=k.isXML,d.contains=k.contains}();var I=/Until$/,J=/^(?:parents|prevUntil|prevAll)/,K=/,/,L=/^.[^:#\[\.,]*$/,M=Array.prototype.slice,N=d.expr.match.POS,O={children:!0,contents:!0,next:!0,prev:!0};d.fn.extend({find:function(a){var b=this.pushStack("","find",a),c=0;for(var e=0,f=this.length;e<f;e++){c=b.length,d.find(a,this[e],b);if(e>0)for(var g=c;g<b.length;g++)for(var h=0;h<c;h++)if(b[h]===b[g]){b.splice(g--,1);break}}return b},has:function(a){var b=d(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(d.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(Q(this,a,!1),"not",a)},filter:function(a){return this.pushStack(Q(this,a,!0),"filter",a)},is:function(a){return!!a&&d.filter(a,this).length>0},closest:function(a,b){var c=[],e,f,g=this[0];if(d.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(e=0,f=a.length;e<f;e++)i=a[e],j[i]||(j[i]=d.expr.match.POS.test(i)?d(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:d(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=N.test(a)?d(a,b||this.context):null;for(e=0,f=this.length;e<f;e++){g=this[e];while(g){if(l?l.index(g)>-1:d.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b)break}}c=c.length>1?d.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a==="string")return d.inArray(this[0],a?d(a):this.parent().children());return d.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a==="string"?d(a,b):d.makeArray(a),e=d.merge(this.get(),c);return this.pushStack(P(c[0])||P(e[0])?e:d.unique(e))},andSelf:function(){return this.add(this.prevObject)}}),d.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return d.dir(a,"parentNode")},parentsUntil:function(a,b,c){return d.dir(a,"parentNode",c)},next:function(a){return d.nth(a,2,"nextSibling")},prev:function(a){return d.nth(a,2,"previousSibling")},nextAll:function(a){return d.dir(a,"nextSibling")},prevAll:function(a){return d.dir(a,"previousSibling")},nextUntil:function(a,b,c){return d.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return d.dir(a,"previousSibling",c)},siblings:function(a){return d.sibling(a.parentNode.firstChild,a)},children:function(a){return d.sibling(a.firstChild)},contents:function(a){return d.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:d.makeArray(a.childNodes)}},function(a,b){d.fn[a]=function(c,e){var f=d.map(this,b,c),g=M.call(arguments);I.test(a)||(e=c),e&&typeof e==="string"&&(f=d.filter(e,f)),f=this.length>1&&!O[a]?d.unique(f):f,(this.length>1||K.test(e))&&J.test(a)&&(f=f.reverse());return this.pushStack(f,a,g.join(","))}}),d.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?d.find.matchesSelector(b[0],a)?[b[0]]:[]:d.find.matches(a,b)},dir:function(a,c,e){var f=[],g=a[c];while(g&&g.nodeType!==9&&(e===b||g.nodeType!==1||!d(g).is(e)))g.nodeType===1&&f.push(g),g=g[c];return f},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var R=/ jQuery\d+="(?:\d+|null)"/g,S=/^\s+/,T=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,U=/<([\w:]+)/,V=/<tbody/i,W=/<|&#?\w+;/,X=/<(?:script|object|embed|option|style)/i,Y=/checked\s*(?:[^=]|=\s*.checked.)/i,Z={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,"",""]};Z.optgroup=Z.option,Z.tbody=Z.tfoot=Z.colgroup=Z.caption=Z.thead,Z.th=Z.td,d.support.htmlSerialize||(Z._default=[1,"div<div>","</div>"]),d.fn.extend({text:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.text(a.call(this,b,c.text()))});if(typeof a!=="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return d.text(this)},wrapAll:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapAll(a.call(this,b))});if(this[0]){var b=d(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapInner(a.call(this,b))});return this.each(function(){var b=d(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){d(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){d.nodeName(this,"body")||d(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=d(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,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,d(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,e;(e=this[c])!=null;c++)if(!a||d.filter(a,[e]).length)!b&&e.nodeType===1&&(d.cleanData(e.getElementsByTagName("*")),d.cleanData([e])),e.parentNode&&e.parentNode.removeChild(e);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&d.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return d.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(R,""):null;if(typeof a!=="string"||X.test(a)||!d.support.leadingWhitespace&&S.test(a)||Z[(U.exec(a)||["",""])[1].toLowerCase()])d.isFunction(a)?this.each(function(b){var c=d(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);else{a=a.replace(T,"<$1></$2>");try{for(var c=0,e=this.length;c<e;c++)this[c].nodeType===1&&(d.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(f){this.empty().append(a)}}return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(d.isFunction(a))return this.each(function(b){var c=d(this),e=c.html();c.replaceWith(a.call(this,b,e))});typeof a!=="string"&&(a=d(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;d(this).remove(),b?d(b).before(a):d(c).append(a)})}return this.length?this.pushStack(d(d.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,e){var f,g,h,i,j=a[0],k=[];if(!d.support.checkClone&&arguments.length===3&&typeof j==="string"&&Y.test(j))return this.each(function(){d(this).domManip(a,c,e,!0)});if(d.isFunction(j))return this.each(function(f){var g=d(this);a[0]=j.call(this,f,c?g.html():b),g.domManip(a,c,e)});if(this[0]){i=j&&j.parentNode,d.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?f={fragment:i}:f=d.buildFragment(a,this,k),h=f.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&d.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)e.call(c?$(this[l],g):this[l],f.cacheable||m>1&&l<n?d.clone(h,!0,!0):h)}k.length&&d.each(k,bc)}return this}}),d.buildFragment=function(a,b,e){var f,g,h,i=b&&b[0]?b[0].ownerDocument||b[0]:c;a.length===1&&typeof a[0]==="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!X.test(a[0])&&(d.support.checkClone||!Y.test(a[0]))&&(g=!0,h=d.fragments[a[0]],h&&(h!==1&&(f=h))),f||(f=i.createDocumentFragment(),d.clean(a,i,f,e)),g&&(d.fragments[a[0]]=h?f:1);return{fragment:f,cacheable:g}},d.fragments={},d.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){d.fn[a]=function(c){var e=[],f=d(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&f.length===1){f[b](this[0]);return this}for(var h=0,i=f.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();d(f[h])[b](j),e=e.concat(j)}return this.pushStack(e,a,f.selector)}}),d.extend({clone:function(a,b,c){var e=a.cloneNode(!0),f,g,h;if((!d.support.noCloneEvent||!d.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!d.isXMLDoc(a)){ba(a,e),f=bb(a),g=bb(e);for(h=0;f[h];++h)ba(f[h],g[h])}if(b){_(a,e);if(c){f=bb(a),g=bb(e);for(h=0;f[h];++h)_(f[h],g[h])}}return e},clean:function(a,b,e,f){b=b||c,typeof b.createElement==="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var g=[];for(var h=0,i;(i=a[h])!=null;h++){typeof i==="number"&&(i+="");if(!i)continue;if(typeof i!=="string"||W.test(i)){if(typeof i==="string"){i=i.replace(T,"<$1></$2>");var j=(U.exec(i)||["",""])[1].toLowerCase(),k=Z[j]||Z._default,l=k[0],m=b.createElement("div");m.innerHTML=k[1]+i+k[2];while(l--)m=m.lastChild;if(!d.support.tbody){var n=V.test(i),o=j==="table"&&!n?m.firstChild&&m.firstChild.childNodes:k[1]==="<table>"&&!n?m.childNodes:[];for(var p=o.length-1;p>=0;--p)d.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!d.support.leadingWhitespace&&S.test(i)&&m.insertBefore(b.createTextNode(S.exec(i)[0]),m.firstChild),i=m.childNodes}}else i=b.createTextNode(i);i.nodeType?g.push(i):g=d.merge(g,i)}if(e)for(h=0;g[h];h++)!f||!d.nodeName(g[h],"script")||g[h].type&&g[h].type.toLowerCase()!=="text/javascript"?(g[h].nodeType===1&&g.splice.apply(g,[h+1,0].concat(d.makeArray(g[h].getElementsByTagName("script")))),e.appendChild(g[h])):f.push(g[h].parentNode?g[h].parentNode.removeChild(g[h]):g[h]);return g},cleanData:function(a){var b,c,e=d.cache,f=d.expando,g=d.event.special,h=d.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&d.noData[j.nodeName.toLowerCase()])continue;c=j[d.expando];if(c){b=e[c]&&e[c][f];if(b&&b.events){for(var k in b.events)g[k]?d.event.remove(j,k):d.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[d.expando]:j.removeAttribute&&j.removeAttribute(d.expando),delete e[c]}}}});var bd=/alpha\([^)]*\)/i,be=/opacity=([^)]*)/,bf=/-([a-z])/ig,bg=/([A-Z]|^ms)/g,bh=/^-?\d+(?:px)?$/i,bi=/^-?\d/,bj={position:"absolute",visibility:"hidden",display:"block"},bk=["Left","Right"],bl=["Top","Bottom"],bm,bn,bo,bp=function(a,b){return b.toUpperCase()};d.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return d.access(this,a,c,!0,function(a,c,e){return e!==b?d.style(a,c,e):d.css(a,c)})},d.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bm(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{zIndex:!0,fontWeight:!0,opacity:!0,zoom:!0,lineHeight:!0},cssProps:{"float":d.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,e,f){if(a&&a.nodeType!==3&&a.nodeType!==8&&a.style){var g,h=d.camelCase(c),i=a.style,j=d.cssHooks[h];c=d.cssProps[h]||h;if(e===b){if(j&&"get"in j&&(g=j.get(a,!1,f))!==b)return g;return i[c]}if(typeof e==="number"&&isNaN(e)||e==null)return;typeof e==="number"&&!d.cssNumber[h]&&(e+="px");if(!j||!("set"in j)||(e=j.set(a,e))!==b)try{i[c]=e}catch(k){}}},css:function(a,c,e){var f,g=d.camelCase(c),h=d.cssHooks[g];c=d.cssProps[g]||g;if(h&&"get"in h&&(f=h.get(a,!0,e))!==b)return f;if(bm)return bm(a,c,g)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]},camelCase:function(a){return a.replace(bf,bp)}}),d.curCSS=d.css,d.each(["height","width"],function(a,b){d.cssHooks[b]={get:function(a,c,e){var f;if(c){a.offsetWidth!==0?f=bq(a,b,e):d.swap(a,bj,function(){f=bq(a,b,e)});if(f<=0){f=bm(a,b,b),f==="0px"&&bo&&(f=bo(a,b,b));if(f!=null)return f===""||f==="auto"?"0px":f}if(f<0||f==null){f=a.style[b];return f===""||f==="auto"?"0px":f}return typeof f==="string"?f:f+"px"}},set:function(a,b){if(!bh.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),d.support.opacity||(d.cssHooks.opacity={get:function(a,b){return be.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style;c.zoom=1;var e=d.isNaN(b)?"":"alpha(opacity="+b*100+")",f=c.filter||"";c.filter=bd.test(f)?f.replace(bd,e):c.filter+" "+e}}),d(function(){d.support.reliableMarginRight||(d.cssHooks.marginRight={get:function(a,b){var c;d.swap(a,{display:"inline-block"},function(){b?c=bm(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bn=function(a,c,e){var f,g,h;e=e.replace(bg,"-$1").toLowerCase();if(!(g=a.ownerDocument.defaultView))return b;if(h=g.getComputedStyle(a,null))f=h.getPropertyValue(e),f===""&&!d.contains(a.ownerDocument.documentElement,a)&&(f=d.style(a,e));return f}),c.documentElement.currentStyle&&(bo=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bh.test(d)&&bi.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bm=bn||bo,d.expr&&d.expr.filters&&(d.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!d.support.reliableHiddenOffsets&&(a.style.display||d.css(a,"display"))==="none"},d.expr.filters.visible=function(a){return!d.expr.filters.hidden(a)});var br=/%20/g,bs=/\[\]$/,bt=/\r?\n/g,bu=/#.*$/,bv=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bw=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bx=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,by=/^(?:GET|HEAD)$/,bz=/^\/\//,bA=/\?/,bB=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bC=/^(?:select|textarea)/i,bD=/\s+/,bE=/([?&])_=[^&]*/,bF=/(^|\-)([a-z])/g,bG=function(a,b,c){return b+c.toUpperCase()},bH=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bI=d.fn.load,bJ={},bK={},bL,bM;try{bL=c.location.href}catch(bN){bL=c.createElement("a"),bL.href="",bL=bL.href}bM=bH.exec(bL.toLowerCase())||[],d.fn.extend({load:function(a,c,e){if(typeof a!=="string"&&bI)return bI.apply(this,arguments);if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var g=a.slice(f,a.length);a=a.slice(0,f)}var h="GET";c&&(d.isFunction(c)?(e=c,c=b):typeof c==="object"&&(c=d.param(c,d.ajaxSettings.traditional),h="POST"));var i=this;d.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?d("<div>").append(c.replace(bB,"")).find(g):c)),e&&i.each(e,[c,b,a])}});return this},serialize:function(){return d.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?d.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bC.test(this.nodeName)||bw.test(this.type))}).map(function(a,b){var c=d(this).val();return c==null?null:d.isArray(c)?d.map(c,function(a,c){return{name:b.name,value:a.replace(bt,"\r\n")}}):{name:b.name,value:c.replace(bt,"\r\n")}}).get()}}),d.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){d.fn[b]=function(a){return this.bind(b,a)}}),d.each(["get","post"],function(a,c){d[c]=function(a,e,f,g){d.isFunction(e)&&(g=g||f,f=e,e=b);return d.ajax({type:c,url:a,data:e,success:f,dataType:g})}}),d.extend({getScript:function(a,c){return d.get(a,b,c,"script")},getJSON:function(a,b,c){return d.get(a,b,c,"json")},ajaxSetup:function(a,b){b?d.extend(!0,a,d.ajaxSettings,b):(b=a,a=d.extend(!0,d.ajaxSettings,b));for(var c in {context:1,url:1})c in b?a[c]=b[c]:c in d.ajaxSettings&&(a[c]=d.ajaxSettings[c]);return a},ajaxSettings:{url:bL,isLocal:bx.test(bM[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":d.parseJSON,"text xml":d.parseXML}},ajaxPrefilter:bO(bJ),ajaxTransport:bO(bK),ajax:function(a,c){function v(a,c,l,n){if(r!==2){r=2,p&&clearTimeout(p),o=b,m=n||"",u.readyState=a?4:0;var q,t,v,w=l?bR(e,u,l):b,x,y;if(a>=200&&a<300||a===304){if(e.ifModified){if(x=u.getResponseHeader("Last-Modified"))d.lastModified[k]=x;if(y=u.getResponseHeader("Etag"))d.etag[k]=y}if(a===304)c="notmodified",q=!0;else try{t=bS(e,w),c="success",q=!0}catch(z){c="parsererror",v=z}}else{v=c;if(!c||a)c="error",a<0&&(a=0)}u.status=a,u.statusText=c,q?h.resolveWith(f,[t,c,u]):h.rejectWith(f,[u,c,v]),u.statusCode(j),j=b,s&&g.trigger("ajax"+(q?"Success":"Error"),[u,e,q?t:v]),i.resolveWith(f,[u,c]),s&&(g.trigger("ajaxComplete",[u,e]),--d.active||d.event.trigger("ajaxStop"))}}typeof a==="object"&&(c=a,a=b),c=c||{};var e=d.ajaxSetup({},c),f=e.context||e,g=f!==e&&(f.nodeType||f instanceof d)?d(f):d.event,h=d.Deferred(),i=d._Deferred(),j=e.statusCode||{},k,l={},m,n,o,p,q,r=0,s,t,u={readyState:0,setRequestHeader:function(a,b){r||(l[a.toLowerCase().replace(bF,bG)]=b);return this},getAllResponseHeaders:function(){return r===2?m:null},getResponseHeader:function(a){var c;if(r===2){if(!n){n={};while(c=bv.exec(m))n[c[1].toLowerCase()]=c[2]}c=n[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){r||(e.mimeType=a);return this},abort:function(a){a=a||"abort",o&&o.abort(a),v(0,a);return this}};h.promise(u),u.success=u.done,u.error=u.fail,u.complete=i.done,u.statusCode=function(a){if(a){var b;if(r<2)for(b in a)j[b]=[j[b],a[b]];else b=a[u.status],u.then(b,b)}return this},e.url=((a||e.url)+"").replace(bu,"").replace(bz,bM[1]+"//"),e.dataTypes=d.trim(e.dataType||"*").toLowerCase().split(bD),e.crossDomain==null&&(q=bH.exec(e.url.toLowerCase()),e.crossDomain=q&&(q[1]!=bM[1]||q[2]!=bM[2]||(q[3]||(q[1]==="http:"?80:443))!=(bM[3]||(bM[1]==="http:"?80:443)))),e.data&&e.processData&&typeof e.data!=="string"&&(e.data=d.param(e.data,e.traditional)),bP(bJ,e,c,u);if(r===2)return!1;s=e.global,e.type=e.type.toUpperCase(),e.hasContent=!by.test(e.type),s&&d.active++===0&&d.event.trigger("ajaxStart");if(!e.hasContent){e.data&&(e.url+=(bA.test(e.url)?"&":"?")+e.data),k=e.url;if(e.cache===!1){var w=d.now(),x=e.url.replace(bE,"$1_="+w);e.url=x+(x===e.url?(bA.test(e.url)?"&":"?")+"_="+w:"")}}if(e.data&&e.hasContent&&e.contentType!==!1||c.contentType)l["Content-Type"]=e.contentType;e.ifModified&&(k=k||e.url,d.lastModified[k]&&(l["If-Modified-Since"]=d.lastModified[k]),d.etag[k]&&(l["If-None-Match"]=d.etag[k])),l.Accept=e.dataTypes[0]&&e.accepts[e.dataTypes[0]]?e.accepts[e.dataTypes[0]]+(e.dataTypes[0]!=="*"?", */*; q=0.01":""):e.accepts["*"];for(t in e.headers)u.setRequestHeader(t,e.headers[t]);if(e.beforeSend&&(e.beforeSend.call(f,u,e)===!1||r===2)){u.abort();return!1}for(t in {success:1,error:1,complete:1})u[t](e[t]);o=bP(bK,e,c,u);if(o){u.readyState=1,s&&g.trigger("ajaxSend",[u,e]),e.async&&e.timeout>0&&(p=setTimeout(function(){u.abort("timeout")},e.timeout));try{r=1,o.send(l,v)}catch(y){status<2?v(-1,y):d.error(y)}}else v(-1,"No Transport");return u},param:function(a,c){var e=[],f=function(a,b){b=d.isFunction(b)?b():b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=d.ajaxSettings.traditional);if(d.isArray(a)||a.jquery&&!d.isPlainObject(a))d.each(a,function(){f(this.name,this.value)});else for(var g in a)bQ(g,a[g],c,f);return e.join("&").replace(br,"+")}}),d.extend({active:0,lastModified:{},etag:{}});var bT=d.now(),bU=/(\=)\?(&|$)|\?\?/i;d.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return d.expando+"_"+bT++}}),d.ajaxPrefilter("json jsonp",function(b,c,e){var f=typeof b.data==="string";if(b.dataTypes[0]==="jsonp"||c.jsonpCallback||c.jsonp!=null||b.jsonp!==!1&&(bU.test(b.url)||f&&bU.test(b.data))){var g,h=b.jsonpCallback=d.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2",m=function(){a[h]=i,g&&d.isFunction(i)&&a[h](g[0])};b.jsonp!==!1&&(j=j.replace(bU,l),b.url===j&&(f&&(k=k.replace(bU,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},e.then(m,m),b.converters["script json"]=function(){g||d.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),d.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){d.globalEval(a);return a}}}),d.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),d.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var bV=d.now(),bW,bX;d.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&bZ()||b$()}:bZ,bX=d.ajaxSettings.xhr(),d.support.ajax=!!bX,d.support.cors=bX&&"withCredentials"in bX,bX=b,d.support.ajax&&d.ajaxTransport(function(a){if(!a.crossDomain||d.support.cors){var c;return{send:function(e,f){var g=a.xhr(),h,i;a.username?g.open(a.type,a.url,a.async,a.username,a.password):g.open(a.type,a.url,a.async);if(a.xhrFields)for(i in a.xhrFields)g[i]=a.xhrFields[i];a.mimeType&&g.overrideMimeType&&g.overrideMimeType(a.mimeType),!a.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(i in e)g.setRequestHeader(i,e[i])}catch(j){}g.send(a.hasContent&&a.data||null),c=function(e,i){var j,k,l,m,n;try{if(c&&(i||g.readyState===4)){c=b,h&&(g.onreadystatechange=d.noop,delete bW[h]);if(i)g.readyState!==4&&g.abort();else{j=g.status,l=g.getAllResponseHeaders(),m={},n=g.responseXML,n&&n.documentElement&&(m.xml=n),m.text=g.responseText;try{k=g.statusText}catch(o){k=""}j||!a.isLocal||a.crossDomain?j===1223&&(j=204):j=m.text?200:404}}}catch(p){i||f(-1,p)}m&&f(j,k,m,l)},a.async&&g.readyState!==4?(bW||(bW={},bY()),h=bV++,g.onreadystatechange=bW[h]=c):c()},abort:function(){c&&c(0,1)}}}});var b_={},ca=/^(?:toggle|show|hide)$/,cb=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cc,cd=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];d.fn.extend({show:function(a,b,c){var e,f;if(a||a===0)return this.animate(ce("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)e=this[g],f=e.style.display,!d._data(e,"olddisplay")&&f==="none"&&(f=e.style.display=""),f===""&&d.css(e,"display")==="none"&&d._data(e,"olddisplay",cf(e.nodeName));for(g=0;g<h;g++){e=this[g],f=e.style.display;if(f===""||f==="none")e.style.display=d._data(e,"olddisplay")||""}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ce("hide",3),a,b,c);for(var e=0,f=this.length;e<f;e++){var g=d.css(this[e],"display");g!=="none"&&!d._data(this[e],"olddisplay")&&d._data(this[e],"olddisplay",g)}for(e=0;e<f;e++)this[e].style.display="none";return this},_toggle:d.fn.toggle,toggle:function(a,b,c){var e=typeof a==="boolean";d.isFunction(a)&&d.isFunction(b)?this._toggle.apply(this,arguments):a==null||e?this.each(function(){var b=e?a:d(this).is(":hidden");d(this)[b?"show":"hide"]()}):this.animate(ce("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,e){var f=d.speed(b,c,e);if(d.isEmptyObject(a))return this.each(f.complete);return this[f.queue===!1?"each":"queue"](function(){var b=d.extend({},f),c,e=this.nodeType===1,g=e&&d(this).is(":hidden"),h=this;for(c in a){var i=d.camelCase(c);c!==i&&(a[i]=a[c],delete a[c],c=i);if(a[c]==="hide"&&g||a[c]==="show"&&!g)return b.complete.call(this);if(e&&(c==="height"||c==="width")){b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(d.css(this,"display")==="inline"&&d.css(this,"float")==="none")if(d.support.inlineBlockNeedsLayout){var j=cf(this.nodeName);j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)}else this.style.display="inline-block"}d.isArray(a[c])&&((b.specialEasing=b.specialEasing||{})[c]=a[c][1],a[c]=a[c][0])}b.overflow!=null&&(this.style.overflow="hidden"),b.curAnim=d.extend({},a),d.each(a,function(c,e){var f=new d.fx(h,b,c);if(ca.test(e))f[e==="toggle"?g?"show":"hide":e](a);else{var i=cb.exec(e),j=f.cur();if(i){var k=parseFloat(i[2]),l=i[3]||(d.cssNumber[c]?"":"px");l!=="px"&&(d.style(h,c,(k||1)+l),j=(k||1)/f.cur()*j,d.style(h,c,j+l)),i[1]&&(k=(i[1]==="-="?-1:1)*k+j),f.custom(j,k,l)}else f.custom(j,e,"")}});return!0})},stop:function(a,b){var c=d.timers;a&&this.queue([]),this.each(function(){for(var a=c.length-1;a>=0;a--)c[a].elem===this&&(b&&c[a](!0),c.splice(a,1))}),b||this.dequeue();return this}}),d.each({slideDown:ce("show",1),slideUp:ce("hide",1),slideToggle:ce("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){d.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),d.extend({speed:function(a,b,c){var e=a&&typeof a==="object"?d.extend({},a):{complete:c||!c&&b||d.isFunction(a)&&a,duration:a,easing:c&&b||b&&!d.isFunction(b)&&b};e.duration=d.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in d.fx.speeds?d.fx.speeds[e.duration]:d.fx.speeds._default,e.old=e.complete,e.complete=function(){e.queue!==!1&&d(this).dequeue(),d.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig||(b.orig={})}}),d.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(d.fx.step[this.prop]||d.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=d.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function g(a){return e.step(a)}var e=this,f=d.fx;this.startTime=d.now(),this.start=a,this.end=b,this.unit=c||this.unit||(d.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&d.timers.push(g)&&!cc&&(cc=setInterval(f.tick,f.interval))},show:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),d(this.elem).show()},hide:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=d.now(),c=!0;if(a||b>=this.options.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),this.options.curAnim[this.prop]=!0;for(var e in this.options.curAnim)this.options.curAnim[e]!==!0&&(c=!1);if(c){if(this.options.overflow!=null&&!d.support.shrinkWrapBlocks){var f=this.elem,g=this.options;d.each(["","X","Y"],function(a,b){f.style["overflow"+b]=g.overflow[a]})}this.options.hide&&d(this.elem).hide();if(this.options.hide||this.options.show)for(var h in this.options.curAnim)d.style(this.elem,h,this.options.orig[h]);this.options.complete.call(this.elem)}return!1}var i=b-this.startTime;this.state=i/this.options.duration;var j=this.options.specialEasing&&this.options.specialEasing[this.prop],k=this.options.easing||(d.easing.swing?"swing":"linear");this.pos=d.easing[j||k](this.state,i,0,1,this.options.duration),this.now=this.start+(this.end-this.start)*this.pos,this.update();return!0}},d.extend(d.fx,{tick:function(){var a=d.timers;for(var b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||d.fx.stop()},interval:13,stop:function(){clearInterval(cc),cc=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){d.style(a.elem,"opacity",a.now)},_default:function(a){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:a.elem[a.prop]=a.now}}}),d.expr&&d.expr.filters&&(d.expr.filters.animated=function(a){return d.grep(d.timers,function(b){return a===b.elem}).length});var cg=/^t(?:able|d|h)$/i,ch=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?d.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,g=f.documentElement;if(!c||!d.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=f.body,i=ci(f),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||d.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||d.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:d.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);d.offset.initialize();var c,e=b.offsetParent,f=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(d.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===e&&(l+=b.offsetTop,m+=b.offsetLeft,d.offset.doesNotAddBorder&&(!d.offset.doesAddBorderForTableAndCells||!cg.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),f=e,e=b.offsetParent),d.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;d.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},d.offset={initialize:function(){var a=c.body,b=c.createElement("div"),e,f,g,h,i=parseFloat(d.css(a,"marginTop"))||0,j="<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>";d.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),e=b.firstChild,f=e.firstChild,h=e.nextSibling.firstChild.firstChild,this.doesNotAddBorder=f.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,f.style.position="fixed",f.style.top="20px",this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15,f.style.position=f.style.top="",e.style.overflow="hidden",e.style.position="relative",this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),d.offset.initialize=d.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;d.offset.initialize(),d.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(d.css(a,"marginTop"))||0,c+=parseFloat(d.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var e=d.css(a,"position");e==="static"&&(a.style.position="relative");var f=d(a),g=f.offset(),h=d.css(a,"top"),i=d.css(a,"left"),j=(e==="absolute"||e==="fixed")&&d.inArray("auto",[h,i])>-1,k={},l={},m,n;j&&(l=f.position()),m=j?l.top:parseInt(h,10)||0,n=j?l.left:parseInt(i,10)||0,d.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):f.css(k)}},d.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),e=ch.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(d.css(a,"marginTop"))||0,c.left-=parseFloat(d.css(a,"marginLeft"))||0,e.top+=parseFloat(d.css(b[0],"borderTopWidth"))||0,e.left+=parseFloat(d.css(b[0],"borderLeftWidth"))||0;return{top:c.top-e.top,left:c.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&(!ch.test(a.nodeName)&&d.css(a,"position")==="static"))a=a.offsetParent;return a})}}),d.each(["Left","Top"],function(a,c){var e="scroll"+c;d.fn[e]=function(c){var f=this[0],g;if(!f)return null;if(c!==b)return this.each(function(){g=ci(this),g?g.scrollTo(a?d(g).scrollLeft():c,a?c:d(g).scrollTop()):this[e]=c});g=ci(f);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:d.support.boxModel&&g.document.documentElement[e]||g.document.body[e]:f[e]}}),d.each(["Height","Width"],function(a,c){var e=c.toLowerCase();d.fn["inner"+c]=function(){return this[0]?parseFloat(d.css(this[0],e,"padding")):null},d.fn["outer"+c]=function(a){return this[0]?parseFloat(d.css(this[0],e,a?"margin":"border")):null},d.fn[e]=function(a){var f=this[0];if(!f)return a==null?null:this;if(d.isFunction(a))return this.each(function(b){var c=d(this);c[e](a.call(this,b,c[e]()))});if(d.isWindow(f)){var g=f.document.documentElement["client"+c];return f.document.compatMode==="CSS1Compat"&&g||f.document.body["client"+c]||g}if(f.nodeType===9)return Math.max(f.documentElement["client"+c],f.body["scroll"+c],f.documentElement["scroll"+c],f.body["offset"+c],f.documentElement["offset"+c]);if(a===b){var h=d.css(f,e),i=parseFloat(h);return d.isNaN(i)?h:i}return this.css(e,typeof a==="string"?a:a+"px")}}),a.jQuery=a.$=d})(window); |
client/comps/app.js | nko5/lisezmoi | import React from 'react'
import { connect } from 'react-redux'
import * as actions from '../action-creators'
import Main from './main'
import Sidebar from './sidebar'
import About from './about'
import End from './end'
import Footer from './footer'
const stateToProps = state => ({
userId: state.userId,
users: state.users,
lines: state.lines,
aboutOpened: state.aboutOpened,
pressedLetter: state.pressedLetter,
betHistory: state.betHistory,
gameEnded: state.gameEnded,
})
class App extends React.Component {
componentDidMount() {
window.addEventListener('mouseup', () => {
const { props } = this
if (props.pressedLetter) {
props.onEndBet(props.pressedLetter)
props.dispatch(actions.pressLetter(null))
}
})
}
toggleAbout() {
this.props.dispatch(actions.toggleAbout())
}
pressLetter(letter) {
this.props.dispatch(actions.pressLetter(letter))
}
render() {
const { props } = this
const { dispatch } = props
return (
<div className='main-in'>
<div className='App'>
<Main
betHistory={props.betHistory}
lines={props.lines}
userId={props.userId}
onToggleAbout={this.toggleAbout.bind(this)}
/>
<Sidebar
onPressLetter={this.pressLetter.bind(this)}
onStartBet={props.onStartBet}
onEndBet={props.onEndBet}
users={props.users}
userId={props.userId}
/>
</div>
<About
opened={props.aboutOpened}
onToggleAbout={this.toggleAbout.bind(this)}
/>
<End
opened={props.gameEnded}
/>
<Footer/>
</div>
)
}
}
export default connect(stateToProps)(App)
|
modules/__tests__/serverRendering-test.js | andreftavares/react-router | /*eslint-env mocha */
/*eslint react/prop-types: 0*/
import expect from 'expect'
import React from 'react'
import createLocation from 'history/lib/createLocation'
import RoutingContext from '../RoutingContext'
import match from '../match'
import Link from '../Link'
describe('server rendering', function () {
let App, Dashboard, About, RedirectRoute, AboutRoute, DashboardRoute, routes
beforeEach(function () {
App = React.createClass({
render() {
return (
<div className="App">
<h1>App</h1>
<Link to="/about" activeClassName="about-is-active">About</Link>{' '}
<Link to="/dashboard" activeClassName="dashboard-is-active">Dashboard</Link>
<div>
{this.props.children}
</div>
</div>
)
}
})
Dashboard = React.createClass({
render() {
return (
<div className="Dashboard">
<h1>The Dashboard</h1>
</div>
)
}
})
About = React.createClass({
render() {
return (
<div className="About">
<h1>About</h1>
</div>
)
}
})
DashboardRoute = {
path: '/dashboard',
component: Dashboard
}
AboutRoute = {
path: '/about',
component: About
}
RedirectRoute = {
path: '/company',
onEnter(nextState, replaceState) {
replaceState(null, '/about')
}
}
routes = {
path: '/',
component: App,
childRoutes: [ DashboardRoute, AboutRoute, RedirectRoute ]
}
})
it('works', function (done) {
const location = createLocation('/dashboard')
match({ routes, location }, function (error, redirectLocation, renderProps) {
const string = React.renderToString(
<RoutingContext {...renderProps} />
)
expect(string).toMatch(/The Dashboard/)
done()
})
})
it('renders active Links as active', function (done) {
const location = createLocation('/about')
match({ routes, location }, function (error, redirectLocation, renderProps) {
const string = React.renderToString(
<RoutingContext {...renderProps} />
)
expect(string).toMatch(/about-is-active/)
//expect(string).toNotMatch(/dashboard-is-active/) TODO add toNotMatch to expect
done()
})
})
it('sends the redirect location', function (done) {
const location = createLocation('/company')
match({ routes, location }, function (error, redirectLocation) {
expect(redirectLocation).toExist()
expect(redirectLocation.pathname).toEqual('/about')
expect(redirectLocation.search).toEqual('')
expect(redirectLocation.state).toEqual(null)
expect(redirectLocation.action).toEqual('REPLACE')
done()
})
})
it('sends null values when no routes match', function (done) {
const location = createLocation('/no-match')
match({ routes, location }, function (error, redirectLocation, state) {
expect(error).toBe(null)
expect(redirectLocation).toBe(null)
expect(state).toBe(null)
done()
})
})
})
|
ajax/libs/rxjs/2.3.20/rx.compat.js | zhangbg/cdnjs | // 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];
console.log(rFileName, rStartingLine, rEndingLine);
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;
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) {
observer.onError = function (err) {
makeStackTraceLong(self, err);
observer.onError(err);
};
subscribe(observer);
};
}
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));
});
};
/**
* 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;
});
};
/**
* 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 self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* 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;
});
}
/**
* 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);
});
};
/**
* 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;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @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 (arguments[0].now) {
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;
});
};
/**
* @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;
});
};
/**
* 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);
});
};
/**
* 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)
);
});
};
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));
});
}
/**
* 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);
});
};
/**
* 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));
};
/**
* 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));
});
};
/**
* 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 (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* 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();
});
});
};
/** @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();
}
});
});
};
/**
* @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));
});
};
/**
* 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();
});
});
};
/**
* 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();
}
);
});
};
/**
* 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));
});
};
/**
* 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();
});
});
};
/**
* 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();
});
});
};
/**
* 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;
});
};
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();
});
}).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;
if (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 () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
// 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));
});
};
/**
* 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));
});
};
/**
* 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();
});
}).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));
});
};
/**
* 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));
});
};
/**
* 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 observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining-- > 0) {
observer.onNext(x);
remaining === 0 && observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* 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 observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* 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 parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (e) {
observer.onError(e);
return;
}
shouldRun && observer.onNext(value);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* 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); }
);
});
};
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));
|
js/App/Components/SensorDetails/SubViews/CalendarModalComponent.js | telldus/telldus-live-mobile-v3 | /**
* Copyright 2016-present Telldus Technologies AB.
*
* This file is part of the Telldus Live! app.
*
* Telldus Live! app is free : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Telldus Live! app is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>.
*/
// @flow
'use strict';
import React from 'react';
import { TouchableOpacity, ScrollView } from 'react-native';
import { Calendar } from 'react-native-calendars';
import Modal from 'react-native-modal';
let dayjs = require('dayjs');
let utc = require('dayjs/plugin/utc');
let timezone = require('dayjs/plugin/timezone');
dayjs.extend(utc);
dayjs.extend(timezone);
const isEqual = require('react-fast-compare');
import DeviceInfo from 'react-native-device-info';
import {
View,
Poster,
Text,
FormattedDate,
} from '../../../../BaseComponents';
import CalendarDay from './CalendarDay';
import {
withTheme,
PropsThemedComponent,
} from '../../HOC/withTheme';
import i18n from '../../../Translations/common';
import Theme from '../../../Theme';
type Props = PropsThemedComponent & {
isVisible: boolean,
current: any,
onPressPositive: (any) => void,
onPressNegative: () => void,
appLayout: Object,
intl: Object,
maxDate: string,
propToUpdate: 1 | 2,
timestamp: Object,
gatewayTimezone: string,
};
type DefaultProps = {
isVisible: boolean,
};
class CalendarModalComponent extends View<Props, null> {
props: Props;
static defaultProps: DefaultProps = {
isVisible: false,
};
isTablet: boolean;
static getDerivedStateFromProps(props: Object, state: Object): null | Object {
const { isVisible, current } = props;
if (isVisible !== state.isVisible) {
return {
isVisible,
current,
};
}
if ((current !== state.current) && !state.isVisible) {
return {
current,
isVisible,
};
}
return null;
}
onPressPositive: () => void;
onPressNegative: () => void;
onDayPress: (Object) => void;
renderDay: (Object) => void;
constructor(props: Props) {
super(props);
this.state = {
current: props.current,
isVisible: props.isVisible,
};
this.isTablet = DeviceInfo.isTablet();
this.onPressPositive = this.onPressPositive.bind(this);
this.onPressNegative = this.onPressNegative.bind(this);
this.onDayPress = this.onDayPress.bind(this);
this.renderDay = this.renderDay.bind(this);
const { formatMessage } = props.intl;
this.ok = formatMessage(i18n.defaultPositiveText);
this.cancel = formatMessage(i18n.defaultNegativeText);
}
onPressPositive() {
const { onPressPositive } = this.props;
const { current } = this.state;
if (onPressPositive) {
onPressPositive(current);
}
}
onPressNegative() {
const { onPressNegative } = this.props;
if (onPressNegative) {
onPressNegative();
}
}
shouldComponentUpdate(nextProps: Object, nextState: Object): boolean {
const isStateEqual = isEqual(this.state, nextState);
const isLayoutEqual = isEqual(this.props.appLayout, nextProps.appLayout);
const isMaxDateEqual = nextProps.maxDate === this.props.maxDate;
return (nextState.isVisible || this.state.isVisible) && (!isStateEqual || !isLayoutEqual || isMaxDateEqual);
}
onDayPress(day: Object) {
const { propToUpdate, gatewayTimezone } = this.props;
if (gatewayTimezone) {
dayjs.tz.setDefault(gatewayTimezone);
}
// The received timestamp is in GMT also start of the day timestamp in milliseconds
let { timestamp } = day;
timestamp = timestamp / 1000;
// Converting UTC start of the day[SOD] timestap to user's locale SOD
let selectedTimestamp = dayjs.unix(timestamp).startOf('day').unix();
// While choosing 'to' date
if (propToUpdate === 2) {
const todayDate = dayjs().format('YYYY-MM-DD');
const timestampAsDate = dayjs.unix(timestamp).format('YYYY-MM-DD');
// Use end of the day[EOD] timestamp, also dayjs converts UTC to user's locale
selectedTimestamp = dayjs.unix(timestamp).endOf('day').unix();
// If 'to' date is today then use 'now/current time' timestamp
if (timestampAsDate === todayDate) {
selectedTimestamp = parseInt(dayjs().format('X'), 10);
}
}
dayjs.tz.setDefault();
this.setState({
current: selectedTimestamp,
});
}
renderDay({date, state, marking}: Object): Object {
const props = {
date,
state,
marking,
onDayPress: this.onDayPress,
appLayout: this.props.appLayout,
};
return (
<CalendarDay {...props} />
);
}
getMarkedDatesAndPosterDate(current: number, gatewayTimezone: string): Object {
if (gatewayTimezone) {
dayjs.tz.setDefault(gatewayTimezone);
}
const posterDate = dayjs.unix(current);
let currentMark = dayjs.unix(current).format('YYYY-MM-DD');
let { timestamp, propToUpdate } = this.props, markedDates = {};
let { fromTimestamp, toTimestamp } = timestamp;
let startDate = dayjs.unix(fromTimestamp).format('YYYY-MM-DD'), endDate = dayjs.unix(toTimestamp).format('YYYY-MM-DD');
if (propToUpdate === 1) {
startDate = dayjs.unix(current).format('YYYY-MM-DD');
} else {
endDate = dayjs.unix(current).format('YYYY-MM-DD');
}
markedDates[startDate] = {marked: true, startingDay: true, selected: currentMark === startDate};
const diff = dayjs(endDate).diff(dayjs(startDate), 'day');
if (diff <= 0) {
if (dayjs(currentMark).isBefore(startDate)) {
markedDates[currentMark] = {marked: true, selected: true, endingDay: true};
}
if (startDate === currentMark) {
markedDates[startDate] = {marked: true, startingDay: true, selected: true, endingDay: true};
}
dayjs.tz.setDefault();
return {
markedDates,
posterDate,
};
}
let temp = startDate;
for (let i = 0; i < diff; i++) {
temp = dayjs(temp).add(1, 'd').format('YYYY-MM-DD');
markedDates[temp] = {marked: true, endingDay: i === (diff - 1), selected: temp === currentMark};
}
dayjs.tz.setDefault();
return {
markedDates,
posterDate,
};
}
render(): Object {
const { current, isVisible } = this.state;
const {
appLayout,
maxDate,
gatewayTimezone,
} = this.props;
const {
containerStyle,
posterWidth,
posterHeight,
posterItemsStyle,
posterTextOneStyle,
posterTextTwoStyle,
calendarTheme,
footerStyle,
positiveLabelStyle,
negativeLabelStyle,
} = this.getStyle(appLayout);
const {
markedDates,
posterDate,
} = this.getMarkedDatesAndPosterDate(current, gatewayTimezone);
return (
<Modal
isVisible={isVisible}
hideModalContentWhileAnimating={true}
supportedOrientations={['portrait', 'landscape']}
onRequestClose={this.onPressNegative}>
<ScrollView style={{flex: 1}} contentContainerStyle={containerStyle}>
<Poster posterWidth={posterWidth} posterHeight={posterHeight}>
<View style={posterItemsStyle}>
<FormattedDate
value={posterDate}
year="numeric"
style={posterTextOneStyle}
level={33}/>
<FormattedDate
value={posterDate}
day="numeric"
month="short"
weekday="short"
style={posterTextTwoStyle}
level={33}/>
</View>
</Poster>
<Calendar
markedDates={{
...markedDates,
}}
maxDate={maxDate}
dayComponent={this.renderDay}
theme={calendarTheme}
firstDay={1}/>
<View style={footerStyle}>
<TouchableOpacity onPress={this.onPressNegative}>
<Text style={negativeLabelStyle}>
{this.cancel}
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.onPressPositive}>
<Text style={positiveLabelStyle}>
{this.ok}
</Text>
</TouchableOpacity>
</View>
</ScrollView>
</Modal>
);
}
getStyle(appLayout: Object): Object {
const {
colors,
} = this.props;
const { height, width } = appLayout;
const isPortrait = height > width;
const deviceWidth = isPortrait ? width : height;
const {
offlineColor,
fontSizeFactorFive,
} = Theme.Core;
const adjustCelendar = !this.isTablet && !isPortrait;
const posterHeight = adjustCelendar ? deviceWidth * 0.12 : deviceWidth * 0.25;
const fontSizePosterTextOne = posterHeight * 0.2;
const fontSizePosterTextTwo = posterHeight * 0.25;
const fontSizeFooterText = adjustCelendar ? deviceWidth * 0.03 : deviceWidth * fontSizeFactorFive;
const footerPadding = adjustCelendar ? fontSizeFooterText * 0.5 : fontSizeFooterText;
const {
inAppBrandSecondary,
card,
textFour,
} = colors;
return {
containerStyle: {
flexGrow: 1,
justifyContent: 'center',
},
posterWidth: width,
posterHeight,
posterItemsStyle: {
flex: 1,
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
paddingLeft: 15,
justifyContent: 'center',
alignItems: 'flex-start',
},
posterTextOneStyle: {
fontSize: fontSizePosterTextOne,
},
posterTextTwoStyle: {
fontSize: fontSizePosterTextTwo,
fontWeight: '500',
},
calendarTheme: {
backgroundColor: card,
calendarBackground: card,
textSectionTitleColor: offlineColor,
selectedDayBackgroundColor: inAppBrandSecondary,
todayTextColor: '#00adf5',
arrowColor: textFour,
monthTextColor: textFour,
'stylesheet.calendar.main': {
week: {
marginTop: 0,
marginBottom: 0,
flexDirection: 'row',
justifyContent: 'space-around',
},
},
},
footerStyle: {
flexDirection: 'row',
backgroundColor: card,
justifyContent: 'flex-end',
paddingVertical: footerPadding,
paddingRight: adjustCelendar ? 10 : 0,
},
positiveLabelStyle: {
color: inAppBrandSecondary,
fontSize: fontSizeFooterText,
marginLeft: 20,
marginRight: 15,
},
negativeLabelStyle: {
color: textFour,
fontSize: fontSizeFooterText,
},
};
}
}
export default (withTheme(CalendarModalComponent): Object);
|
src/components/Patterns/LeftPane/PatternsLeftPaneComponent.js | coolshare/ReactReduxStarterKit | import React from 'react';
import classNames from 'classnames';
import InfiniteTree from 'react-infinite-tree';
import 'react-infinite-tree/dist/react-infinite-tree.css';
import cs from '../../../services/CommunicationService'
export default class PatternsLeftPane extends React.Component {
tree = null;
componentDidMount() {
this.tree.loadData(this.props.data);
// Select the first node
this.tree.selectNode(this.tree.getChildNodes()[0].getChildren()[0].getChildren()[0]);
}
render() {
return (
<div>
<InfiniteTree
ref={(c) => {if (c!==null) this.tree = c.tree;}}
autoOpen={true}
loadNodes={(parentNode, done) => {
const suffix = parentNode.id.replace(/(\w)+/, '');
const nodes = [
{
id: 'node1' + suffix,
name: 'Node 1'
},
{
id: 'node2' + suffix,
name: 'Node 2'
}
];
setTimeout(() => {
done(null, nodes);
}, 1000);
}}
rowRenderer={(node, treeOptions) => {
const { id, name, loadOnDemand = false, children, state, props = {} } = node;
const droppable = treeOptions.droppable;
const { depth, open, path, total, selected = false } = state;
const more = node.hasChildren();
return (
<div
className={classNames(
'infinite-tree-item',
{ 'infinite-tree-selected': selected }
)}
data-id={id}
droppable={droppable}
>
<div
className="infinite-tree-node"
style={{ marginLeft: depth * 18 }}
>
{!more && loadOnDemand &&
<a className={classNames(treeOptions.togglerClass, 'infinite-tree-closed')}>►</a>
}
{more && open &&
<a className={classNames(treeOptions.togglerClass)}>▼</a>
}
{more && !open &&
<a className={classNames(treeOptions.togglerClass, 'infinite-tree-closed')}>►</a>
}
<span className="infinite-tree-title">{name}</span>
</div>
</div>
);
}}
selectable={true}
shouldSelectNode={(node) => {
if (!node || (node === this.tree.getSelectedNode())) {
return false; // Prevent from deselecting the current node
}
return true;
}}
onClick={(event) => {
// click event
const target = event.target || event.srcElement; // IE8
console.log('click:', target);
cs.dispatch({"type":"switchPage", "id":event.target.innerText})
}}
onDoubleClick={(event) => {
// dblclick event
}}
onKeyDown={(event) => {
// keydown event
}}
onKeyUp={(event) => {
// keyup event
}}
onOpenNode={(node) => {
console.log('open node:', node);
}}
onCloseNode={(node) => {
console.log('close node:', node);
}}
onSelectNode={(node) => {
console.log('select node:', node);
}}
onClusterWillChange={() => {
}}
onClusterDidChange={() => {
}}
onContentWillUpdate={() => {
}}
onContentDidUpdate={() => {
}}
/>
</div>
);
}
}
|
ajax/libs/video.js/5.0.0-rc.98/video.js | froala/cdnjs | /**
* @license
* Video.js 5.0.0-rc.98 <http://videojs.com/>
* Copyright Brightcove, Inc. <https://www.brightcove.com/>
* Available under Apache License Version 2.0
* <https://github.com/videojs/video.js/blob/master/LICENSE>
*
* Includes vtt.js <https://github.com/mozilla/vtt.js>
* Available under Apache License Version 2.0
* <https://github.com/mozilla/vtt.js/blob/master/LICENSE>
*/
(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.videojs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
(function (global){
var topLevel = typeof global !== 'undefined' ? global :
typeof window !== 'undefined' ? window : {}
var minDoc = _dereq_('min-document');
if (typeof document !== 'undefined') {
module.exports = document;
} else {
var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
}
module.exports = doccy;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvZG9jdW1lbnQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgdG9wTGV2ZWwgPSB0eXBlb2YgZ2xvYmFsICE9PSAndW5kZWZpbmVkJyA/IGdsb2JhbCA6XG4gICAgdHlwZW9mIHdpbmRvdyAhPT0gJ3VuZGVmaW5lZCcgPyB3aW5kb3cgOiB7fVxudmFyIG1pbkRvYyA9IHJlcXVpcmUoJ21pbi1kb2N1bWVudCcpO1xuXG5pZiAodHlwZW9mIGRvY3VtZW50ICE9PSAndW5kZWZpbmVkJykge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZG9jdW1lbnQ7XG59IGVsc2Uge1xuICAgIHZhciBkb2NjeSA9IHRvcExldmVsWydfX0dMT0JBTF9ET0NVTUVOVF9DQUNIRUA0J107XG5cbiAgICBpZiAoIWRvY2N5KSB7XG4gICAgICAgIGRvY2N5ID0gdG9wTGV2ZWxbJ19fR0xPQkFMX0RPQ1VNRU5UX0NBQ0hFQDQnXSA9IG1pbkRvYztcbiAgICB9XG5cbiAgICBtb2R1bGUuZXhwb3J0cyA9IGRvY2N5O1xufVxuIl19
},{"min-document":3}],2:[function(_dereq_,module,exports){
(function (global){
if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvd2luZG93LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiaWYgKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIpIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHdpbmRvdztcbn0gZWxzZSBpZiAodHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIikge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZ2xvYmFsO1xufSBlbHNlIGlmICh0eXBlb2Ygc2VsZiAhPT0gXCJ1bmRlZmluZWRcIil7XG4gICAgbW9kdWxlLmV4cG9ydHMgPSBzZWxmO1xufSBlbHNlIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHt9O1xufVxuIl19
},{}],3:[function(_dereq_,module,exports){
},{}],4:[function(_dereq_,module,exports){
var getNative = _dereq_('../internal/getNative');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeNow = getNative(Date, 'now');
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Date
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => logs the number of milliseconds it took for the deferred function to be invoked
*/
var now = nativeNow || function() {
return new Date().getTime();
};
module.exports = now;
},{"../internal/getNative":20}],5:[function(_dereq_,module,exports){
var isObject = _dereq_('../lang/isObject'),
now = _dereq_('../date/now');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed invocations. Provide an options object to indicate that `func`
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
* Subsequent calls to the debounced function return the result of the last
* `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify invoking on the leading
* edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
* delayed before it's invoked.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // invoke `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // ensure `batchLog` is invoked once after 1 second of debounced calls
* var source = new EventSource('/stream');
* jQuery(source).on('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }));
*
* // cancel a debounced call
* var todoChanges = _.debounce(batchLog, 1000);
* Object.observe(models.todo, todoChanges);
*
* Object.observe(models, function(changes) {
* if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
* todoChanges.cancel();
* }
* }, ['delete']);
*
* // ...at some point `models.todo` is changed
* models.todo.completed = true;
*
* // ...before 1 second has passed `models.todo` is deleted
* // which cancels the debounced `todoChanges` call
* delete models.todo;
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = wait < 0 ? 0 : (+wait || 0);
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = !!options.leading;
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
lastCalled = 0;
maxTimeoutId = timeoutId = trailingCall = undefined;
}
function complete(isCalled, id) {
if (id) {
clearTimeout(id);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = undefined;
}
}
}
function delayed() {
var remaining = wait - (now() - stamp);
if (remaining <= 0 || remaining > wait) {
complete(trailingCall, maxTimeoutId);
} else {
timeoutId = setTimeout(delayed, remaining);
}
}
function maxDelayed() {
complete(trailing, timeoutId);
}
function debounced() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0 || remaining > maxWait;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = undefined;
}
return result;
}
debounced.cancel = cancel;
return debounced;
}
module.exports = debounce;
},{"../date/now":4,"../lang/isObject":33}],6:[function(_dereq_,module,exports){
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
module.exports = restParam;
},{}],7:[function(_dereq_,module,exports){
var debounce = _dereq_('./debounce'),
isObject = _dereq_('../lang/isObject');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed invocations. Provide an options object to indicate
* that `func` should be invoked on the leading and/or trailing edge of the
* `wait` timeout. Subsequent calls to the throttled function return the
* result of the last `func` call.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the throttled function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=true] Specify invoking on the leading
* edge of the timeout.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // avoid excessively updating the position while scrolling
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
* jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
* 'trailing': false
* }));
*
* // cancel a trailing throttled call
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (options === false) {
leading = false;
} else if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
}
module.exports = throttle;
},{"../lang/isObject":33,"./debounce":5}],8:[function(_dereq_,module,exports){
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function arrayCopy(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = arrayCopy;
},{}],9:[function(_dereq_,module,exports){
/**
* A specialized version of `_.forEach` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
},{}],10:[function(_dereq_,module,exports){
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property names to copy.
* @param {Object} [object={}] The object to copy properties to.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, props, object) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
},{}],11:[function(_dereq_,module,exports){
var createBaseFor = _dereq_('./createBaseFor');
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iteratee functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
},{"./createBaseFor":18}],12:[function(_dereq_,module,exports){
var baseFor = _dereq_('./baseFor'),
keysIn = _dereq_('../object/keysIn');
/**
* The base implementation of `_.forIn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForIn(object, iteratee) {
return baseFor(object, iteratee, keysIn);
}
module.exports = baseForIn;
},{"../object/keysIn":39,"./baseFor":11}],13:[function(_dereq_,module,exports){
var arrayEach = _dereq_('./arrayEach'),
baseMergeDeep = _dereq_('./baseMergeDeep'),
isArray = _dereq_('../lang/isArray'),
isArrayLike = _dereq_('./isArrayLike'),
isObject = _dereq_('../lang/isObject'),
isObjectLike = _dereq_('./isObjectLike'),
isTypedArray = _dereq_('../lang/isTypedArray'),
keys = _dereq_('../object/keys');
/**
* The base implementation of `_.merge` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {Object} Returns `object`.
*/
function baseMerge(object, source, customizer, stackA, stackB) {
if (!isObject(object)) {
return object;
}
var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
props = isSrcArr ? undefined : keys(source);
arrayEach(props || source, function(srcValue, key) {
if (props) {
key = srcValue;
srcValue = source[key];
}
if (isObjectLike(srcValue)) {
stackA || (stackA = []);
stackB || (stackB = []);
baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
}
else {
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
}
if ((result !== undefined || (isSrcArr && !(key in object))) &&
(isCommon || (result === result ? (result !== value) : (value === value)))) {
object[key] = result;
}
}
});
return object;
}
module.exports = baseMerge;
},{"../lang/isArray":30,"../lang/isObject":33,"../lang/isTypedArray":36,"../object/keys":38,"./arrayEach":9,"./baseMergeDeep":14,"./isArrayLike":21,"./isObjectLike":26}],14:[function(_dereq_,module,exports){
var arrayCopy = _dereq_('./arrayCopy'),
isArguments = _dereq_('../lang/isArguments'),
isArray = _dereq_('../lang/isArray'),
isArrayLike = _dereq_('./isArrayLike'),
isPlainObject = _dereq_('../lang/isPlainObject'),
isTypedArray = _dereq_('../lang/isTypedArray'),
toPlainObject = _dereq_('../lang/toPlainObject');
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
var length = stackA.length,
srcValue = source[key];
while (length--) {
if (stackA[length] == srcValue) {
object[key] = stackB[length];
return;
}
}
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
result = isArray(value)
? value
: (isArrayLike(value) ? arrayCopy(value) : []);
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
result = isArguments(value)
? toPlainObject(value)
: (isPlainObject(value) ? value : {});
}
else {
isCommon = false;
}
}
// Add the source value to the stack of traversed objects and associate
// it with its merged value.
stackA.push(srcValue);
stackB.push(result);
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
} else if (result === result ? (result !== value) : (value === value)) {
object[key] = result;
}
}
module.exports = baseMergeDeep;
},{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isPlainObject":34,"../lang/isTypedArray":36,"../lang/toPlainObject":37,"./arrayCopy":8,"./isArrayLike":21}],15:[function(_dereq_,module,exports){
var toObject = _dereq_('./toObject');
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : toObject(object)[key];
};
}
module.exports = baseProperty;
},{"./toObject":28}],16:[function(_dereq_,module,exports){
var identity = _dereq_('../utility/identity');
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (thisArg === undefined) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
module.exports = bindCallback;
},{"../utility/identity":42}],17:[function(_dereq_,module,exports){
var bindCallback = _dereq_('./bindCallback'),
isIterateeCall = _dereq_('./isIterateeCall'),
restParam = _dereq_('../function/restParam');
/**
* Creates a `_.assign`, `_.defaults`, or `_.merge` function.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return restParam(function(object, sources) {
var index = -1,
length = object == null ? 0 : sources.length,
customizer = length > 2 ? sources[length - 2] : undefined,
guard = length > 2 ? sources[2] : undefined,
thisArg = length > 1 ? sources[length - 1] : undefined;
if (typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = typeof thisArg == 'function' ? thisArg : undefined;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
},{"../function/restParam":6,"./bindCallback":16,"./isIterateeCall":24}],18:[function(_dereq_,module,exports){
var toObject = _dereq_('./toObject');
/**
* Creates a base function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var iterable = toObject(object),
props = keysFunc(object),
length = props.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
},{"./toObject":28}],19:[function(_dereq_,module,exports){
var baseProperty = _dereq_('./baseProperty');
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
module.exports = getLength;
},{"./baseProperty":15}],20:[function(_dereq_,module,exports){
var isNative = _dereq_('../lang/isNative');
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
module.exports = getNative;
},{"../lang/isNative":32}],21:[function(_dereq_,module,exports){
var getLength = _dereq_('./getLength'),
isLength = _dereq_('./isLength');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
module.exports = isArrayLike;
},{"./getLength":19,"./isLength":25}],22:[function(_dereq_,module,exports){
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
var isHostObject = (function() {
try {
Object({ 'toString': 0 } + '');
} catch(e) {
return function() { return false; };
}
return function(value) {
// IE < 9 presents many host objects as `Object` objects that can coerce
// to strings despite having improperly defined `toString` methods.
return typeof value.toString != 'function' && typeof (value + '') == 'string';
};
}());
module.exports = isHostObject;
},{}],23:[function(_dereq_,module,exports){
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
module.exports = isIndex;
},{}],24:[function(_dereq_,module,exports){
var isArrayLike = _dereq_('./isArrayLike'),
isIndex = _dereq_('./isIndex'),
isObject = _dereq_('../lang/isObject');
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
module.exports = isIterateeCall;
},{"../lang/isObject":33,"./isArrayLike":21,"./isIndex":23}],25:[function(_dereq_,module,exports){
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
},{}],26:[function(_dereq_,module,exports){
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
},{}],27:[function(_dereq_,module,exports){
var isArguments = _dereq_('../lang/isArguments'),
isArray = _dereq_('../lang/isArray'),
isIndex = _dereq_('./isIndex'),
isLength = _dereq_('./isLength'),
isString = _dereq_('../lang/isString'),
keysIn = _dereq_('../object/keysIn');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = !!length && isLength(length) &&
(isArray(object) || isArguments(object) || isString(object));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
module.exports = shimKeys;
},{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isString":35,"../object/keysIn":39,"./isIndex":23,"./isLength":25}],28:[function(_dereq_,module,exports){
var isObject = _dereq_('../lang/isObject'),
isString = _dereq_('../lang/isString'),
support = _dereq_('../support');
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
if (support.unindexedChars && isString(value)) {
var index = -1,
length = value.length,
result = Object(value);
while (++index < length) {
result[index] = value.charAt(index);
}
return result;
}
return isObject(value) ? value : Object(value);
}
module.exports = toObject;
},{"../lang/isObject":33,"../lang/isString":35,"../support":41}],29:[function(_dereq_,module,exports){
var isArrayLike = _dereq_('../internal/isArrayLike'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return isObjectLike(value) && isArrayLike(value) &&
hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
}
module.exports = isArguments;
},{"../internal/isArrayLike":21,"../internal/isObjectLike":26}],30:[function(_dereq_,module,exports){
var getNative = _dereq_('../internal/getNative'),
isLength = _dereq_('../internal/isLength'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** `Object#toString` result references. */
var arrayTag = '[object Array]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = getNative(Array, 'isArray');
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
};
module.exports = isArray;
},{"../internal/getNative":20,"../internal/isLength":25,"../internal/isObjectLike":26}],31:[function(_dereq_,module,exports){
var isObject = _dereq_('./isObject');
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 which returns 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
module.exports = isFunction;
},{"./isObject":33}],32:[function(_dereq_,module,exports){
var isFunction = _dereq_('./isFunction'),
isHostObject = _dereq_('../internal/isHostObject'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value);
}
module.exports = isNative;
},{"../internal/isHostObject":22,"../internal/isObjectLike":26,"./isFunction":31}],33:[function(_dereq_,module,exports){
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isObject;
},{}],34:[function(_dereq_,module,exports){
var baseForIn = _dereq_('../internal/baseForIn'),
isArguments = _dereq_('./isArguments'),
isHostObject = _dereq_('../internal/isHostObject'),
isObjectLike = _dereq_('../internal/isObjectLike'),
support = _dereq_('../support');
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* **Note:** This method assumes objects created by the `Object` constructor
* have no inherited enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
var Ctor;
// Exit early for non `Object` objects.
if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value) && !isArguments(value)) ||
(!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
var result;
if (support.ownLast) {
baseForIn(value, function(subValue, key, object) {
result = hasOwnProperty.call(object, key);
return false;
});
return result !== false;
}
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
baseForIn(value, function(subValue, key) {
result = key;
});
return result === undefined || hasOwnProperty.call(value, result);
}
module.exports = isPlainObject;
},{"../internal/baseForIn":12,"../internal/isHostObject":22,"../internal/isObjectLike":26,"../support":41,"./isArguments":29}],35:[function(_dereq_,module,exports){
var isObjectLike = _dereq_('../internal/isObjectLike');
/** `Object#toString` result references. */
var stringTag = '[object String]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
}
module.exports = isString;
},{"../internal/isObjectLike":26}],36:[function(_dereq_,module,exports){
var isLength = _dereq_('../internal/isLength'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
module.exports = isTypedArray;
},{"../internal/isLength":25,"../internal/isObjectLike":26}],37:[function(_dereq_,module,exports){
var baseCopy = _dereq_('../internal/baseCopy'),
keysIn = _dereq_('../object/keysIn');
/**
* Converts `value` to a plain object flattening inherited enumerable
* properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return baseCopy(value, keysIn(value));
}
module.exports = toPlainObject;
},{"../internal/baseCopy":10,"../object/keysIn":39}],38:[function(_dereq_,module,exports){
var getNative = _dereq_('../internal/getNative'),
isArrayLike = _dereq_('../internal/isArrayLike'),
isObject = _dereq_('../lang/isObject'),
shimKeys = _dereq_('../internal/shimKeys'),
support = _dereq_('../support');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeKeys = getNative(Object, 'keys');
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
var Ctor = object == null ? undefined : object.constructor;
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
module.exports = keys;
},{"../internal/getNative":20,"../internal/isArrayLike":21,"../internal/shimKeys":27,"../lang/isObject":33,"../support":41}],39:[function(_dereq_,module,exports){
var arrayEach = _dereq_('../internal/arrayEach'),
isArguments = _dereq_('../lang/isArguments'),
isArray = _dereq_('../lang/isArray'),
isFunction = _dereq_('../lang/isFunction'),
isIndex = _dereq_('../internal/isIndex'),
isLength = _dereq_('../internal/isLength'),
isObject = _dereq_('../lang/isObject'),
isString = _dereq_('../lang/isString'),
support = _dereq_('../support');
/** `Object#toString` result references. */
var arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
stringTag = '[object String]';
/** Used to fix the JScript `[[DontEnum]]` bug. */
var shadowProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used for native method references. */
var errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to avoid iterating over non-enumerable properties in IE < 9. */
var nonEnumProps = {};
nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true };
nonEnumProps[objectTag] = { 'constructor': true };
arrayEach(shadowProps, function(key) {
for (var tag in nonEnumProps) {
if (hasOwnProperty.call(nonEnumProps, tag)) {
var props = nonEnumProps[tag];
props[key] = hasOwnProperty.call(props, key);
}
}
});
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || isArguments(object) || isString(object)) && length) || 0;
var Ctor = object.constructor,
index = -1,
proto = (isFunction(Ctor) && Ctor.prototype) || objectProto,
isProto = proto === object,
result = Array(length),
skipIndexes = length > 0,
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error),
skipProto = support.enumPrototypes && isFunction(object);
while (++index < length) {
result[index] = (index + '');
}
// lodash skips the `constructor` property when it infers it's iterating
// over a `prototype` object because IE < 9 can't set the `[[Enumerable]]`
// attribute of an existing property and the `constructor` property of a
// prototype defaults to non-enumerable.
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name')) &&
!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)),
nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag];
if (tag == objectTag) {
proto = objectProto;
}
length = shadowProps.length;
while (length--) {
key = shadowProps[length];
var nonEnum = nonEnums[key];
if (!(isProto && nonEnum) &&
(nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) {
result.push(key);
}
}
}
return result;
}
module.exports = keysIn;
},{"../internal/arrayEach":9,"../internal/isIndex":23,"../internal/isLength":25,"../lang/isArguments":29,"../lang/isArray":30,"../lang/isFunction":31,"../lang/isObject":33,"../lang/isString":35,"../support":41}],40:[function(_dereq_,module,exports){
var baseMerge = _dereq_('../internal/baseMerge'),
createAssigner = _dereq_('../internal/createAssigner');
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* overwrite property assignments of previous sources. If `customizer` is
* provided it's invoked to produce the merged values of the destination and
* source properties. If `customizer` returns `undefined` merging is handled
* by the method instead. The `customizer` is bound to `thisArg` and invoked
* with five arguments: (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* var users = {
* 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
* };
*
* var ages = {
* 'data': [{ 'age': 36 }, { 'age': 40 }]
* };
*
* _.merge(users, ages);
* // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
*
* // using a customizer callback
* var object = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var other = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(object, other, function(a, b) {
* if (_.isArray(a)) {
* return a.concat(b);
* }
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
*/
var merge = createAssigner(baseMerge);
module.exports = merge;
},{"../internal/baseMerge":13,"../internal/createAssigner":17}],41:[function(_dereq_,module,exports){
/** Used for native method references. */
var arrayProto = Array.prototype,
errorProto = Error.prototype,
objectProto = Object.prototype;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/**
* An object environment feature flags.
*
* @static
* @memberOf _
* @type Object
*/
var support = {};
(function(x) {
var Ctor = function() { this.x = x; },
object = { '0': x, 'length': x },
props = [];
Ctor.prototype = { 'valueOf': x, 'y': x };
for (var key in new Ctor) { props.push(key); }
/**
* Detect if `name` or `message` properties of `Error.prototype` are
* enumerable by default (IE < 9, Safari < 5.1).
*
* @memberOf _.support
* @type boolean
*/
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') ||
propertyIsEnumerable.call(errorProto, 'name');
/**
* Detect if `prototype` properties are enumerable by default.
*
* Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
* (if the prototype or a property on the prototype has been set)
* incorrectly set the `[[Enumerable]]` value of a function's `prototype`
* property to `true`.
*
* @memberOf _.support
* @type boolean
*/
support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype');
/**
* Detect if properties shadowing those on `Object.prototype` are non-enumerable.
*
* In IE < 9 an object's own properties, shadowing non-enumerable ones,
* are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumShadows = !/valueOf/.test(props);
/**
* Detect if own properties are iterated after inherited properties (IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.ownLast = props[0] != 'x';
/**
* Detect if `Array#shift` and `Array#splice` augment array-like objects
* correctly.
*
* Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array
* `shift()` and `splice()` functions that fail to remove the last element,
* `value[0]`, of array-like objects even though the "length" property is
* set to `0`. The `shift()` method is buggy in compatibility modes of IE 8,
* while `splice()` is buggy regardless of mode in IE < 9.
*
* @memberOf _.support
* @type boolean
*/
support.spliceObjects = (splice.call(object, 0, 1), !object[0]);
/**
* Detect lack of support for accessing string characters by index.
*
* IE < 8 can't access characters by index. IE 8 can only access characters
* by index on string literals, not string objects.
*
* @memberOf _.support
* @type boolean
*/
support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx';
}(1, 0));
module.exports = support;
},{}],42:[function(_dereq_,module,exports){
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
},{}],43:[function(_dereq_,module,exports){
'use strict';
// modified from https://github.com/es-shims/es6-shim
var keys = _dereq_('object-keys');
var canBeObject = function (obj) {
return typeof obj !== 'undefined' && obj !== null;
};
var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
var defineProperties = _dereq_('define-properties');
var toObject = Object;
var push = Array.prototype.push;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
var assignShim = function assign(target, source1) {
if (!canBeObject(target)) { throw new TypeError('target must be an object'); }
var objTarget = toObject(target);
var s, source, i, props, syms;
for (s = 1; s < arguments.length; ++s) {
source = toObject(arguments[s]);
props = keys(source);
if (hasSymbols && Object.getOwnPropertySymbols) {
syms = Object.getOwnPropertySymbols(source);
for (i = 0; i < syms.length; ++i) {
if (propIsEnumerable.call(source, syms[i])) {
push.call(props, syms[i]);
}
}
}
for (i = 0; i < props.length; ++i) {
objTarget[props[i]] = source[props[i]];
}
}
return objTarget;
};
defineProperties(assignShim, {
shim: function shimObjectAssign() {
var assignHasPendingExceptions = function () {
if (!Object.assign || !Object.preventExtensions) {
return false;
}
// Firefox 37 still has "pending exception" logic in its Object.assign implementation,
// which is 72% slower than our shim, and Firefox 40's native implementation.
var thrower = Object.preventExtensions({ 1: 2 });
try {
Object.assign(thrower, 'xy');
} catch (e) {
return thrower[1] === 'y';
}
};
defineProperties(
Object,
{ assign: assignShim },
{ assign: assignHasPendingExceptions }
);
return Object.assign || assignShim;
}
});
module.exports = assignShim;
},{"define-properties":44,"object-keys":46}],44:[function(_dereq_,module,exports){
'use strict';
var keys = _dereq_('object-keys');
var foreach = _dereq_('foreach');
var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
var toStr = Object.prototype.toString;
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};
var arePropertyDescriptorsSupported = function () {
var obj = {};
try {
Object.defineProperty(obj, 'x', { value: obj, enumerable: false });
/* eslint-disable no-unused-vars */
for (var _ in obj) { return false; }
/* eslint-enable no-unused-vars */
return obj.x === obj;
} catch (e) { /* this is IE 8. */
return false;
}
};
var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported();
var defineProperty = function (object, name, value, predicate) {
if (name in object && (!isFunction(predicate) || !predicate())) {
return;
}
if (supportsDescriptors) {
Object.defineProperty(object, name, {
configurable: true,
enumerable: false,
writable: true,
value: value
});
} else {
object[name] = value;
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = keys(map);
if (hasSymbols) {
props = props.concat(Object.getOwnPropertySymbols(map));
}
foreach(props, function (name) {
defineProperty(object, name, map[name], predicates[name]);
});
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
},{"foreach":45,"object-keys":46}],45:[function(_dereq_,module,exports){
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
},{}],46:[function(_dereq_,module,exports){
'use strict';
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = _dereq_('./isArguments');
var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString');
var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var blacklistedKeys = {
$window: true,
$console: true,
$parent: true,
$self: true,
$frames: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' && !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (!Object.keys) {
Object.keys = keysShim;
} else {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
}
return Object.keys || keysShim;
};
module.exports = keysShim;
},{"./isArguments":47}],47:[function(_dereq_,module,exports){
'use strict';
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
},{}],48:[function(_dereq_,module,exports){
module.exports = SafeParseTuple
function SafeParseTuple(obj, reviver) {
var json
var error = null
try {
json = JSON.parse(obj, reviver)
} catch (err) {
error = err
}
return [error, json]
}
},{}],49:[function(_dereq_,module,exports){
function clean (s) {
return s.replace(/\n\r?\s*/g, '')
}
module.exports = function tsml (sa) {
var s = ''
, i = 0
for (; i < arguments.length; i++)
s += clean(sa[i]) + (arguments[i + 1] || '')
return s
}
},{}],50:[function(_dereq_,module,exports){
"use strict";
var window = _dereq_("global/window")
var once = _dereq_("once")
var parseHeaders = _dereq_("parse-headers")
module.exports = createXHR
createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
function isEmpty(obj){
for(var i in obj){
if(obj.hasOwnProperty(i)) return false
}
return true
}
function createXHR(options, callback) {
function readystatechange() {
if (xhr.readyState === 4) {
loadFunc()
}
}
function getBody() {
// Chrome with requestType=blob throws errors arround when even testing access to responseText
var body = undefined
if (xhr.response) {
body = xhr.response
} else if (xhr.responseType === "text" || !xhr.responseType) {
body = xhr.responseText || xhr.responseXML
}
if (isJson) {
try {
body = JSON.parse(body)
} catch (e) {}
}
return body
}
var failureResponse = {
body: undefined,
headers: {},
statusCode: 0,
method: method,
url: uri,
rawRequest: xhr
}
function errorFunc(evt) {
clearTimeout(timeoutTimer)
if(!(evt instanceof Error)){
evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
}
evt.statusCode = 0
callback(evt, failureResponse)
}
// will load the data & process the response in a special response object
function loadFunc() {
if (aborted) return
var status
clearTimeout(timeoutTimer)
if(options.useXDR && xhr.status===undefined) {
//IE8 CORS GET successful response doesn't have a status field, but body is fine
status = 200
} else {
status = (xhr.status === 1223 ? 204 : xhr.status)
}
var response = failureResponse
var err = null
if (status !== 0){
response = {
body: getBody(),
statusCode: status,
method: method,
headers: {},
url: uri,
rawRequest: xhr
}
if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
response.headers = parseHeaders(xhr.getAllResponseHeaders())
}
} else {
err = new Error("Internal XMLHttpRequest Error")
}
callback(err, response, response.body)
}
if (typeof options === "string") {
options = { uri: options }
}
options = options || {}
if(typeof callback === "undefined"){
throw new Error("callback argument missing")
}
callback = once(callback)
var xhr = options.xhr || null
if (!xhr) {
if (options.cors || options.useXDR) {
xhr = new createXHR.XDomainRequest()
}else{
xhr = new createXHR.XMLHttpRequest()
}
}
var key
var aborted
var uri = xhr.url = options.uri || options.url
var method = xhr.method = options.method || "GET"
var body = options.body || options.data
var headers = xhr.headers = options.headers || {}
var sync = !!options.sync
var isJson = false
var timeoutTimer
if ("json" in options) {
isJson = true
headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
if (method !== "GET" && method !== "HEAD") {
headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
body = JSON.stringify(options.json)
}
}
xhr.onreadystatechange = readystatechange
xhr.onload = loadFunc
xhr.onerror = errorFunc
// IE9 must have onprogress be set to a unique function.
xhr.onprogress = function () {
// IE must die
}
xhr.ontimeout = errorFunc
xhr.open(method, uri, !sync, options.username, options.password)
//has to be after open
if(!sync) {
xhr.withCredentials = !!options.withCredentials
}
// Cannot set timeout with sync request
// not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
// both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
if (!sync && options.timeout > 0 ) {
timeoutTimer = setTimeout(function(){
aborted=true//IE9 may still call readystatechange
xhr.abort("timeout")
var e = new Error("XMLHttpRequest timeout")
e.code = "ETIMEDOUT"
errorFunc(e)
}, options.timeout )
}
if (xhr.setRequestHeader) {
for(key in headers){
if(headers.hasOwnProperty(key)){
xhr.setRequestHeader(key, headers[key])
}
}
} else if (options.headers && !isEmpty(options.headers)) {
throw new Error("Headers cannot be set on an XDomainRequest object")
}
if ("responseType" in options) {
xhr.responseType = options.responseType
}
if ("beforeSend" in options &&
typeof options.beforeSend === "function"
) {
options.beforeSend(xhr)
}
xhr.send(body)
return xhr
}
function noop() {}
},{"global/window":2,"once":51,"parse-headers":55}],51:[function(_dereq_,module,exports){
module.exports = once
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
})
function once (fn) {
var called = false
return function () {
if (called) return
called = true
return fn.apply(this, arguments)
}
}
},{}],52:[function(_dereq_,module,exports){
var isFunction = _dereq_('is-function')
module.exports = forEach
var toString = Object.prototype.toString
var hasOwnProperty = Object.prototype.hasOwnProperty
function forEach(list, iterator, context) {
if (!isFunction(iterator)) {
throw new TypeError('iterator must be a function')
}
if (arguments.length < 3) {
context = this
}
if (toString.call(list) === '[object Array]')
forEachArray(list, iterator, context)
else if (typeof list === 'string')
forEachString(list, iterator, context)
else
forEachObject(list, iterator, context)
}
function forEachArray(array, iterator, context) {
for (var i = 0, len = array.length; i < len; i++) {
if (hasOwnProperty.call(array, i)) {
iterator.call(context, array[i], i, array)
}
}
}
function forEachString(string, iterator, context) {
for (var i = 0, len = string.length; i < len; i++) {
// no such thing as a sparse string.
iterator.call(context, string.charAt(i), i, string)
}
}
function forEachObject(object, iterator, context) {
for (var k in object) {
if (hasOwnProperty.call(object, k)) {
iterator.call(context, object[k], k, object)
}
}
}
},{"is-function":53}],53:[function(_dereq_,module,exports){
module.exports = isFunction
var toString = Object.prototype.toString
function isFunction (fn) {
var string = toString.call(fn)
return string === '[object Function]' ||
(typeof fn === 'function' && string !== '[object RegExp]') ||
(typeof window !== 'undefined' &&
// IE8 and below
(fn === window.setTimeout ||
fn === window.alert ||
fn === window.confirm ||
fn === window.prompt))
};
},{}],54:[function(_dereq_,module,exports){
exports = module.exports = trim;
function trim(str){
return str.replace(/^\s*|\s*$/g, '');
}
exports.left = function(str){
return str.replace(/^\s*/, '');
};
exports.right = function(str){
return str.replace(/\s*$/, '');
};
},{}],55:[function(_dereq_,module,exports){
var trim = _dereq_('trim')
, forEach = _dereq_('for-each')
, isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
}
module.exports = function (headers) {
if (!headers)
return {}
var result = {}
forEach(
trim(headers).split('\n')
, function (row) {
var index = row.indexOf(':')
, key = trim(row.slice(0, index)).toLowerCase()
, value = trim(row.slice(index + 1))
if (typeof(result[key]) === 'undefined') {
result[key] = value
} else if (isArray(result[key])) {
result[key].push(value)
} else {
result[key] = [ result[key], value ]
}
}
)
return result
}
},{"for-each":52,"trim":54}],56:[function(_dereq_,module,exports){
/**
* @file big-play-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('./button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('./component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Initial play button. Shows before the video has played. The hiding of the
* big play button is done via CSS and player states.
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Button
* @class BigPlayButton
*/
var BigPlayButton = (function (_Button) {
_inherits(BigPlayButton, _Button);
function BigPlayButton(player, options) {
_classCallCheck(this, BigPlayButton);
_Button.call(this, player, options);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
BigPlayButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-big-play-button';
};
/**
* Handles click for play
*
* @method handleClick
*/
BigPlayButton.prototype.handleClick = function handleClick() {
this.player_.play();
};
return BigPlayButton;
})(_buttonJs2['default']);
BigPlayButton.prototype.controlText_ = 'Play Video';
_componentJs2['default'].registerComponent('BigPlayButton', BigPlayButton);
exports['default'] = BigPlayButton;
module.exports = exports['default'];
},{"./button.js":57,"./component.js":58}],57:[function(_dereq_,module,exports){
/**
* @file button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* Base class for all buttons
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Component
* @class Button
*/
var Button = (function (_Component) {
_inherits(Button, _Component);
function Button(player, options) {
_classCallCheck(this, Button);
_Component.call(this, player, options);
this.emitTapEvents();
this.on('tap', this.handleClick);
this.on('click', this.handleClick);
this.on('focus', this.handleFocus);
this.on('blur', this.handleBlur);
}
/**
* Create the component's DOM element
*
* @param {String=} type Element's node type. e.g. 'div'
* @param {Object=} props An object of element attributes that should be set on the element Tag name
* @return {Element}
* @method createEl
*/
Button.prototype.createEl = function createEl() {
var tag = arguments.length <= 0 || arguments[0] === undefined ? 'button' : arguments[0];
var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
props = _objectAssign2['default']({
className: this.buildCSSClass(),
tabIndex: 0
}, props);
// Add standard Aria info
attributes = _objectAssign2['default']({
role: 'button',
type: 'button', // Necessary since the default button type is "submit"
'aria-live': 'polite' // let the screen reader user know that the text of the button may change
}, attributes);
var el = _Component.prototype.createEl.call(this, tag, props, attributes);
this.controlTextEl_ = Dom.createEl('span', {
className: 'vjs-control-text'
});
el.appendChild(this.controlTextEl_);
this.controlText(this.controlText_);
return el;
};
/**
* Controls text - both request and localize
*
* @param {String} text Text for button
* @return {String}
* @method controlText
*/
Button.prototype.controlText = function controlText(text) {
if (!text) return this.controlText_ || 'Need Text';
this.controlText_ = text;
this.controlTextEl_.innerHTML = this.localize(this.controlText_);
return this;
};
/**
* Allows sub components to stack CSS class names
*
* @return {String}
* @method buildCSSClass
*/
Button.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Handle Click - Override with specific functionality for button
*
* @method handleClick
*/
Button.prototype.handleClick = function handleClick() {};
/**
* Handle Focus - Add keyboard functionality to element
*
* @method handleFocus
*/
Button.prototype.handleFocus = function handleFocus() {
Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress));
};
/**
* Handle KeyPress (document level) - Trigger click when keys are pressed
*
* @method handleKeyPress
*/
Button.prototype.handleKeyPress = function handleKeyPress(event) {
// Check for space bar (32) or enter (13) keys
if (event.which === 32 || event.which === 13) {
event.preventDefault();
this.handleClick(event);
}
};
/**
* Handle Blur - Remove keyboard triggers
*
* @method handleBlur
*/
Button.prototype.handleBlur = function handleBlur() {
Events.off(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress));
};
return Button;
})(_component2['default']);
_component2['default'].registerComponent('Button', Button);
exports['default'] = Button;
module.exports = exports['default'];
},{"./component":58,"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"global/document":1,"object.assign":43}],58:[function(_dereq_,module,exports){
/**
* @file component.js
*
* Player Component - Base class for all UI objects
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsGuidJs = _dereq_('./utils/guid.js');
var Guid = _interopRequireWildcard(_utilsGuidJs);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsLogJs = _dereq_('./utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
/**
* 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.
* ```js
* // adding a button to the player
* var button = player.addChild('button');
* button.el(); // -> button element
* ```
* ```html
* <div class="video-js">
* <div class="vjs-button">Button</div>
* </div>
* ```
* Components are also event targets.
* ```js
* button.on('click', function(){
* console.log('Button Clicked!');
* });
* button.trigger('customevent');
* ```
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @class Component
*/
var Component = (function () {
function Component(player, options, ready) {
_classCallCheck(this, Component);
// The component might be the player itself and we can't pass `this` to super
if (!player && this.play) {
this.player_ = player = this; // eslint-disable-line
} else {
this.player_ = player;
}
// Make a copy of prototype.options_ to protect against overriding defaults
this.options_ = _utilsMergeOptionsJs2['default']({}, this.options_);
// Updated options with supplied options
options = this.options_ = _utilsMergeOptionsJs2['default'](this.options_, options);
// Get ID from options or options element if one is supplied
this.id_ = options.id || options.el && options.el.id;
// If there was no ID from the options, generate one
if (!this.id_) {
// Don't require the player ID function in the case of mock players
var id = player && player.id && player.id() || 'no_player';
this.id_ = id + '_component_' + Guid.newGUID();
}
this.name_ = options.name || null;
// Create element if one wasn't provided in options
if (options.el) {
this.el_ = options.el;
} else if (options.createEl !== false) {
this.el_ = this.createEl();
}
this.children_ = [];
this.childIndex_ = {};
this.childNameIndex_ = {};
// Add any child components in options
if (options.initChildren !== false) {
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
*
* @method dispose
*/
Component.prototype.dispose = function dispose() {
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_);
}
Dom.removeElData(this.el_);
this.el_ = null;
};
/**
* Return the component's player
*
* @return {Player}
* @method player
*/
Component.prototype.player = function player() {
return this.player_;
};
/**
* Deep merge of options objects
* Whenever a property is an object on both options objects
* the two properties will be merged using mergeOptions.
* 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.
* ```js
* 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
* ```js
* {
* 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
* @method options
*/
Component.prototype.options = function options(obj) {
_utilsLogJs2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0');
if (!obj) {
return this.options_;
}
this.options_ = _utilsMergeOptionsJs2['default'](this.options_, obj);
return this.options_;
};
/**
* Get the component's DOM element
* ```js
* var domEl = myComponent.el();
* ```
*
* @return {Element}
* @method el
*/
Component.prototype.el = function el() {
return this.el_;
};
/**
* Create the component's DOM element
*
* @param {String=} tagName Element's node type. e.g. 'div'
* @param {Object=} properties An object of properties that should be set
* @param {Object=} attributes An object of attributes that should be set
* @return {Element}
* @method createEl
*/
Component.prototype.createEl = function createEl(tagName, properties, attributes) {
return Dom.createEl(tagName, properties, attributes);
};
Component.prototype.localize = function localize(string) {
var code = this.player_.language && this.player_.language();
var languages = this.player_.languages && this.player_.languages();
if (!code || !languages) {
return string;
}
var language = languages[code];
if (language && language[string]) {
return language[string];
}
var primaryCode = code.split('-')[0];
var primaryLang = languages[primaryCode];
if (primaryLang && primaryLang[string]) {
return primaryLang[string];
}
return string;
};
/**
* Return the component's DOM element where children are inserted.
* Will either be the same as el() or a new element defined in createEl().
*
* @return {Element}
* @method contentEl
*/
Component.prototype.contentEl = function contentEl() {
return this.contentEl_ || this.el_;
};
/**
* Get the component's ID
* ```js
* var id = myComponent.id();
* ```
*
* @return {String}
* @method id
*/
Component.prototype.id = function id() {
return this.id_;
};
/**
* Get the component's name. The name is often used to reference the component.
* ```js
* var name = myComponent.name();
* ```
*
* @return {String}
* @method name
*/
Component.prototype.name = function name() {
return this.name_;
};
/**
* Get an array of all child components
* ```js
* var kids = myComponent.children();
* ```
*
* @return {Array} The children
* @method children
*/
Component.prototype.children = function children() {
return this.children_;
};
/**
* Returns a child component with the provided ID
*
* @return {Component}
* @method getChildById
*/
Component.prototype.getChildById = function getChildById(id) {
return this.childIndex_[id];
};
/**
* Returns a child component with the provided name
*
* @return {Component}
* @method getChild
*/
Component.prototype.getChild = function getChild(name) {
return this.childNameIndex_[name];
};
/**
* Adds a child component inside this component
* ```js
* myComponent.el();
* // -> <div class='my-component'></div>
* myComponent.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
* ```js
* var myButton = myComponent.addChild('MyButton', {
* text: 'Press Me',
* children: {
* buttonChildExample: {
* buttonChildOption: true
* }
* }
* });
* ```
*
* @param {String|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 {Component} The child component (created by this process if a string was used)
* @method addChild
*/
Component.prototype.addChild = function addChild(child) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var component = undefined;
var componentName = undefined;
// If child is a string, create nt with options
if (typeof child === 'string') {
componentName = child;
// Options can also be specified as a boolean, so convert to an empty object if false.
if (!options) {
options = {};
}
// Same as above, but true is deprecated so show a warning.
if (options === true) {
_utilsLogJs2['default'].warn('Initializing a child component with `true` is deprecated. Children should be defined in an array when possible, but if necessary use an object instead of `true`.');
options = {};
}
// If no componentClass in options, assume componentClass is the name lowercased
// (e.g. playButton)
var componentClassName = options.componentClass || _utilsToTitleCaseJs2['default'](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
var ComponentClass = Component.getComponent(componentClassName);
component = new 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 {Component} component Component to remove
* @method removeChild
*/
Component.prototype.removeChild = function removeChild(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
* ```js
* // 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
* ```js
* 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).
* ```js
* var myComp = new MyComponent(player, {
* children: [
* 'button',
* {
* name: 'button',
* someOtherOption: true
* }
* ]
* });
* ```
*
* @method initChildren
*/
Component.prototype.initChildren = function initChildren() {
var _this = this;
var children = this.options_.children;
if (children) {
(function () {
// `this` is `parent`
var parentOptions = _this.options_;
var handleAdd = function handleAdd(name, opts) {
// Allow options for children to be set at the parent options
// e.g. videojs(id, { controlBar: false });
// instead of videojs(id, { children: { controlBar: false });
if (parentOptions[name] !== undefined) {
opts = parentOptions[name];
}
// Allow for disabling default components
// e.g. options['children']['posterImage'] = false
if (opts === false) {
return;
}
// Allow options to be passed as a simple boolean if no configuration
// is necessary.
if (opts === true) {
opts = {};
}
// We also want to pass the original player options to each component as well so they don't need to
// reach back into the player for options later.
opts.playerOptions = _this.options_.playerOptions;
// Create and add the child component.
// Add a direct reference to the child by name on the parent instance.
// If two of the same component are used, different names should be supplied
// for each
_this[name] = _this.addChild(name, opts);
};
// Allow for an array of children details to passed in the options
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = children[i];
var _name = undefined;
var opts = undefined;
if (typeof child === 'string') {
// ['myComponent']
_name = child;
opts = {};
} else {
// [{ name: 'myComponent', otherOption: true }]
_name = child.name;
opts = child;
}
handleAdd(_name, opts);
}
} else {
Object.getOwnPropertyNames(children).forEach(function (name) {
handleAdd(name, children[name]);
});
}
})();
}
};
/**
* Allows sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
Component.prototype.buildCSSClass = function buildCSSClass() {
// Child classes can include a function that does:
// return 'CLASS NAME' + this._super();
return '';
};
/**
* Add an event listener to this component's element
* ```js
* var myFunc = function(){
* var myComponent = this;
* // Do something when the event is fired
* };
*
* myComponent.on('eventType', myFunc);
* ```
* The context of myFunc will be myComponent unless previously bound.
* Alternatively, you can add a listener to another element or component.
* ```js
* myComponent.on(otherElement, 'eventName', myFunc);
* myComponent.on(otherComponent, 'eventName', myFunc);
* ```
* The benefit of using this over `VjsEvents.on(otherElement, 'eventName', myFunc)`
* and `otherComponent.on('eventName', myFunc)` is that this way the listeners
* will be automatically cleaned up when either component is disposed.
* It will also bind myComponent as the context of myFunc.
* **NOTE**: When using this on elements in the page other than window
* and document (both permanent), if you remove the element from the DOM
* you need to call `myComponent.trigger(el, 'dispose')` on it to clean up
* references to it and allow the browser to garbage collect it.
*
* @param {String|Component} first The event type or other component
* @param {Function|String} second The event handler or event type
* @param {Function} third The event handler
* @return {Component}
* @method on
*/
Component.prototype.on = function on(first, second, third) {
var _this2 = this;
if (typeof first === 'string' || Array.isArray(first)) {
Events.on(this.el_, first, Fn.bind(this, second));
// Targeting another component or element
} else {
(function () {
var target = first;
var type = second;
var fn = Fn.bind(_this2, third);
// When this component is disposed, remove the listener from the other component
var removeOnDispose = function removeOnDispose() {
return _this2.off(target, type, fn);
};
// Use the same function ID so we can remove it later it using the ID
// of the original listener
removeOnDispose.guid = fn.guid;
_this2.on('dispose', removeOnDispose);
// If the other component is disposed first we need to clean the reference
// to the other component in this component's removeOnDispose listener
// Otherwise we create a memory leak.
var cleanRemover = function cleanRemover() {
return _this2.off('dispose', removeOnDispose);
};
// Add the same function ID so we can easily remove it later
cleanRemover.guid = fn.guid;
// Check if this is a DOM node
if (first.nodeName) {
// Add the listener to the other element
Events.on(target, type, fn);
Events.on(target, 'dispose', cleanRemover);
// Should be a component
// Not using `instanceof Component` because it makes mock players difficult
} else if (typeof first.on === 'function') {
// Add the listener to the other component
target.on(type, fn);
target.on('dispose', cleanRemover);
}
})();
}
return this;
};
/**
* Remove an event listener from this component's element
* ```js
* myComponent.off('eventType', myFunc);
* ```
* If myFunc is excluded, ALL listeners for the event type will be removed.
* If eventType is excluded, ALL listeners will be removed from the component.
* Alternatively you can use `off` to remove listeners that were added to other
* elements or components using `myComponent.on(otherComponent...`.
* In this case both the event type and listener function are REQUIRED.
* ```js
* myComponent.off(otherElement, 'eventType', myFunc);
* myComponent.off(otherComponent, 'eventType', myFunc);
* ```
*
* @param {String=|Component} first The event type or other component
* @param {Function=|String} second The listener function or event type
* @param {Function=} third The listener for other component
* @return {Component}
* @method off
*/
Component.prototype.off = function off(first, second, third) {
if (!first || typeof first === 'string' || Array.isArray(first)) {
Events.off(this.el_, first, second);
} else {
var target = first;
var type = second;
// Ensure there's at least a guid, even if the function hasn't been used
var fn = Fn.bind(this, third);
// Remove the dispose listener on this component,
// which was given the same guid as the event listener
this.off('dispose', fn);
if (first.nodeName) {
// Remove the listener
Events.off(target, type, fn);
// Remove the listener for cleaning the dispose listener
Events.off(target, 'dispose', fn);
} else {
target.off(type, fn);
target.off('dispose', fn);
}
}
return this;
};
/**
* Add an event listener to be triggered only once and then removed
* ```js
* myComponent.one('eventName', myFunc);
* ```
* Alternatively you can add a listener to another element or component
* that will be triggered only once.
* ```js
* myComponent.one(otherElement, 'eventName', myFunc);
* myComponent.one(otherComponent, 'eventName', myFunc);
* ```
*
* @param {String|Component} first The event type or other component
* @param {Function|String} second The listener function or event type
* @param {Function=} third The listener function for other component
* @return {Component}
* @method one
*/
Component.prototype.one = function one(first, second, third) {
var _this3 = this,
_arguments = arguments;
if (typeof first === 'string' || Array.isArray(first)) {
Events.one(this.el_, first, Fn.bind(this, second));
} else {
(function () {
var target = first;
var type = second;
var fn = Fn.bind(_this3, third);
var newFunc = function newFunc() {
_this3.off(target, type, newFunc);
fn.apply(null, _arguments);
};
// Keep the same function ID so we can remove it later
newFunc.guid = fn.guid;
_this3.on(target, type, newFunc);
})();
}
return this;
};
/**
* Trigger an event on an element
* ```js
* myComponent.trigger('eventName');
* myComponent.trigger({'type':'eventName'});
* myComponent.trigger('eventName', {data: 'some data'});
* myComponent.trigger({'type':'eventName'}, {data: 'some data'});
* ```
*
* @param {Event|Object|String} event A string (the type) or an event object with a type attribute
* @param {Object} [hash] data hash to pass along with the event
* @return {Component} self
* @method trigger
*/
Component.prototype.trigger = function trigger(event, hash) {
Events.trigger(this.el_, event, hash);
return this;
};
/**
* Bind a listener to the component's ready state.
* Different from event listeners in that if the ready event has already happened
* it will trigger the function immediately.
*
* @param {Function} fn Ready listener
* @param {Boolean} sync Exec the listener synchronously if component is ready
* @return {Component}
* @method ready
*/
Component.prototype.ready = function ready(fn) {
var sync = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (fn) {
if (this.isReady_) {
if (sync) {
fn.call(this);
} else {
// Call the function asynchronously by default for consistency
this.setTimeout(fn, 1);
}
} else {
this.readyQueue_ = this.readyQueue_ || [];
this.readyQueue_.push(fn);
}
}
return this;
};
/**
* Trigger the ready listeners
*
* @return {Component}
* @method triggerReady
*/
Component.prototype.triggerReady = function triggerReady() {
this.isReady_ = true;
// Ensure ready is triggerd asynchronously
this.setTimeout(function () {
var readyQueue = this.readyQueue_;
if (readyQueue && readyQueue.length > 0) {
readyQueue.forEach(function (fn) {
fn.call(this);
}, this);
// Reset Ready Queue
this.readyQueue_ = [];
}
// Allow for using event listeners also
this.trigger('ready');
}, 1);
};
/**
* Check if a component's element has a CSS class name
*
* @param {String} classToCheck Classname to check
* @return {Component}
* @method hasClass
*/
Component.prototype.hasClass = function hasClass(classToCheck) {
return Dom.hasElClass(this.el_, classToCheck);
};
/**
* Add a CSS class name to the component's element
*
* @param {String} classToAdd Classname to add
* @return {Component}
* @method addClass
*/
Component.prototype.addClass = function addClass(classToAdd) {
Dom.addElClass(this.el_, classToAdd);
return this;
};
/**
* Remove and return a CSS class name from the component's element
*
* @param {String} classToRemove Classname to remove
* @return {Component}
* @method removeClass
*/
Component.prototype.removeClass = function removeClass(classToRemove) {
Dom.removeElClass(this.el_, classToRemove);
return this;
};
/**
* Show the component element if hidden
*
* @return {Component}
* @method show
*/
Component.prototype.show = function show() {
this.removeClass('vjs-hidden');
return this;
};
/**
* Hide the component element if currently showing
*
* @return {Component}
* @method hide
*/
Component.prototype.hide = function hide() {
this.addClass('vjs-hidden');
return this;
};
/**
* Lock an item in its visible state
* To be used with fadeIn/fadeOut.
*
* @return {Component}
* @private
* @method lockShowing
*/
Component.prototype.lockShowing = function lockShowing() {
this.addClass('vjs-lock-showing');
return this;
};
/**
* Unlock an item to be hidden
* To be used with fadeIn/fadeOut.
*
* @return {Component}
* @private
* @method unlockShowing
*/
Component.prototype.unlockShowing = function unlockShowing() {
this.removeClass('vjs-lock-showing');
return this;
};
/**
* 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 {Component} This component, when setting the width
* @return {Number|String} The width, when getting
* @method width
*/
Component.prototype.width = function width(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 {Component} This component, when setting the height
* @return {Number|String} The height, when getting
* @method height
*/
Component.prototype.height = function height(num, skipListeners) {
return this.dimension('height', num, skipListeners);
};
/**
* Set both width and height at the same time
*
* @param {Number|String} width Width of player
* @param {Number|String} height Height of player
* @return {Component} The component
* @method dimensions
*/
Component.prototype.dimensions = function dimensions(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 {Component} The component if a dimension was set
* @return {Number|String} The dimension if nothing was set
* @private
* @method dimension
*/
Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) {
if (num !== undefined) {
// Set to zero if null or literally NaN (NaN !== NaN)
if (num === null || num !== 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
return parseInt(this.el_['offset' + _utilsToTitleCaseJs2['default'](widthOrHeight)], 10);
};
/**
* Emit 'tap' events when touch events are supported
* This is used to support toggling the controls through a tap on the video.
* We're requiring them to be enabled because otherwise every component would
* have this extra overhead unnecessarily, on mobile devices where extra
* overhead is especially bad.
*
* @private
* @method emitTapEvents
*/
Component.prototype.emitTapEvents = function emitTapEvents() {
// Track the start time so we can determine how long the touch lasted
var touchStart = 0;
var firstTouch = null;
// Maximum movement allowed during a touch event to still be considered a tap
// Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number.
var tapMovementThreshold = 10;
// The maximum length a touch can be while still being considered a tap
var touchTimeThreshold = 200;
var couldBeTap = undefined;
this.on('touchstart', function (event) {
// If more than one finger, don't consider treating this as a click
if (event.touches.length === 1) {
// Copy the touches object to prevent modifying the original
firstTouch = _objectAssign2['default']({}, 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
var xdiff = event.touches[0].pageX - firstTouch.pageX;
var ydiff = event.touches[0].pageY - firstTouch.pageY;
var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
if (touchDistance > tapMovementThreshold) {
couldBeTap = false;
}
}
});
var noTap = function noTap() {
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
var touchTime = new Date().getTime() - touchStart;
// Make sure the touch was less than the threshold to be considered a tap
if (touchTime < touchTimeThreshold) {
// Don't let browser turn this into a click
event.preventDefault();
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
// Events.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.
*
* @method enableTouchActivity
*/
Component.prototype.enableTouchActivity = function enableTouchActivity() {
// Don't continue if the root player doesn't support reporting user activity
if (!this.player() || !this.player().reportUserActivity) {
return;
}
// listener for reporting that the user is active
var report = Fn.bind(this.player(), this.player().reportUserActivity);
var touchHolding = undefined;
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
this.clearInterval(touchHolding);
// report at the same interval as activityCheck
touchHolding = this.setInterval(report, 250);
});
var touchEnd = function touchEnd(event) {
report();
// stop the interval that maintains activity if the touch is holding
this.clearInterval(touchHolding);
};
this.on('touchmove', report);
this.on('touchend', touchEnd);
this.on('touchcancel', touchEnd);
};
/**
* Creates timeout and sets up disposal automatically.
*
* @param {Function} fn The function to run after the timeout.
* @param {Number} timeout Number of ms to delay before executing specified function.
* @return {Number} Returns the timeout ID
* @method setTimeout
*/
Component.prototype.setTimeout = function setTimeout(fn, timeout) {
fn = Fn.bind(this, fn);
// window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't.
var timeoutId = _globalWindow2['default'].setTimeout(fn, timeout);
var disposeFn = function disposeFn() {
this.clearTimeout(timeoutId);
};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.on('dispose', disposeFn);
return timeoutId;
};
/**
* Clears a timeout and removes the associated dispose listener
*
* @param {Number} timeoutId The id of the timeout to clear
* @return {Number} Returns the timeout ID
* @method clearTimeout
*/
Component.prototype.clearTimeout = function clearTimeout(timeoutId) {
_globalWindow2['default'].clearTimeout(timeoutId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.off('dispose', disposeFn);
return timeoutId;
};
/**
* Creates an interval and sets up disposal automatically.
*
* @param {Function} fn The function to run every N seconds.
* @param {Number} interval Number of ms to delay before executing specified function.
* @return {Number} Returns the interval ID
* @method setInterval
*/
Component.prototype.setInterval = function setInterval(fn, interval) {
fn = Fn.bind(this, fn);
var intervalId = _globalWindow2['default'].setInterval(fn, interval);
var disposeFn = function disposeFn() {
this.clearInterval(intervalId);
};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.on('dispose', disposeFn);
return intervalId;
};
/**
* Clears an interval and removes the associated dispose listener
*
* @param {Number} intervalId The id of the interval to clear
* @return {Number} Returns the interval ID
* @method clearInterval
*/
Component.prototype.clearInterval = function clearInterval(intervalId) {
_globalWindow2['default'].clearInterval(intervalId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.off('dispose', disposeFn);
return intervalId;
};
/**
* Registers a component
*
* @param {String} name Name of the component to register
* @param {Object} comp The component to register
* @static
* @method registerComponent
*/
Component.registerComponent = function registerComponent(name, comp) {
if (!Component.components_) {
Component.components_ = {};
}
Component.components_[name] = comp;
return comp;
};
/**
* Gets a component by name
*
* @param {String} name Name of the component to get
* @return {Component}
* @static
* @method getComponent
*/
Component.getComponent = function getComponent(name) {
if (Component.components_ && Component.components_[name]) {
return Component.components_[name];
}
if (_globalWindow2['default'] && _globalWindow2['default'].videojs && _globalWindow2['default'].videojs[name]) {
_utilsLogJs2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)');
return _globalWindow2['default'].videojs[name];
}
};
/**
* Sets up the constructor using the supplied init method
* or uses the init of the parent object
*
* @param {Object} props An object of properties
* @static
* @deprecated
* @method extend
*/
Component.extend = function extend(props) {
props = props || {};
_utilsLogJs2['default'].warn('Component.extend({}) has been deprecated, use videojs.extend(Component, {}) instead');
// 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
var 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 constructor because the `this` in `this.init`
// would still refer to the Child and cause an infinite loop.
// We would instead have to do
// `ParentObject.prototype.init.apply(this, arguments);`
// Bleh. We're not creating a _super() function, so it's good to keep
// the parent constructor reference simple.
var subObj = function subObj() {
init.apply(this, arguments);
};
// Inherit from this object's prototype
subObj.prototype = Object.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 = Component.extend;
// Extend subObj's prototype with functions and other properties from props
for (var _name2 in props) {
if (props.hasOwnProperty(_name2)) {
subObj.prototype[_name2] = props[_name2];
}
}
return subObj;
};
return Component;
})();
Component.registerComponent('Component', Component);
exports['default'] = Component;
module.exports = exports['default'];
},{"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"./utils/guid.js":122,"./utils/log.js":123,"./utils/merge-options.js":124,"./utils/to-title-case.js":127,"global/window":2,"object.assign":43}],59:[function(_dereq_,module,exports){
/**
* @file control-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
// Required children
var _playToggleJs = _dereq_('./play-toggle.js');
var _playToggleJs2 = _interopRequireDefault(_playToggleJs);
var _timeControlsCurrentTimeDisplayJs = _dereq_('./time-controls/current-time-display.js');
var _timeControlsCurrentTimeDisplayJs2 = _interopRequireDefault(_timeControlsCurrentTimeDisplayJs);
var _timeControlsDurationDisplayJs = _dereq_('./time-controls/duration-display.js');
var _timeControlsDurationDisplayJs2 = _interopRequireDefault(_timeControlsDurationDisplayJs);
var _timeControlsTimeDividerJs = _dereq_('./time-controls/time-divider.js');
var _timeControlsTimeDividerJs2 = _interopRequireDefault(_timeControlsTimeDividerJs);
var _timeControlsRemainingTimeDisplayJs = _dereq_('./time-controls/remaining-time-display.js');
var _timeControlsRemainingTimeDisplayJs2 = _interopRequireDefault(_timeControlsRemainingTimeDisplayJs);
var _liveDisplayJs = _dereq_('./live-display.js');
var _liveDisplayJs2 = _interopRequireDefault(_liveDisplayJs);
var _progressControlProgressControlJs = _dereq_('./progress-control/progress-control.js');
var _progressControlProgressControlJs2 = _interopRequireDefault(_progressControlProgressControlJs);
var _fullscreenToggleJs = _dereq_('./fullscreen-toggle.js');
var _fullscreenToggleJs2 = _interopRequireDefault(_fullscreenToggleJs);
var _volumeControlVolumeControlJs = _dereq_('./volume-control/volume-control.js');
var _volumeControlVolumeControlJs2 = _interopRequireDefault(_volumeControlVolumeControlJs);
var _volumeMenuButtonJs = _dereq_('./volume-menu-button.js');
var _volumeMenuButtonJs2 = _interopRequireDefault(_volumeMenuButtonJs);
var _muteToggleJs = _dereq_('./mute-toggle.js');
var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs);
var _textTrackControlsChaptersButtonJs = _dereq_('./text-track-controls/chapters-button.js');
var _textTrackControlsChaptersButtonJs2 = _interopRequireDefault(_textTrackControlsChaptersButtonJs);
var _textTrackControlsSubtitlesButtonJs = _dereq_('./text-track-controls/subtitles-button.js');
var _textTrackControlsSubtitlesButtonJs2 = _interopRequireDefault(_textTrackControlsSubtitlesButtonJs);
var _textTrackControlsCaptionsButtonJs = _dereq_('./text-track-controls/captions-button.js');
var _textTrackControlsCaptionsButtonJs2 = _interopRequireDefault(_textTrackControlsCaptionsButtonJs);
var _playbackRateMenuPlaybackRateMenuButtonJs = _dereq_('./playback-rate-menu/playback-rate-menu-button.js');
var _playbackRateMenuPlaybackRateMenuButtonJs2 = _interopRequireDefault(_playbackRateMenuPlaybackRateMenuButtonJs);
var _spacerControlsCustomControlSpacerJs = _dereq_('./spacer-controls/custom-control-spacer.js');
var _spacerControlsCustomControlSpacerJs2 = _interopRequireDefault(_spacerControlsCustomControlSpacerJs);
/**
* Container of main controls
*
* @extends Component
* @class ControlBar
*/
var ControlBar = (function (_Component) {
_inherits(ControlBar, _Component);
function ControlBar() {
_classCallCheck(this, ControlBar);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
ControlBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-control-bar'
});
};
return ControlBar;
})(_componentJs2['default']);
ControlBar.prototype.options_ = {
loadEvent: 'play',
children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'fullscreenToggle']
};
_componentJs2['default'].registerComponent('ControlBar', ControlBar);
exports['default'] = ControlBar;
module.exports = exports['default'];
},{"../component.js":58,"./fullscreen-toggle.js":60,"./live-display.js":61,"./mute-toggle.js":62,"./play-toggle.js":63,"./playback-rate-menu/playback-rate-menu-button.js":64,"./progress-control/progress-control.js":69,"./spacer-controls/custom-control-spacer.js":71,"./text-track-controls/captions-button.js":74,"./text-track-controls/chapters-button.js":75,"./text-track-controls/subtitles-button.js":78,"./time-controls/current-time-display.js":81,"./time-controls/duration-display.js":82,"./time-controls/remaining-time-display.js":83,"./time-controls/time-divider.js":84,"./volume-control/volume-control.js":86,"./volume-menu-button.js":88}],60:[function(_dereq_,module,exports){
/**
* @file fullscreen-toggle.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Toggle fullscreen video
*
* @extends Button
* @class FullscreenToggle
*/
var FullscreenToggle = (function (_Button) {
_inherits(FullscreenToggle, _Button);
function FullscreenToggle() {
_classCallCheck(this, FullscreenToggle);
_Button.apply(this, arguments);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handles click for full screen
*
* @method handleClick
*/
FullscreenToggle.prototype.handleClick = function handleClick() {
if (!this.player_.isFullscreen()) {
this.player_.requestFullscreen();
this.controlText('Non-Fullscreen');
} else {
this.player_.exitFullscreen();
this.controlText('Fullscreen');
}
};
return FullscreenToggle;
})(_buttonJs2['default']);
FullscreenToggle.prototype.controlText_ = 'Fullscreen';
_componentJs2['default'].registerComponent('FullscreenToggle', FullscreenToggle);
exports['default'] = FullscreenToggle;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58}],61:[function(_dereq_,module,exports){
/**
* @file live-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* Displays the live indicator
* TODO - Future make it click to snap to live
*
* @extends Component
* @class LiveDisplay
*/
var LiveDisplay = (function (_Component) {
_inherits(LiveDisplay, _Component);
function LiveDisplay(player, options) {
_classCallCheck(this, LiveDisplay);
_Component.call(this, player, options);
this.updateShowing();
this.on(this.player(), 'durationchange', this.updateShowing);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
LiveDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-live-control vjs-control'
});
this.contentEl_ = Dom.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;
};
LiveDisplay.prototype.updateShowing = function updateShowing() {
if (this.player().duration() === Infinity) {
this.show();
} else {
this.hide();
}
};
return LiveDisplay;
})(_component2['default']);
_component2['default'].registerComponent('LiveDisplay', LiveDisplay);
exports['default'] = LiveDisplay;
module.exports = exports['default'];
},{"../component":58,"../utils/dom.js":118}],62:[function(_dereq_,module,exports){
/**
* @file mute-toggle.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _button = _dereq_('../button');
var _button2 = _interopRequireDefault(_button);
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* A button component for muting the audio
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class MuteToggle
*/
var MuteToggle = (function (_Button) {
_inherits(MuteToggle, _Button);
function MuteToggle(player, options) {
_classCallCheck(this, MuteToggle);
_Button.call(this, player, options);
this.on(player, 'volumechange', 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');
}
this.on(player, 'loadstart', function () {
this.update(); // We need to update the button to account for a default muted state.
if (player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
});
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
MuteToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handle click on mute
*
* @method handleClick
*/
MuteToggle.prototype.handleClick = function handleClick() {
this.player_.muted(this.player_.muted() ? false : true);
};
/**
* Update volume
*
* @method update
*/
MuteToggle.prototype.update = function update() {
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.
var toMute = this.player_.muted() ? 'Unmute' : 'Mute';
var localizedMute = this.localize(toMute);
if (this.controlText() !== localizedMute) {
this.controlText(localizedMute);
}
/* TODO improve muted icon classes */
for (var i = 0; i < 4; i++) {
Dom.removeElClass(this.el_, 'vjs-vol-' + i);
}
Dom.addElClass(this.el_, 'vjs-vol-' + level);
};
return MuteToggle;
})(_button2['default']);
MuteToggle.prototype.controlText_ = 'Mute';
_component2['default'].registerComponent('MuteToggle', MuteToggle);
exports['default'] = MuteToggle;
module.exports = exports['default'];
},{"../button":57,"../component":58,"../utils/dom.js":118}],63:[function(_dereq_,module,exports){
/**
* @file play-toggle.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Button to toggle between play and pause
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class PlayToggle
*/
var PlayToggle = (function (_Button) {
_inherits(PlayToggle, _Button);
function PlayToggle(player, options) {
_classCallCheck(this, PlayToggle);
_Button.call(this, player, options);
this.on(player, 'play', this.handlePlay);
this.on(player, 'pause', this.handlePause);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
PlayToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handle click to toggle between play and pause
*
* @method handleClick
*/
PlayToggle.prototype.handleClick = function handleClick() {
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
};
/**
* Add the vjs-playing class to the element so it can change appearance
*
* @method handlePlay
*/
PlayToggle.prototype.handlePlay = function handlePlay() {
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
this.controlText('Pause'); // change the button text to "Pause"
};
/**
* Add the vjs-paused class to the element so it can change appearance
*
* @method handlePause
*/
PlayToggle.prototype.handlePause = function handlePause() {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
this.controlText('Play'); // change the button text to "Play"
};
return PlayToggle;
})(_buttonJs2['default']);
PlayToggle.prototype.controlText_ = 'Play';
_componentJs2['default'].registerComponent('PlayToggle', PlayToggle);
exports['default'] = PlayToggle;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58}],64:[function(_dereq_,module,exports){
/**
* @file playback-rate-menu-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _menuMenuJs = _dereq_('../../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _playbackRateMenuItemJs = _dereq_('./playback-rate-menu-item.js');
var _playbackRateMenuItemJs2 = _interopRequireDefault(_playbackRateMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* The component for controlling the playback rate
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuButton
* @class PlaybackRateMenuButton
*/
var PlaybackRateMenuButton = (function (_MenuButton) {
_inherits(PlaybackRateMenuButton, _MenuButton);
function PlaybackRateMenuButton(player, options) {
_classCallCheck(this, PlaybackRateMenuButton);
_MenuButton.call(this, player, options);
this.updateVisibility();
this.updateLabel();
this.on(player, 'loadstart', this.updateVisibility);
this.on(player, 'ratechange', this.updateLabel);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
PlaybackRateMenuButton.prototype.createEl = function createEl() {
var el = _MenuButton.prototype.createEl.call(this);
this.labelEl_ = Dom.createEl('div', {
className: 'vjs-playback-rate-value',
innerHTML: 1.0
});
el.appendChild(this.labelEl_);
return el;
};
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this);
};
/**
* Create the playback rate menu
*
* @return {Menu} Menu object populated with items
* @method createMenu
*/
PlaybackRateMenuButton.prototype.createMenu = function createMenu() {
var menu = new _menuMenuJs2['default'](this.player());
var rates = this.playbackRates();
if (rates) {
for (var i = rates.length - 1; i >= 0; i--) {
menu.addChild(new _playbackRateMenuItemJs2['default'](this.player(), { 'rate': rates[i] + 'x' }));
}
}
return menu;
};
/**
* Updates ARIA accessibility attributes
*
* @method updateARIAAttributes
*/
PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() {
// Current playback rate
this.el().setAttribute('aria-valuenow', this.player().playbackRate());
};
/**
* Handle menu item click
*
* @method handleClick
*/
PlaybackRateMenuButton.prototype.handleClick = function handleClick() {
// select next rate option
var currentRate = this.player().playbackRate();
var rates = this.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);
};
/**
* Get possible playback rates
*
* @return {Array} Possible playback rates
* @method playbackRates
*/
PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() {
return this.options_['playbackRates'] || this.options_.playerOptions && this.options_.playerOptions['playbackRates'];
};
/**
* Get supported playback rates
*
* @return {Array} Supported playback rates
* @method playbackRateSupported
*/
PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() {
return this.player().tech_ && this.player().tech_['featuresPlaybackRate'] && this.playbackRates() && this.playbackRates().length > 0;
};
/**
* Hide playback rate controls when they're no playback rate options to select
*
* @method updateVisibility
*/
PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility() {
if (this.playbackRateSupported()) {
this.removeClass('vjs-hidden');
} else {
this.addClass('vjs-hidden');
}
};
/**
* Update button label when rate changed
*
* @method updateLabel
*/
PlaybackRateMenuButton.prototype.updateLabel = function updateLabel() {
if (this.playbackRateSupported()) {
this.labelEl_.innerHTML = this.player().playbackRate() + 'x';
}
};
return PlaybackRateMenuButton;
})(_menuMenuButtonJs2['default']);
PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
_componentJs2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
exports['default'] = PlaybackRateMenuButton;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-button.js":95,"../../menu/menu.js":97,"../../utils/dom.js":118,"./playback-rate-menu-item.js":65}],65:[function(_dereq_,module,exports){
/**
* @file playback-rate-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuItemJs = _dereq_('../../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The specific menu item type for selecting a playback rate
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuItem
* @class PlaybackRateMenuItem
*/
var PlaybackRateMenuItem = (function (_MenuItem) {
_inherits(PlaybackRateMenuItem, _MenuItem);
function PlaybackRateMenuItem(player, options) {
_classCallCheck(this, PlaybackRateMenuItem);
var label = options['rate'];
var rate = parseFloat(label, 10);
// Modify options for parent MenuItem class's init.
options['label'] = label;
options['selected'] = rate === 1;
_MenuItem.call(this, player, options);
this.label = label;
this.rate = rate;
this.on(player, 'ratechange', this.update);
}
/**
* Handle click on menu item
*
* @method handleClick
*/
PlaybackRateMenuItem.prototype.handleClick = function handleClick() {
_MenuItem.prototype.handleClick.call(this);
this.player().playbackRate(this.rate);
};
/**
* Update playback rate with selected rate
*
* @method update
*/
PlaybackRateMenuItem.prototype.update = function update() {
this.selected(this.player().playbackRate() === this.rate);
};
return PlaybackRateMenuItem;
})(_menuMenuItemJs2['default']);
PlaybackRateMenuItem.prototype.contentElType = 'button';
_componentJs2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
exports['default'] = PlaybackRateMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-item.js":96}],66:[function(_dereq_,module,exports){
/**
* @file load-progress-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* Shows load progress
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class LoadProgressBar
*/
var LoadProgressBar = (function (_Component) {
_inherits(LoadProgressBar, _Component);
function LoadProgressBar(player, options) {
_classCallCheck(this, LoadProgressBar);
_Component.call(this, player, options);
this.on(player, 'progress', this.update);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
LoadProgressBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-load-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>'
});
};
/**
* Update progress bar
*
* @method update
*/
LoadProgressBar.prototype.update = function update() {
var buffered = this.player_.buffered();
var duration = this.player_.duration();
var bufferedEnd = this.player_.bufferedEnd();
var children = this.el_.children;
// get the percent width of a time compared to the total end
var percentify = function percentify(time, end) {
var percent = time / end || 0; // no NaN
return (percent >= 1 ? 1 : 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 (var i = 0; i < buffered.length; i++) {
var start = buffered.start(i);
var end = buffered.end(i);
var part = children[i];
if (!part) {
part = this.el_.appendChild(Dom.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 (var i = children.length; i > buffered.length; i--) {
this.el_.removeChild(children[i - 1]);
}
};
return LoadProgressBar;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('LoadProgressBar', LoadProgressBar);
exports['default'] = LoadProgressBar;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118}],67:[function(_dereq_,module,exports){
/**
* @file mouse-time-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
var _lodashCompatFunctionThrottle = _dereq_('lodash-compat/function/throttle');
var _lodashCompatFunctionThrottle2 = _interopRequireDefault(_lodashCompatFunctionThrottle);
/**
* The Mouse Time Display component shows the time you will seek to
* when hovering over the progress bar
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class MouseTimeDisplay
*/
var MouseTimeDisplay = (function (_Component) {
_inherits(MouseTimeDisplay, _Component);
function MouseTimeDisplay(player, options) {
var _this = this;
_classCallCheck(this, MouseTimeDisplay);
_Component.call(this, player, options);
this.update(0, 0);
player.on('ready', function () {
_this.on(player.controlBar.progressControl.el(), 'mousemove', _lodashCompatFunctionThrottle2['default'](Fn.bind(_this, _this.handleMouseMove), 25));
});
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
MouseTimeDisplay.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-mouse-display'
});
};
MouseTimeDisplay.prototype.handleMouseMove = function handleMouseMove(event) {
var duration = this.player_.duration();
var newTime = this.calculateDistance(event) * duration;
var position = event.pageX - Dom.findElPosition(this.el().parentNode).left;
this.update(newTime, position);
};
MouseTimeDisplay.prototype.update = function update(newTime, position) {
var time = _utilsFormatTimeJs2['default'](newTime, this.player_.duration());
this.el().style.left = position + 'px';
this.el().setAttribute('data-current-time', time);
};
MouseTimeDisplay.prototype.calculateDistance = function calculateDistance(event) {
return Dom.getPointerPosition(this.el().parentNode, event).x;
};
return MouseTimeDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('MouseTimeDisplay', MouseTimeDisplay);
exports['default'] = MouseTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118,"../../utils/fn.js":120,"../../utils/format-time.js":121,"lodash-compat/function/throttle":7}],68:[function(_dereq_,module,exports){
/**
* @file play-progress-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Shows play progress
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class PlayProgressBar
*/
var PlayProgressBar = (function (_Component) {
_inherits(PlayProgressBar, _Component);
function PlayProgressBar(player, options) {
_classCallCheck(this, PlayProgressBar);
_Component.call(this, player, options);
this.updateDataAttr();
this.on(player, 'timeupdate', this.updateDataAttr);
player.ready(Fn.bind(this, this.updateDataAttr));
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
PlayProgressBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-play-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>'
});
};
PlayProgressBar.prototype.updateDataAttr = function updateDataAttr() {
var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
this.el_.setAttribute('data-current-time', _utilsFormatTimeJs2['default'](time, this.player_.duration()));
};
return PlayProgressBar;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('PlayProgressBar', PlayProgressBar);
exports['default'] = PlayProgressBar;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/fn.js":120,"../../utils/format-time.js":121}],69:[function(_dereq_,module,exports){
/**
* @file progress-control.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _seekBarJs = _dereq_('./seek-bar.js');
var _seekBarJs2 = _interopRequireDefault(_seekBarJs);
var _mouseTimeDisplayJs = _dereq_('./mouse-time-display.js');
var _mouseTimeDisplayJs2 = _interopRequireDefault(_mouseTimeDisplayJs);
/**
* The Progress Control component contains the seek bar, load progress,
* and play progress
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class ProgressControl
*/
var ProgressControl = (function (_Component) {
_inherits(ProgressControl, _Component);
function ProgressControl() {
_classCallCheck(this, ProgressControl);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
ProgressControl.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-control vjs-control'
});
};
return ProgressControl;
})(_componentJs2['default']);
ProgressControl.prototype.options_ = {
children: {
'seekBar': {}
}
};
_componentJs2['default'].registerComponent('ProgressControl', ProgressControl);
exports['default'] = ProgressControl;
module.exports = exports['default'];
},{"../../component.js":58,"./mouse-time-display.js":67,"./seek-bar.js":70}],70:[function(_dereq_,module,exports){
/**
* @file seek-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _sliderSliderJs = _dereq_('../../slider/slider.js');
var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _loadProgressBarJs = _dereq_('./load-progress-bar.js');
var _loadProgressBarJs2 = _interopRequireDefault(_loadProgressBarJs);
var _playProgressBarJs = _dereq_('./play-progress-bar.js');
var _playProgressBarJs2 = _interopRequireDefault(_playProgressBarJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* Seek Bar and holder for the progress bars
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Slider
* @class SeekBar
*/
var SeekBar = (function (_Slider) {
_inherits(SeekBar, _Slider);
function SeekBar(player, options) {
_classCallCheck(this, SeekBar);
_Slider.call(this, player, options);
this.on(player, 'timeupdate', this.updateARIAAttributes);
player.ready(Fn.bind(this, this.updateARIAAttributes));
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
SeekBar.prototype.createEl = function createEl() {
return _Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-holder'
}, {
'aria-label': 'video progress bar'
});
};
/**
* Update ARIA accessibility attributes
*
* @method updateARIAAttributes
*/
SeekBar.prototype.updateARIAAttributes = function updateARIAAttributes() {
// 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', (this.getPercent() * 100).toFixed(2)); // machine readable value of progress bar (percentage complete)
this.el_.setAttribute('aria-valuetext', _utilsFormatTimeJs2['default'](time, this.player_.duration())); // human readable value of progress bar (time complete)
};
/**
* Get percentage of video played
*
* @return {Number} Percentage played
* @method getPercent
*/
SeekBar.prototype.getPercent = function getPercent() {
var percent = this.player_.currentTime() / this.player_.duration();
return percent >= 1 ? 1 : percent;
};
/**
* Handle mouse down on seek bar
*
* @method handleMouseDown
*/
SeekBar.prototype.handleMouseDown = function handleMouseDown(event) {
_Slider.prototype.handleMouseDown.call(this, event);
this.player_.scrubbing(true);
this.videoWasPlaying = !this.player_.paused();
this.player_.pause();
};
/**
* Handle mouse move on seek bar
*
* @method handleMouseMove
*/
SeekBar.prototype.handleMouseMove = function handleMouseMove(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);
};
/**
* Handle mouse up on seek bar
*
* @method handleMouseUp
*/
SeekBar.prototype.handleMouseUp = function handleMouseUp(event) {
_Slider.prototype.handleMouseUp.call(this, event);
this.player_.scrubbing(false);
if (this.videoWasPlaying) {
this.player_.play();
}
};
/**
* Move more quickly fast forward for keyboard-only users
*
* @method stepForward
*/
SeekBar.prototype.stepForward = function stepForward() {
this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users
};
/**
* Move more quickly rewind for keyboard-only users
*
* @method stepBack
*/
SeekBar.prototype.stepBack = function stepBack() {
this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users
};
return SeekBar;
})(_sliderSliderJs2['default']);
SeekBar.prototype.options_ = {
children: {
'loadProgressBar': {},
'mouseTimeDisplay': {},
'playProgressBar': {}
},
'barName': 'playProgressBar'
};
SeekBar.prototype.playerEvent = 'timeupdate';
_componentJs2['default'].registerComponent('SeekBar', SeekBar);
exports['default'] = SeekBar;
module.exports = exports['default'];
},{"../../component.js":58,"../../slider/slider.js":102,"../../utils/fn.js":120,"../../utils/format-time.js":121,"./load-progress-bar.js":66,"./play-progress-bar.js":68,"object.assign":43}],71:[function(_dereq_,module,exports){
/**
* @file custom-control-spacer.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _spacerJs = _dereq_('./spacer.js');
var _spacerJs2 = _interopRequireDefault(_spacerJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Spacer specifically meant to be used as an insertion point for new plugins, etc.
*
* @extends Spacer
* @class CustomControlSpacer
*/
var CustomControlSpacer = (function (_Spacer) {
_inherits(CustomControlSpacer, _Spacer);
function CustomControlSpacer() {
_classCallCheck(this, CustomControlSpacer);
_Spacer.apply(this, arguments);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
CustomControlSpacer.prototype.createEl = function createEl() {
var el = _Spacer.prototype.createEl.call(this, {
className: this.buildCSSClass()
});
// No-flex/table-cell mode requires there be some content
// in the cell to fill the remaining space of the table.
el.innerHTML = ' ';
return el;
};
return CustomControlSpacer;
})(_spacerJs2['default']);
_componentJs2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer);
exports['default'] = CustomControlSpacer;
module.exports = exports['default'];
},{"../../component.js":58,"./spacer.js":72}],72:[function(_dereq_,module,exports){
/**
* @file spacer.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Just an empty spacer element that can be used as an append point for plugins, etc.
* Also can be used to create space between elements when necessary.
*
* @extends Component
* @class Spacer
*/
var Spacer = (function (_Component) {
_inherits(Spacer, _Component);
function Spacer() {
_classCallCheck(this, Spacer);
_Component.apply(this, arguments);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
Spacer.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Spacer.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: this.buildCSSClass()
});
};
return Spacer;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('Spacer', Spacer);
exports['default'] = Spacer;
module.exports = exports['default'];
},{"../../component.js":58}],73:[function(_dereq_,module,exports){
/**
* @file caption-settings-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The menu item for caption track settings menu
*
* @param {Player|Object} player
* @param {Object=} options
* @extends TextTrackMenuItem
* @class CaptionSettingsMenuItem
*/
var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) {
_inherits(CaptionSettingsMenuItem, _TextTrackMenuItem);
function CaptionSettingsMenuItem(player, options) {
_classCallCheck(this, CaptionSettingsMenuItem);
options['track'] = {
'kind': options['kind'],
'player': player,
'label': options['kind'] + ' settings',
'default': false,
mode: 'disabled'
};
_TextTrackMenuItem.call(this, player, options);
this.addClass('vjs-texttrack-settings');
}
/**
* Handle click on menu item
*
* @method handleClick
*/
CaptionSettingsMenuItem.prototype.handleClick = function handleClick() {
this.player().getChild('textTrackSettings').show();
};
return CaptionSettingsMenuItem;
})(_textTrackMenuItemJs2['default']);
_componentJs2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
exports['default'] = CaptionSettingsMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"./text-track-menu-item.js":80}],74:[function(_dereq_,module,exports){
/**
* @file captions-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackButtonJs = _dereq_('./text-track-button.js');
var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _captionSettingsMenuItemJs = _dereq_('./caption-settings-menu-item.js');
var _captionSettingsMenuItemJs2 = _interopRequireDefault(_captionSettingsMenuItemJs);
/**
* The button component for toggling and selecting captions
*
* @param {Object} player Player object
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends TextTrackButton
* @class CaptionsButton
*/
var CaptionsButton = (function (_TextTrackButton) {
_inherits(CaptionsButton, _TextTrackButton);
function CaptionsButton(player, options, ready) {
_classCallCheck(this, CaptionsButton);
_TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Captions Menu');
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
CaptionsButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
/**
* Update caption menu items
*
* @method update
*/
CaptionsButton.prototype.update = function update() {
var threshold = 2;
_TextTrackButton.prototype.update.call(this);
// if native, then threshold is 1 because no settings button
if (this.player().tech_ && this.player().tech_['featuresNativeTextTracks']) {
threshold = 1;
}
if (this.items && this.items.length > threshold) {
this.show();
} else {
this.hide();
}
};
/**
* Create caption menu items
*
* @return {Array} Array of menu items
* @method createItems
*/
CaptionsButton.prototype.createItems = function createItems() {
var items = [];
if (!(this.player().tech_ && this.player().tech_['featuresNativeTextTracks'])) {
items.push(new _captionSettingsMenuItemJs2['default'](this.player_, { 'kind': this.kind_ }));
}
return _TextTrackButton.prototype.createItems.call(this, items);
};
return CaptionsButton;
})(_textTrackButtonJs2['default']);
CaptionsButton.prototype.kind_ = 'captions';
CaptionsButton.prototype.controlText_ = 'Captions';
_componentJs2['default'].registerComponent('CaptionsButton', CaptionsButton);
exports['default'] = CaptionsButton;
module.exports = exports['default'];
},{"../../component.js":58,"./caption-settings-menu-item.js":73,"./text-track-button.js":79}],75:[function(_dereq_,module,exports){
/**
* @file chapters-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackButtonJs = _dereq_('./text-track-button.js');
var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _chaptersTrackMenuItemJs = _dereq_('./chapters-track-menu-item.js');
var _chaptersTrackMenuItemJs2 = _interopRequireDefault(_chaptersTrackMenuItemJs);
var _menuMenuJs = _dereq_('../../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsToTitleCaseJs = _dereq_('../../utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* The button component for toggling and selecting chapters
* Chapters act much differently than other text tracks
* Cues are navigation vs. other tracks of alternative languages
*
* @param {Object} player Player object
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends TextTrackButton
* @class ChaptersButton
*/
var ChaptersButton = (function (_TextTrackButton) {
_inherits(ChaptersButton, _TextTrackButton);
function ChaptersButton(player, options, ready) {
_classCallCheck(this, ChaptersButton);
_TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Chapters Menu');
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
ChaptersButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
/**
* Create a menu item for each text track
*
* @return {Array} Array of menu items
* @method createItems
*/
ChaptersButton.prototype.createItems = function createItems() {
var items = [];
var tracks = this.player_.textTracks();
if (!tracks) {
return items;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track['kind'] === this.kind_) {
items.push(new _textTrackMenuItemJs2['default'](this.player_, {
'track': track
}));
}
}
return items;
};
/**
* Create menu from chapter buttons
*
* @return {Menu} Menu of chapter buttons
* @method createMenu
*/
ChaptersButton.prototype.createMenu = function createMenu() {
var tracks = this.player_.textTracks() || [];
var chaptersTrack = undefined;
var items = this.items = [];
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (track['kind'] === this.kind_) {
if (!track.cues) {
track['mode'] = 'hidden';
/* jshint loopfunc:true */
// TODO see if we can figure out a better way of doing this https://github.com/videojs/video.js/issues/1864
_globalWindow2['default'].setTimeout(Fn.bind(this, function () {
this.createMenu();
}), 100);
/* jshint loopfunc:false */
} else {
chaptersTrack = track;
break;
}
}
}
var menu = this.menu;
if (menu === undefined) {
menu = new _menuMenuJs2['default'](this.player_);
menu.contentEl().appendChild(Dom.createEl('li', {
className: 'vjs-menu-title',
innerHTML: _utilsToTitleCaseJs2['default'](this.kind_),
tabIndex: -1
}));
}
if (chaptersTrack) {
var cues = chaptersTrack['cues'],
cue = undefined;
for (var i = 0, l = cues.length; i < l; i++) {
cue = cues[i];
var mi = new _chaptersTrackMenuItemJs2['default'](this.player_, {
'track': chaptersTrack,
'cue': cue
});
items.push(mi);
menu.addChild(mi);
}
this.addChild(menu);
}
if (this.items.length > 0) {
this.show();
}
return menu;
};
return ChaptersButton;
})(_textTrackButtonJs2['default']);
ChaptersButton.prototype.kind_ = 'chapters';
ChaptersButton.prototype.controlText_ = 'Chapters';
_componentJs2['default'].registerComponent('ChaptersButton', ChaptersButton);
exports['default'] = ChaptersButton;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu.js":97,"../../utils/dom.js":118,"../../utils/fn.js":120,"../../utils/to-title-case.js":127,"./chapters-track-menu-item.js":76,"./text-track-button.js":79,"./text-track-menu-item.js":80,"global/window":2}],76:[function(_dereq_,module,exports){
/**
* @file chapters-track-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuItemJs = _dereq_('../../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
/**
* The chapter track menu item
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuItem
* @class ChaptersTrackMenuItem
*/
var ChaptersTrackMenuItem = (function (_MenuItem) {
_inherits(ChaptersTrackMenuItem, _MenuItem);
function ChaptersTrackMenuItem(player, options) {
_classCallCheck(this, ChaptersTrackMenuItem);
var track = options['track'];
var cue = options['cue'];
var currentTime = player.currentTime();
// Modify options for parent MenuItem class's init.
options['label'] = cue.text;
options['selected'] = cue['startTime'] <= currentTime && currentTime < cue['endTime'];
_MenuItem.call(this, player, options);
this.track = track;
this.cue = cue;
track.addEventListener('cuechange', Fn.bind(this, this.update));
}
/**
* Handle click on menu item
*
* @method handleClick
*/
ChaptersTrackMenuItem.prototype.handleClick = function handleClick() {
_MenuItem.prototype.handleClick.call(this);
this.player_.currentTime(this.cue.startTime);
this.update(this.cue.startTime);
};
/**
* Update chapter menu item
*
* @method update
*/
ChaptersTrackMenuItem.prototype.update = function update() {
var cue = this.cue;
var currentTime = this.player_.currentTime();
// vjs.log(currentTime, cue.startTime);
this.selected(cue['startTime'] <= currentTime && currentTime < cue['endTime']);
};
return ChaptersTrackMenuItem;
})(_menuMenuItemJs2['default']);
_componentJs2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
exports['default'] = ChaptersTrackMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-item.js":96,"../../utils/fn.js":120}],77:[function(_dereq_,module,exports){
/**
* @file off-text-track-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* A special menu item for turning of a specific type of text track
*
* @param {Player|Object} player
* @param {Object=} options
* @extends TextTrackMenuItem
* @class OffTextTrackMenuItem
*/
var OffTextTrackMenuItem = (function (_TextTrackMenuItem) {
_inherits(OffTextTrackMenuItem, _TextTrackMenuItem);
function OffTextTrackMenuItem(player, options) {
_classCallCheck(this, OffTextTrackMenuItem);
// Create pseudo track info
// Requires options['kind']
options['track'] = {
'kind': options['kind'],
'player': player,
'label': options['kind'] + ' off',
'default': false,
'mode': 'disabled'
};
_TextTrackMenuItem.call(this, player, options);
this.selected(true);
}
/**
* Handle text track change
*
* @param {Object} event Event object
* @method handleTracksChange
*/
OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) {
var tracks = this.player().textTracks();
var selected = true;
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (track['kind'] === this.track['kind'] && track['mode'] === 'showing') {
selected = false;
break;
}
}
this.selected(selected);
};
return OffTextTrackMenuItem;
})(_textTrackMenuItemJs2['default']);
_componentJs2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
exports['default'] = OffTextTrackMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"./text-track-menu-item.js":80}],78:[function(_dereq_,module,exports){
/**
* @file subtitles-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackButtonJs = _dereq_('./text-track-button.js');
var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The button component for toggling and selecting subtitles
*
* @param {Object} player Player object
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends TextTrackButton
* @class SubtitlesButton
*/
var SubtitlesButton = (function (_TextTrackButton) {
_inherits(SubtitlesButton, _TextTrackButton);
function SubtitlesButton(player, options, ready) {
_classCallCheck(this, SubtitlesButton);
_TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Subtitles Menu');
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
return SubtitlesButton;
})(_textTrackButtonJs2['default']);
SubtitlesButton.prototype.kind_ = 'subtitles';
SubtitlesButton.prototype.controlText_ = 'Subtitles';
_componentJs2['default'].registerComponent('SubtitlesButton', SubtitlesButton);
exports['default'] = SubtitlesButton;
module.exports = exports['default'];
},{"../../component.js":58,"./text-track-button.js":79}],79:[function(_dereq_,module,exports){
/**
* @file text-track-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _offTextTrackMenuItemJs = _dereq_('./off-text-track-menu-item.js');
var _offTextTrackMenuItemJs2 = _interopRequireDefault(_offTextTrackMenuItemJs);
/**
* The base class for buttons that toggle specific text track types (e.g. subtitles)
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuButton
* @class TextTrackButton
*/
var TextTrackButton = (function (_MenuButton) {
_inherits(TextTrackButton, _MenuButton);
function TextTrackButton(player, options) {
_classCallCheck(this, TextTrackButton);
_MenuButton.call(this, player, options);
var tracks = this.player_.textTracks();
if (this.items.length <= 1) {
this.hide();
}
if (!tracks) {
return;
}
var updateHandler = Fn.bind(this, this.update);
tracks.addEventListener('removetrack', updateHandler);
tracks.addEventListener('addtrack', updateHandler);
this.player_.on('dispose', function () {
tracks.removeEventListener('removetrack', updateHandler);
tracks.removeEventListener('addtrack', updateHandler);
});
}
// Create a menu item for each text track
TextTrackButton.prototype.createItems = function createItems() {
var items = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];
// Add an OFF menu item to turn all tracks off
items.push(new _offTextTrackMenuItemJs2['default'](this.player_, { 'kind': this.kind_ }));
var tracks = this.player_.textTracks();
if (!tracks) {
return items;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
// only add tracks that are of the appropriate kind and have a label
if (track['kind'] === this.kind_) {
items.push(new _textTrackMenuItemJs2['default'](this.player_, {
'track': track
}));
}
}
return items;
};
return TextTrackButton;
})(_menuMenuButtonJs2['default']);
_componentJs2['default'].registerComponent('TextTrackButton', TextTrackButton);
exports['default'] = TextTrackButton;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-button.js":95,"../../utils/fn.js":120,"./off-text-track-menu-item.js":77,"./text-track-menu-item.js":80}],80:[function(_dereq_,module,exports){
/**
* @file text-track-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuItemJs = _dereq_('../../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* The specific menu item type for selecting a language within a text track kind
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuItem
* @class TextTrackMenuItem
*/
var TextTrackMenuItem = (function (_MenuItem) {
_inherits(TextTrackMenuItem, _MenuItem);
function TextTrackMenuItem(player, options) {
var _this = this;
_classCallCheck(this, TextTrackMenuItem);
var track = options['track'];
var tracks = player.textTracks();
// Modify options for parent MenuItem class's init.
options['label'] = track['label'] || track['language'] || 'Unknown';
options['selected'] = track['default'] || track['mode'] === 'showing';
_MenuItem.call(this, player, options);
this.track = track;
if (tracks) {
(function () {
var changeHandler = Fn.bind(_this, _this.handleTracksChange);
tracks.addEventListener('change', changeHandler);
_this.on('dispose', function () {
tracks.removeEventListener('change', changeHandler);
});
})();
}
// iOS7 doesn't dispatch change events to TextTrackLists when an
// associated track's mode changes. Without something like
// Object.observe() (also not present on iOS7), it's not
// possible to detect changes to the mode attribute and polyfill
// the change event. As a poor substitute, we manually dispatch
// change events whenever the controls modify the mode.
if (tracks && tracks.onchange === undefined) {
(function () {
var event = undefined;
_this.on(['tap', 'click'], function () {
if (typeof _globalWindow2['default'].Event !== 'object') {
// Android 2.3 throws an Illegal Constructor error for window.Event
try {
event = new _globalWindow2['default'].Event('change');
} catch (err) {}
}
if (!event) {
event = _globalDocument2['default'].createEvent('Event');
event.initEvent('change', true, true);
}
tracks.dispatchEvent(event);
});
})();
}
}
/**
* Handle click on text track
*
* @method handleClick
*/
TextTrackMenuItem.prototype.handleClick = function handleClick(event) {
var kind = this.track['kind'];
var tracks = this.player_.textTracks();
_MenuItem.prototype.handleClick.call(this, event);
if (!tracks) return;
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track['kind'] !== kind) {
continue;
}
if (track === this.track) {
track['mode'] = 'showing';
} else {
track['mode'] = 'disabled';
}
}
};
/**
* Handle text track change
*
* @method handleTracksChange
*/
TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) {
this.selected(this.track['mode'] === 'showing');
};
return TextTrackMenuItem;
})(_menuMenuItemJs2['default']);
_componentJs2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem);
exports['default'] = TextTrackMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-item.js":96,"../../utils/fn.js":120,"global/document":1,"global/window":2}],81:[function(_dereq_,module,exports){
/**
* @file current-time-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Displays the current time
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class CurrentTimeDisplay
*/
var CurrentTimeDisplay = (function (_Component) {
_inherits(CurrentTimeDisplay, _Component);
function CurrentTimeDisplay(player, options) {
_classCallCheck(this, CurrentTimeDisplay);
_Component.call(this, player, options);
this.on(player, 'timeupdate', this.updateContent);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
CurrentTimeDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-current-time vjs-time-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-current-time-display',
// label the current time for screen reader users
innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Update current time display
*
* @method updateContent
*/
CurrentTimeDisplay.prototype.updateContent = function updateContent() {
// Allows for smooth scrubbing, when player can't keep up.
var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
var localizedText = this.localize('Current Time');
var formattedTime = _utilsFormatTimeJs2['default'](time, this.player_.duration());
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime;
};
return CurrentTimeDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
exports['default'] = CurrentTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118,"../../utils/format-time.js":121}],82:[function(_dereq_,module,exports){
/**
* @file duration-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Displays the duration
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class DurationDisplay
*/
var DurationDisplay = (function (_Component) {
_inherits(DurationDisplay, _Component);
function DurationDisplay(player, options) {
_classCallCheck(this, DurationDisplay);
_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.
this.on(player, 'timeupdate', this.updateContent);
this.on(player, 'loadedmetadata', this.updateContent);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
DurationDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-duration vjs-time-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-duration-display',
// label the duration time for screen reader users
innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Update duration time display
*
* @method updateContent
*/
DurationDisplay.prototype.updateContent = function updateContent() {
var duration = this.player_.duration();
if (duration) {
var localizedText = this.localize('Duration Time');
var formattedTime = _utilsFormatTimeJs2['default'](duration);
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users
}
};
return DurationDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('DurationDisplay', DurationDisplay);
exports['default'] = DurationDisplay;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118,"../../utils/format-time.js":121}],83:[function(_dereq_,module,exports){
/**
* @file remaining-time-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Displays the time left in the video
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class RemainingTimeDisplay
*/
var RemainingTimeDisplay = (function (_Component) {
_inherits(RemainingTimeDisplay, _Component);
function RemainingTimeDisplay(player, options) {
_classCallCheck(this, RemainingTimeDisplay);
_Component.call(this, player, options);
this.on(player, 'timeupdate', this.updateContent);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
RemainingTimeDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-remaining-time vjs-time-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-remaining-time-display',
// label the remaining time for screen reader users
innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Update remaining time display
*
* @method updateContent
*/
RemainingTimeDisplay.prototype.updateContent = function updateContent() {
if (this.player_.duration()) {
var localizedText = this.localize('Remaining Time');
var formattedTime = _utilsFormatTimeJs2['default'](this.player_.remainingTime());
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime;
}
// 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());
};
return RemainingTimeDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
exports['default'] = RemainingTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118,"../../utils/format-time.js":121}],84:[function(_dereq_,module,exports){
/**
* @file time-divider.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The separator between the current time and duration.
* Can be hidden if it's not needed in the design.
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class TimeDivider
*/
var TimeDivider = (function (_Component) {
_inherits(TimeDivider, _Component);
function TimeDivider() {
_classCallCheck(this, TimeDivider);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
TimeDivider.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-time-control vjs-time-divider',
innerHTML: '<div><span>/</span></div>'
});
};
return TimeDivider;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('TimeDivider', TimeDivider);
exports['default'] = TimeDivider;
module.exports = exports['default'];
},{"../../component.js":58}],85:[function(_dereq_,module,exports){
/**
* @file volume-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _sliderSliderJs = _dereq_('../../slider/slider.js');
var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
// Required children
var _volumeLevelJs = _dereq_('./volume-level.js');
var _volumeLevelJs2 = _interopRequireDefault(_volumeLevelJs);
/**
* The bar that contains the volume level and can be clicked on to adjust the level
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Slider
* @class VolumeBar
*/
var VolumeBar = (function (_Slider) {
_inherits(VolumeBar, _Slider);
function VolumeBar(player, options) {
_classCallCheck(this, VolumeBar);
_Slider.call(this, player, options);
this.on(player, 'volumechange', this.updateARIAAttributes);
player.ready(Fn.bind(this, this.updateARIAAttributes));
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
VolumeBar.prototype.createEl = function createEl() {
return _Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-bar'
}, {
'aria-label': 'volume level'
});
};
/**
* Handle mouse move on volume bar
*
* @method handleMouseMove
*/
VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) {
if (this.player_.muted()) {
this.player_.muted(false);
}
this.player_.volume(this.calculateDistance(event));
};
/**
* Get percent of volume level
*
* @retun {Number} Volume level percent
* @method getPercent
*/
VolumeBar.prototype.getPercent = function getPercent() {
if (this.player_.muted()) {
return 0;
} else {
return this.player_.volume();
}
};
/**
* Increase volume level for keyboard users
*
* @method stepForward
*/
VolumeBar.prototype.stepForward = function stepForward() {
this.player_.volume(this.player_.volume() + 0.1);
};
/**
* Decrease volume level for keyboard users
*
* @method stepBack
*/
VolumeBar.prototype.stepBack = function stepBack() {
this.player_.volume(this.player_.volume() - 0.1);
};
/**
* Update ARIA accessibility attributes
*
* @method updateARIAAttributes
*/
VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes() {
// Current value of volume bar as a percentage
var volume = (this.player_.volume() * 100).toFixed(2);
this.el_.setAttribute('aria-valuenow', volume);
this.el_.setAttribute('aria-valuetext', volume + '%');
};
return VolumeBar;
})(_sliderSliderJs2['default']);
VolumeBar.prototype.options_ = {
children: {
'volumeLevel': {}
},
'barName': 'volumeLevel'
};
VolumeBar.prototype.playerEvent = 'volumechange';
_componentJs2['default'].registerComponent('VolumeBar', VolumeBar);
exports['default'] = VolumeBar;
module.exports = exports['default'];
},{"../../component.js":58,"../../slider/slider.js":102,"../../utils/fn.js":120,"./volume-level.js":87}],86:[function(_dereq_,module,exports){
/**
* @file volume-control.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
// Required children
var _volumeBarJs = _dereq_('./volume-bar.js');
var _volumeBarJs2 = _interopRequireDefault(_volumeBarJs);
/**
* The component for controlling the volume level
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class VolumeControl
*/
var VolumeControl = (function (_Component) {
_inherits(VolumeControl, _Component);
function VolumeControl(player, options) {
_classCallCheck(this, VolumeControl);
_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');
}
this.on(player, 'loadstart', function () {
if (player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
});
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
VolumeControl.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-control vjs-control'
});
};
return VolumeControl;
})(_componentJs2['default']);
VolumeControl.prototype.options_ = {
children: {
'volumeBar': {}
}
};
_componentJs2['default'].registerComponent('VolumeControl', VolumeControl);
exports['default'] = VolumeControl;
module.exports = exports['default'];
},{"../../component.js":58,"./volume-bar.js":85}],87:[function(_dereq_,module,exports){
/**
* @file volume-level.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Shows volume level
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class VolumeLevel
*/
var VolumeLevel = (function (_Component) {
_inherits(VolumeLevel, _Component);
function VolumeLevel() {
_classCallCheck(this, VolumeLevel);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
VolumeLevel.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-level',
innerHTML: '<span class="vjs-control-text"></span>'
});
};
return VolumeLevel;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('VolumeLevel', VolumeLevel);
exports['default'] = VolumeLevel;
module.exports = exports['default'];
},{"../../component.js":58}],88:[function(_dereq_,module,exports){
/**
* @file volume-menu-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _menuMenuJs = _dereq_('../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _menuMenuButtonJs = _dereq_('../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _muteToggleJs = _dereq_('./mute-toggle.js');
var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs);
var _volumeControlVolumeBarJs = _dereq_('./volume-control/volume-bar.js');
var _volumeControlVolumeBarJs2 = _interopRequireDefault(_volumeControlVolumeBarJs);
/**
* Button for volume menu
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuButton
* @class VolumeMenuButton
*/
var VolumeMenuButton = (function (_MenuButton) {
_inherits(VolumeMenuButton, _MenuButton);
function VolumeMenuButton(player) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, VolumeMenuButton);
// Default to inline
if (options.inline === undefined) {
options.inline = true;
}
// If the vertical option isn't passed at all, default to true.
if (options.vertical === undefined) {
// If an inline volumeMenuButton is used, we should default to using
// a horizontal slider for obvious reasons.
if (options.inline) {
options.vertical = false;
} else {
options.vertical = true;
}
}
// The vertical option needs to be set on the volumeBar as well,
// since that will need to be passed along to the VolumeBar constructor
options.volumeBar = options.volumeBar || {};
options.volumeBar.vertical = !!options.vertical;
_MenuButton.call(this, player, options);
// Same listeners as MuteToggle
this.on(player, 'volumechange', this.volumeUpdate);
this.on(player, 'loadstart', this.volumeUpdate);
// hide mute toggle if the current tech doesn't support volume control
function updateVisibility() {
if (player.tech_ && player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
}
updateVisibility.call(this);
this.on(player, 'loadstart', updateVisibility);
this.on(this.volumeBar, ['slideractive', 'focus'], function () {
this.addClass('vjs-slider-active');
});
this.on(this.volumeBar, ['sliderinactive', 'blur'], function () {
this.removeClass('vjs-slider-active');
});
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() {
var orientationClass = '';
if (!!this.options_.vertical) {
orientationClass = 'vjs-volume-menu-button-vertical';
} else {
orientationClass = 'vjs-volume-menu-button-horizontal';
}
return 'vjs-volume-menu-button ' + _MenuButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass;
};
/**
* Allow sub components to stack CSS class names
*
* @return {Menu} The volume menu button
* @method createMenu
*/
VolumeMenuButton.prototype.createMenu = function createMenu() {
var menu = new _menuMenuJs2['default'](this.player_, {
contentElType: 'div'
});
var vb = new _volumeControlVolumeBarJs2['default'](this.player_, this.options_.volumeBar);
menu.addChild(vb);
this.volumeBar = vb;
return menu;
};
/**
* Handle click on volume menu and calls super
*
* @method handleClick
*/
VolumeMenuButton.prototype.handleClick = function handleClick() {
_muteToggleJs2['default'].prototype.handleClick.call(this);
_MenuButton.prototype.handleClick.call(this);
};
return VolumeMenuButton;
})(_menuMenuButtonJs2['default']);
VolumeMenuButton.prototype.volumeUpdate = _muteToggleJs2['default'].prototype.update;
VolumeMenuButton.prototype.controlText_ = 'Mute';
_componentJs2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton);
exports['default'] = VolumeMenuButton;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58,"../menu/menu-button.js":95,"../menu/menu.js":97,"./mute-toggle.js":62,"./volume-control/volume-bar.js":85}],89:[function(_dereq_,module,exports){
/**
* @file error-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* Display that an error has occurred making the video unplayable
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Component
* @class ErrorDisplay
*/
var ErrorDisplay = (function (_Component) {
_inherits(ErrorDisplay, _Component);
function ErrorDisplay(player, options) {
_classCallCheck(this, ErrorDisplay);
_Component.call(this, player, options);
this.update();
this.on(player, 'error', this.update);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
ErrorDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-error-display'
});
this.contentEl_ = Dom.createEl('div');
el.appendChild(this.contentEl_);
return el;
};
/**
* Update the error message in localized language
*
* @method update
*/
ErrorDisplay.prototype.update = function update() {
if (this.player().error()) {
this.contentEl_.innerHTML = this.localize(this.player().error().message);
}
};
return ErrorDisplay;
})(_component2['default']);
_component2['default'].registerComponent('ErrorDisplay', ErrorDisplay);
exports['default'] = ErrorDisplay;
module.exports = exports['default'];
},{"./component":58,"./utils/dom.js":118}],90:[function(_dereq_,module,exports){
/**
* @file event-target.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var EventTarget = function EventTarget() {};
EventTarget.prototype.allowedEvents_ = {};
EventTarget.prototype.on = function (type, fn) {
// Remove the addEventListener alias before calling Events.on
// so we don't get into an infinite type loop
var ael = this.addEventListener;
this.addEventListener = Function.prototype;
Events.on(this, type, fn);
this.addEventListener = ael;
};
EventTarget.prototype.addEventListener = EventTarget.prototype.on;
EventTarget.prototype.off = function (type, fn) {
Events.off(this, type, fn);
};
EventTarget.prototype.removeEventListener = EventTarget.prototype.off;
EventTarget.prototype.one = function (type, fn) {
Events.one(this, type, fn);
};
EventTarget.prototype.trigger = function (event) {
var type = event.type || event;
if (typeof event === 'string') {
event = {
type: type
};
}
event = Events.fixEvent(event);
if (this.allowedEvents_[type] && this['on' + type]) {
this['on' + type](event);
}
Events.trigger(this, event);
};
// The standard DOM EventTarget.dispatchEvent() is aliased to trigger()
EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger;
exports['default'] = EventTarget;
module.exports = exports['default'];
},{"./utils/events.js":119}],91:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _utilsLog = _dereq_('./utils/log');
var _utilsLog2 = _interopRequireDefault(_utilsLog);
/*
* @file extend.js
*
* A combination of node inherits and babel's inherits (after transpile).
* Both work the same but node adds `super_` to the subClass
* and Bable adds the superClass as __proto__. Both seem useful.
*/
var _inherits = function _inherits(subClass, superClass) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) {
// node
subClass.super_ = superClass;
}
};
/*
* Function for subclassing using the same inheritance that
* videojs uses internally
* ```js
* var Button = videojs.getComponent('Button');
* ```
* ```js
* var MyButton = videojs.extend(Button, {
* constructor: function(player, options) {
* Button.call(this, player, options);
* },
* onClick: function() {
* // doSomething
* }
* });
* ```
*/
var extendFn = function extendFn(superClass) {
var subClassMethods = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var subClass = function subClass() {
superClass.apply(this, arguments);
};
var methods = {};
if (typeof subClassMethods === 'object') {
if (typeof subClassMethods.init === 'function') {
_utilsLog2['default'].warn('Constructor logic via init() is deprecated; please use constructor() instead.');
subClassMethods.constructor = subClassMethods.init;
}
if (subClassMethods.constructor !== Object.prototype.constructor) {
subClass = subClassMethods.constructor;
}
methods = subClassMethods;
} else if (typeof subClassMethods === 'function') {
subClass = subClassMethods;
}
_inherits(subClass, superClass);
// Extend subObj's prototype with functions and other properties from props
for (var name in methods) {
if (methods.hasOwnProperty(name)) {
subClass.prototype[name] = methods[name];
}
}
return subClass;
};
exports['default'] = extendFn;
module.exports = exports['default'];
},{"./utils/log":123}],92:[function(_dereq_,module,exports){
/**
* @file fullscreen-api.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/*
* Store the browser-specific methods for the fullscreen API
* @type {Object|undefined}
* @private
*/
var FullscreenApi = {};
// browser API methods
// map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js
var 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']];
var specApi = apiMap[0];
var browserApi = undefined;
// determine the supported set of functions
for (var i = 0; i < apiMap.length; i++) {
// check for exitFullscreen function
if (apiMap[i][1] in _globalDocument2['default']) {
browserApi = apiMap[i];
break;
}
}
// map the browser API names to the spec API names
if (browserApi) {
for (var i = 0; i < browserApi.length; i++) {
FullscreenApi[specApi[i]] = browserApi[i];
}
}
exports['default'] = FullscreenApi;
module.exports = exports['default'];
},{"global/document":1}],93:[function(_dereq_,module,exports){
/**
* @file loading-spinner.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
/* Loading Spinner
================================================================================ */
/**
* Loading spinner for waiting events
*
* @extends Component
* @class LoadingSpinner
*/
var LoadingSpinner = (function (_Component) {
_inherits(LoadingSpinner, _Component);
function LoadingSpinner() {
_classCallCheck(this, LoadingSpinner);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @method createEl
*/
LoadingSpinner.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-loading-spinner'
});
};
return LoadingSpinner;
})(_component2['default']);
_component2['default'].registerComponent('LoadingSpinner', LoadingSpinner);
exports['default'] = LoadingSpinner;
module.exports = exports['default'];
},{"./component":58}],94:[function(_dereq_,module,exports){
/**
* @file media-error.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/*
* Custom MediaError to mimic the HTML5 MediaError
*
* @param {Number} code The media error code
*/
var MediaError = function MediaError(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
_objectAssign2['default'](this, code);
}
if (!this.message) {
this.message = MediaError.defaultMessages[this.code] || '';
}
};
/*
* The error code that refers two one of the defined
* MediaError types
*
* @type {Number}
*/
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}
*/
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 {Array}
*/
MediaError.prototype.status = null;
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
];
MediaError.defaultMessages = {
1: 'You aborted the media playback',
2: 'A network error caused the media download to fail part-way.',
3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
5: 'The media 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 < MediaError.errorTypes.length; errNum++) {
MediaError[MediaError.errorTypes[errNum]] = errNum;
// values should be accessible on both the class and instance
MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
}
exports['default'] = MediaError;
module.exports = exports['default'];
},{"object.assign":43}],95:[function(_dereq_,module,exports){
/**
* @file menu-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _menuJs = _dereq_('./menu.js');
var _menuJs2 = _interopRequireDefault(_menuJs);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
/**
* A button class with a popup menu
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class MenuButton
*/
var MenuButton = (function (_Button) {
_inherits(MenuButton, _Button);
function MenuButton(player) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, MenuButton);
_Button.call(this, player, options);
this.update();
this.on('keydown', this.handleKeyPress);
this.el_.setAttribute('aria-haspopup', true);
this.el_.setAttribute('role', 'button');
}
/**
* Update menu
*
* @method update
*/
MenuButton.prototype.update = function update() {
var menu = this.createMenu();
if (this.menu) {
this.removeChild(this.menu);
}
this.menu = menu;
this.addChild(menu);
/**
* Track the state of the menu button
*
* @type {Boolean}
* @private
*/
this.buttonPressed_ = false;
if (this.items && this.items.length === 0) {
this.hide();
} else if (this.items && this.items.length > 1) {
this.show();
}
};
/**
* Create menu
*
* @return {Menu} The constructed menu
* @method createMenu
*/
MenuButton.prototype.createMenu = function createMenu() {
var menu = new _menuJs2['default'](this.player_);
// Add a title list item to the top
if (this.options_.title) {
menu.contentEl().appendChild(Dom.createEl('li', {
className: 'vjs-menu-title',
innerHTML: _utilsToTitleCaseJs2['default'](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.
*
* @method createItems
*/
MenuButton.prototype.createItems = function createItems() {};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
MenuButton.prototype.createEl = function createEl() {
return _Button.prototype.createEl.call(this, 'div', {
className: this.buildCSSClass()
});
};
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
MenuButton.prototype.buildCSSClass = function buildCSSClass() {
var menuButtonClass = 'vjs-menu-button';
// If the inline option is passed, we want to use different styles altogether.
if (this.options_.inline === true) {
menuButtonClass += '-inline';
} else {
menuButtonClass += '-popup';
}
return 'vjs-menu-button ' + menuButtonClass + ' ' + _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.
*
* @method handleFocus
*/
MenuButton.prototype.handleFocus = function handleFocus() {};
/**
* Can't turn off list display that we turned
* on with focus, because list would go away.
*
* @method handleBlur
*/
MenuButton.prototype.handleBlur = function handleBlur() {};
/**
* 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.
* Allow sub components to stack CSS class names
*
* @method handleClick
*/
MenuButton.prototype.handleClick = function handleClick() {
this.one('mouseout', Fn.bind(this, function () {
this.menu.unlockShowing();
this.el_.blur();
}));
if (this.buttonPressed_) {
this.unpressButton();
} else {
this.pressButton();
}
};
/**
* Handle key press on menu
*
* @param {Object} Key press event
* @method handleKeyPress
*/
MenuButton.prototype.handleKeyPress = function handleKeyPress(event) {
// Check for space bar (32) or enter (13) keys
if (event.which === 32 || event.which === 13) {
if (this.buttonPressed_) {
this.unpressButton();
} else {
this.pressButton();
}
event.preventDefault();
// Check for escape (27) key
} else if (event.which === 27) {
if (this.buttonPressed_) {
this.unpressButton();
}
event.preventDefault();
}
};
/**
* Makes changes based on button pressed
*
* @method pressButton
*/
MenuButton.prototype.pressButton = function pressButton() {
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
}
};
/**
* Makes changes based on button unpressed
*
* @method unpressButton
*/
MenuButton.prototype.unpressButton = function unpressButton() {
this.buttonPressed_ = false;
this.menu.unlockShowing();
this.el_.setAttribute('aria-pressed', false);
};
return MenuButton;
})(_buttonJs2['default']);
_componentJs2['default'].registerComponent('MenuButton', MenuButton);
exports['default'] = MenuButton;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58,"../utils/dom.js":118,"../utils/fn.js":120,"../utils/to-title-case.js":127,"./menu.js":97}],96:[function(_dereq_,module,exports){
/**
* @file menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* The component for a menu item. `<li>`
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class MenuItem
*/
var MenuItem = (function (_Button) {
_inherits(MenuItem, _Button);
function MenuItem(player, options) {
_classCallCheck(this, MenuItem);
_Button.call(this, player, options);
this.selected(options['selected']);
}
/**
* Create the component's DOM element
*
* @param {String=} type Desc
* @param {Object=} props Desc
* @return {Element}
* @method createEl
*/
MenuItem.prototype.createEl = function createEl(type, props, attrs) {
return _Button.prototype.createEl.call(this, 'li', _objectAssign2['default']({
className: 'vjs-menu-item',
innerHTML: this.localize(this.options_['label'])
}, props), attrs);
};
/**
* Handle a click on the menu item, and set it to selected
*
* @method handleClick
*/
MenuItem.prototype.handleClick = function handleClick() {
this.selected(true);
};
/**
* Set this menu item as selected or not
*
* @param {Boolean} selected
* @method selected
*/
MenuItem.prototype.selected = function selected(_selected) {
if (_selected) {
this.addClass('vjs-selected');
this.el_.setAttribute('aria-selected', true);
} else {
this.removeClass('vjs-selected');
this.el_.setAttribute('aria-selected', false);
}
};
return MenuItem;
})(_buttonJs2['default']);
_componentJs2['default'].registerComponent('MenuItem', MenuItem);
exports['default'] = MenuItem;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58,"object.assign":43}],97:[function(_dereq_,module,exports){
/**
* @file menu.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsEventsJs = _dereq_('../utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
/**
* The Menu component is used to build pop up menus, including subtitle and
* captions selection menus.
*
* @extends Component
* @class Menu
*/
var Menu = (function (_Component) {
_inherits(Menu, _Component);
function Menu() {
_classCallCheck(this, Menu);
_Component.apply(this, arguments);
}
/**
* Add a menu item to the menu
*
* @param {Object|String} component Component or component type to add
* @method addItem
*/
Menu.prototype.addItem = function addItem(component) {
this.addChild(component);
component.on('click', Fn.bind(this, function () {
this.unlockShowing();
}));
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Menu.prototype.createEl = function createEl() {
var contentElType = this.options_.contentElType || 'ul';
this.contentEl_ = Dom.createEl(contentElType, {
className: 'vjs-menu-content'
});
var el = _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
Events.on(el, 'click', function (event) {
event.preventDefault();
event.stopImmediatePropagation();
});
return el;
};
return Menu;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('Menu', Menu);
exports['default'] = Menu;
module.exports = exports['default'];
},{"../component.js":58,"../utils/dom.js":118,"../utils/events.js":119,"../utils/fn.js":120}],98:[function(_dereq_,module,exports){
/**
* @file player.js
*/
// Subclasses Component
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('./component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsGuidJs = _dereq_('./utils/guid.js');
var Guid = _interopRequireWildcard(_utilsGuidJs);
var _utilsBrowserJs = _dereq_('./utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _utilsLogJs = _dereq_('./utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js');
var _utilsBufferJs = _dereq_('./utils/buffer.js');
var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js');
var stylesheet = _interopRequireWildcard(_utilsStylesheetJs);
var _fullscreenApiJs = _dereq_('./fullscreen-api.js');
var _fullscreenApiJs2 = _interopRequireDefault(_fullscreenApiJs);
var _mediaErrorJs = _dereq_('./media-error.js');
var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs);
var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple');
var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
var _tracksTextTrackListConverterJs = _dereq_('./tracks/text-track-list-converter.js');
var _tracksTextTrackListConverterJs2 = _interopRequireDefault(_tracksTextTrackListConverterJs);
// Include required child components (importing also registers them)
var _techLoaderJs = _dereq_('./tech/loader.js');
var _techLoaderJs2 = _interopRequireDefault(_techLoaderJs);
var _posterImageJs = _dereq_('./poster-image.js');
var _posterImageJs2 = _interopRequireDefault(_posterImageJs);
var _tracksTextTrackDisplayJs = _dereq_('./tracks/text-track-display.js');
var _tracksTextTrackDisplayJs2 = _interopRequireDefault(_tracksTextTrackDisplayJs);
var _loadingSpinnerJs = _dereq_('./loading-spinner.js');
var _loadingSpinnerJs2 = _interopRequireDefault(_loadingSpinnerJs);
var _bigPlayButtonJs = _dereq_('./big-play-button.js');
var _bigPlayButtonJs2 = _interopRequireDefault(_bigPlayButtonJs);
var _controlBarControlBarJs = _dereq_('./control-bar/control-bar.js');
var _controlBarControlBarJs2 = _interopRequireDefault(_controlBarControlBarJs);
var _errorDisplayJs = _dereq_('./error-display.js');
var _errorDisplayJs2 = _interopRequireDefault(_errorDisplayJs);
var _tracksTextTrackSettingsJs = _dereq_('./tracks/text-track-settings.js');
var _tracksTextTrackSettingsJs2 = _interopRequireDefault(_tracksTextTrackSettingsJs);
// Require html5 tech, at least for disposing the original video tag
var _techHtml5Js = _dereq_('./tech/html5.js');
var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js);
/**
* An instance of the `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')`.
*
* @param {Element} tag The original video tag used for configuring options
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Component
* @class Player
*/
var Player = (function (_Component) {
_inherits(Player, _Component);
/**
* 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
*/
function Player(tag, options, ready) {
var _this = this;
_classCallCheck(this, Player);
// Make sure tag ID exists
tag.id = tag.id || 'vjs_video_' + Guid.newGUID();
// 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 = _objectAssign2['default'](Player.getTagSettings(tag), options);
// Delay the initialization of children because we need to set up
// player properties first, and can't use `this` before `super()`
options.initChildren = false;
// Same with creating the element
options.createEl = 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
_Component.call(this, null, options, ready);
// if the global option object was accidentally blown away by
// someone, bail early with an informative error
if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
}
this.tag = tag; // Store the original tag used to set options
// Store the tag attributes used to restore html5 element
this.tagAttributes = tag && Dom.getElAttributes(tag);
// Update current language
this.language(this.options_.language);
// Update Supported Languages
if (options.languages) {
(function () {
// Normalise player option languages to lowercase
var languagesToLower = {};
Object.getOwnPropertyNames(options.languages).forEach(function (name) {
languagesToLower[name.toLowerCase()] = options.languages[name];
});
_this.languages_ = languagesToLower;
})();
} else {
this.languages_ = Player.prototype.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;
/*
* Store the internal state of scrubbing
*
* @private
* @return {Boolean} True if the user is scrubbing
*/
this.scrubbing_ = false;
this.el_ = this.createEl();
// We also want to pass the original player options to each component and plugin
// as well so they don't need to reach back into the player for options later.
// We also need to do another copy of this.options_ so we don't end up with
// an infinite loop.
var playerOptionsCopy = _utilsMergeOptionsJs2['default'](this.options_);
// Load plugins
if (options.plugins) {
(function () {
var plugins = options.plugins;
Object.getOwnPropertyNames(plugins).forEach(function (name) {
if (typeof this[name] === 'function') {
this[name](plugins[name]);
} else {
_utilsLogJs2['default'].error('Unable to find plugin:', name);
}
}, _this);
})();
}
this.options_.playerOptions = playerOptionsCopy;
this.initChildren();
// Set isAudio based on whether or not an audio tag was used
this.isAudio(tag.nodeName.toLowerCase() === 'audio');
// 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');
}
if (this.isAudio()) {
this.addClass('vjs-audio');
}
if (this.flexNotSupported_()) {
this.addClass('vjs-no-flex');
}
// TODO: Make this smarter. Toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// if (browser.TOUCH_ENABLED) {
// this.addClass('vjs-touch-enabled');
// }
// Make player easily findable by ID
Player.players[this.id_] = this;
// When the player is first initialized, trigger activity so components
// like the control bar show themselves if needed
this.userActive(true);
this.reportUserActivity();
this.listenForUserActivity_();
this.on('fullscreenchange', this.handleFullscreenChange_);
this.on('stageclick', this.handleStageClick_);
}
/*
* Global player list
*
* @type {Object}
*/
/**
* Destroys the video player and does any necessary cleanup
* ```js
* myPlayer.dispose();
* ```
* This is especially helpful if you are dynamically adding and removing videos
* to/from the DOM.
*
* @method dispose
*/
Player.prototype.dispose = function dispose() {
this.trigger('dispose');
// prevent dispose from being called twice
this.off('dispose');
if (this.styleEl_) {
this.styleEl_.parentNode.removeChild(this.styleEl_);
}
// Kill reference to this player
Player.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.prototype.dispose.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Player.prototype.createEl = function createEl() {
var el = this.el_ = _Component.prototype.createEl.call(this, 'div');
var tag = this.tag;
// Remove width/height attrs from tag so CSS can make it 100% width/height
tag.removeAttribute('width');
tag.removeAttribute('height');
// Copy over all the attributes from the tag, including ID and class
// ID will now reference player box, not the video tag
var attrs = Dom.getElAttributes(tag);
Object.getOwnPropertyNames(attrs).forEach(function (attr) {
// workaround so we don't totally break IE7
// http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7
if (attr === 'class') {
el.className = attrs[attr];
} else {
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');
// Add a style element in the player that we'll use to set the width/height
// of the player in a way that's still overrideable by CSS, just like the
// video element
this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions');
var defaultsStyleEl = _globalDocument2['default'].querySelector('.vjs-styles-defaults');
var head = _globalDocument2['default'].querySelector('head');
head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
// Pass in the width/height/aspectRatio options which will update the style el
this.width(this.options_.width);
this.height(this.options_.height);
this.fluid(this.options_.fluid);
this.aspectRatio(this.options_.aspectRatio);
// insertElFirst seems to cause the networkState to flicker from 3 to 2, so
// keep track of the original for later so we can know if the source originally failed
tag.initNetworkState_ = tag.networkState;
// Wrap video tag in div (el/box) container
if (tag.parentNode) {
tag.parentNode.insertBefore(el, tag);
}
Dom.insertElFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup.
this.el_ = el;
return el;
};
/**
* Get/set player width
*
* @param {Number=} value Value for width
* @return {Number} Width when getting
* @method width
*/
Player.prototype.width = function width(value) {
return this.dimension('width', value);
};
/**
* Get/set player height
*
* @param {Number=} value Value for height
* @return {Number} Height when getting
* @method height
*/
Player.prototype.height = function height(value) {
return this.dimension('height', value);
};
/**
* Get/set dimension for player
*
* @param {String} dimension Either width or height
* @param {Number=} value Value for dimension
* @return {Component}
* @method dimension
*/
Player.prototype.dimension = function dimension(_dimension, value) {
var privDimension = _dimension + '_';
if (value === undefined) {
return this[privDimension] || 0;
}
if (value === '') {
// If an empty string is given, reset the dimension to be automatic
this[privDimension] = undefined;
} else {
var parsedVal = parseFloat(value);
if (isNaN(parsedVal)) {
_utilsLogJs2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension);
return this;
}
this[privDimension] = parsedVal;
}
this.updateStyleEl_();
return this;
};
/**
* Add/remove the vjs-fluid class
*
* @param {Boolean} bool Value of true adds the class, value of false removes the class
* @method fluid
*/
Player.prototype.fluid = function fluid(bool) {
if (bool === undefined) {
return !!this.fluid_;
}
this.fluid_ = !!bool;
if (bool) {
this.addClass('vjs-fluid');
} else {
this.removeClass('vjs-fluid');
}
};
/**
* Get/Set the aspect ratio
*
* @param {String=} ratio Aspect ratio for player
* @return aspectRatio
* @method aspectRatio
*/
Player.prototype.aspectRatio = function aspectRatio(ratio) {
if (ratio === undefined) {
return this.aspectRatio_;
}
// Check for width:height format
if (!/^\d+\:\d+$/.test(ratio)) {
throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
}
this.aspectRatio_ = ratio;
// We're assuming if you set an aspect ratio you want fluid mode,
// because in fixed mode you could calculate width and height yourself.
this.fluid(true);
this.updateStyleEl_();
};
/**
* Update styles of the player element (height, width and aspect ratio)
*
* @method updateStyleEl_
*/
Player.prototype.updateStyleEl_ = function updateStyleEl_() {
var width = undefined;
var height = undefined;
var aspectRatio = undefined;
// The aspect ratio is either used directly or to calculate width and height.
if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
// Use any aspectRatio that's been specifically set
aspectRatio = this.aspectRatio_;
} else if (this.videoWidth()) {
// Otherwise try to get the aspect ratio from the video metadata
aspectRatio = this.videoWidth() + ':' + this.videoHeight();
} else {
// Or use a default. The video element's is 2:1, but 16:9 is more common.
aspectRatio = '16:9';
}
// Get the ratio as a decimal we can use to calculate dimensions
var ratioParts = aspectRatio.split(':');
var ratioMultiplier = ratioParts[1] / ratioParts[0];
if (this.width_ !== undefined) {
// Use any width that's been specifically set
width = this.width_;
} else if (this.height_ !== undefined) {
// Or calulate the width from the aspect ratio if a height has been set
width = this.height_ / ratioMultiplier;
} else {
// Or use the video's metadata, or use the video el's default of 300
width = this.videoWidth() || 300;
}
if (this.height_ !== undefined) {
// Use any height that's been specifically set
height = this.height_;
} else {
// Otherwise calculate the height from the ratio and the width
height = width * ratioMultiplier;
}
var idClass = this.id() + '-dimensions';
// Ensure the right class is still on the player for the style element
this.addClass(idClass);
stylesheet.setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n ');
};
/**
* Load the Media Playback Technology (tech)
* Load/Create an instance of playback technology including element and API methods
* And append playback element in player div.
*
* @param {String} techName Name of the playback technology
* @param {String} source Video source
* @method loadTech_
* @private
*/
Player.prototype.loadTech_ = function loadTech_(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) {
_componentJs2['default'].getComponent('Html5').disposeMediaElement(this.tag);
this.tag.player = null;
this.tag = null;
}
this.techName_ = techName;
// Turn off API access because we're loading a new tech that might load asynchronously
this.isReady_ = false;
// Grab tech-specific options from player options and add source and parent element to use.
var techOptions = _objectAssign2['default']({
'nativeControlsForTouch': this.options_.nativeControlsForTouch,
'source': source,
'playerId': this.id(),
'techId': this.id() + '_' + techName + '_api',
'textTracks': this.textTracks_,
'autoplay': this.options_.autoplay,
'preload': this.options_.preload,
'loop': this.options_.loop,
'muted': this.options_.muted,
'poster': this.poster(),
'language': this.language(),
'vtt.js': this.options_['vtt.js']
}, this.options_[techName.toLowerCase()]);
if (this.tag) {
techOptions.tag = this.tag;
}
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
var techComponent = _componentJs2['default'].getComponent(techName);
this.tech_ = new techComponent(techOptions);
// player.triggerReady is always async, so don't need this to be async
this.tech_.ready(Fn.bind(this, this.handleTechReady_), true);
_tracksTextTrackListConverterJs2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
// Listen to all HTML5-defined events and trigger them on the player
this.on(this.tech_, 'loadstart', this.handleTechLoadStart_);
this.on(this.tech_, 'waiting', this.handleTechWaiting_);
this.on(this.tech_, 'canplay', this.handleTechCanPlay_);
this.on(this.tech_, 'canplaythrough', this.handleTechCanPlayThrough_);
this.on(this.tech_, 'playing', this.handleTechPlaying_);
this.on(this.tech_, 'ended', this.handleTechEnded_);
this.on(this.tech_, 'seeking', this.handleTechSeeking_);
this.on(this.tech_, 'seeked', this.handleTechSeeked_);
this.on(this.tech_, 'play', this.handleTechPlay_);
this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_);
this.on(this.tech_, 'pause', this.handleTechPause_);
this.on(this.tech_, 'progress', this.handleTechProgress_);
this.on(this.tech_, 'durationchange', this.handleTechDurationChange_);
this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_);
this.on(this.tech_, 'error', this.handleTechError_);
this.on(this.tech_, 'suspend', this.handleTechSuspend_);
this.on(this.tech_, 'abort', this.handleTechAbort_);
this.on(this.tech_, 'emptied', this.handleTechEmptied_);
this.on(this.tech_, 'stalled', this.handleTechStalled_);
this.on(this.tech_, 'loadedmetadata', this.handleTechLoadedMetaData_);
this.on(this.tech_, 'loadeddata', this.handleTechLoadedData_);
this.on(this.tech_, 'timeupdate', this.handleTechTimeUpdate_);
this.on(this.tech_, 'ratechange', this.handleTechRateChange_);
this.on(this.tech_, 'volumechange', this.handleTechVolumeChange_);
this.on(this.tech_, 'texttrackchange', this.handleTechTextTrackChange_);
this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_);
this.usingNativeControls(this.techGet_('controls'));
if (this.controls() && !this.usingNativeControls()) {
this.addTechControlsListeners_();
}
// Add the tech element in the DOM if it was not already there
// Make sure to not insert the original video element if using Html5
if (this.tech_.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) {
Dom.insertElFirst(this.tech_.el(), this.el());
}
// Get rid of the original video tag reference after the first tech is loaded
if (this.tag) {
this.tag.player = null;
this.tag = null;
}
};
/**
* Unload playback technology
*
* @method unloadTech_
* @private
*/
Player.prototype.unloadTech_ = function unloadTech_() {
// Save the current text tracks so that we can reuse the same text tracks with the next tech
this.textTracks_ = this.textTracks();
this.textTracksJson_ = _tracksTextTrackListConverterJs2['default'].textTracksToJson(this);
this.isReady_ = false;
this.tech_.dispose();
this.tech_ = false;
};
/**
* 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
*
* @private
* @method addTechControlsListeners_
*/
Player.prototype.addTechControlsListeners_ = function addTechControlsListeners_() {
// Make sure to remove all the previous listeners in case we are called multiple times.
this.removeTechControlsListeners_();
// 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(this.tech_, 'mousedown', this.handleTechClick_);
// 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(this.tech_, 'touchstart', this.handleTechTouchStart_);
this.on(this.tech_, 'touchmove', this.handleTechTouchMove_);
this.on(this.tech_, 'touchend', this.handleTechTouchEnd_);
// The tap listener needs to come after the touchend listener because the tap
// listener cancels out any reportedUserActivity when setting userActive(false)
this.on(this.tech_, 'tap', this.handleTechTap_);
};
/**
* Remove the listeners used for click and tap controls. This is needed for
* toggling to controls disabled, where a tap/touch should do nothing.
*
* @method removeTechControlsListeners_
* @private
*/
Player.prototype.removeTechControlsListeners_ = function removeTechControlsListeners_() {
// We don't want to just use `this.off()` because there might be other needed
// listeners added by techs that extend this.
this.off(this.tech_, 'tap', this.handleTechTap_);
this.off(this.tech_, 'touchstart', this.handleTechTouchStart_);
this.off(this.tech_, 'touchmove', this.handleTechTouchMove_);
this.off(this.tech_, 'touchend', this.handleTechTouchEnd_);
this.off(this.tech_, 'mousedown', this.handleTechClick_);
};
/**
* Player waits for the tech to be ready
*
* @method handleTechReady_
* @private
*/
Player.prototype.handleTechReady_ = function handleTechReady_() {
this.triggerReady();
// Keep the same volume as before
if (this.cache_.volume) {
this.techCall_('setVolume', this.cache_.volume);
}
// Update the duration if available
this.handleTechDurationChange_();
// 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
if (this.tag && this.options_.autoplay && this.paused()) {
delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16.
this.play();
}
};
/**
* Fired when the user agent begins looking for media data
*
* @private
* @method handleTechLoadStart_
*/
Player.prototype.handleTechLoadStart_ = function handleTechLoadStart_() {
// TODO: Update to use `emptied` event instead. See #1277.
this.removeClass('vjs-ended');
// 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('loadstart');
this.trigger('firstplay');
} else {
// reset the hasStarted state
this.hasStarted(false);
this.trigger('loadstart');
}
};
/**
* Add/remove the vjs-has-started class
*
* @param {Boolean} hasStarted The value of true adds the class the value of false remove the class
* @return {Boolean} Boolean value if has started
* @private
* @method hasStarted
*/
Player.prototype.hasStarted = function hasStarted(_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 whenever the media begins or resumes playback
*
* @private
* @method handleTechPlay_
*/
Player.prototype.handleTechPlay_ = function handleTechPlay_() {
this.removeClass('vjs-ended');
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
// hide the poster when the user hits play
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play
this.hasStarted(true);
this.trigger('play');
};
/**
* Fired whenever the media begins waiting
*
* @private
* @method handleTechWaiting_
*/
Player.prototype.handleTechWaiting_ = function handleTechWaiting_() {
this.addClass('vjs-waiting');
this.trigger('waiting');
};
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
*
* @private
* @method handleTechCanPlay_
*/
Player.prototype.handleTechCanPlay_ = function handleTechCanPlay_() {
this.removeClass('vjs-waiting');
this.trigger('canplay');
};
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
*
* @private
* @method handleTechCanPlayThrough_
*/
Player.prototype.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() {
this.removeClass('vjs-waiting');
this.trigger('canplaythrough');
};
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
*
* @private
* @method handleTechPlaying_
*/
Player.prototype.handleTechPlaying_ = function handleTechPlaying_() {
this.removeClass('vjs-waiting');
this.trigger('playing');
};
/**
* Fired whenever the player is jumping to a new time
*
* @private
* @method handleTechSeeking_
*/
Player.prototype.handleTechSeeking_ = function handleTechSeeking_() {
this.addClass('vjs-seeking');
this.trigger('seeking');
};
/**
* Fired when the player has finished jumping to a new time
*
* @private
* @method handleTechSeeked_
*/
Player.prototype.handleTechSeeked_ = function handleTechSeeked_() {
this.removeClass('vjs-seeking');
this.trigger('seeked');
};
/**
* 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.
*
* @private
* @method handleTechFirstPlay_
*/
Player.prototype.handleTechFirstPlay_ = function handleTechFirstPlay_() {
//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');
this.trigger('firstplay');
};
/**
* Fired whenever the media has been paused
*
* @private
* @method handleTechPause_
*/
Player.prototype.handleTechPause_ = function handleTechPause_() {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
this.trigger('pause');
};
/**
* Fired while the user agent is downloading media data
*
* @private
* @method handleTechProgress_
*/
Player.prototype.handleTechProgress_ = function handleTechProgress_() {
this.trigger('progress');
};
/**
* Fired when the end of the media resource is reached (currentTime == duration)
*
* @private
* @method handleTechEnded_
*/
Player.prototype.handleTechEnded_ = function handleTechEnded_() {
this.addClass('vjs-ended');
if (this.options_.loop) {
this.currentTime(0);
this.play();
} else if (!this.paused()) {
this.pause();
}
this.trigger('ended');
};
/**
* Fired when the duration of the media resource is first known or changed
*
* @private
* @method handleTechDurationChange_
*/
Player.prototype.handleTechDurationChange_ = function handleTechDurationChange_() {
this.duration(this.techGet_('duration'));
};
/**
* Handle a click on the media element to play/pause
*
* @param {Object=} event Event object
* @private
* @method handleTechClick_
*/
Player.prototype.handleTechClick_ = function handleTechClick_(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.controls()) {
if (this.paused()) {
this.play();
} else {
this.pause();
}
}
};
/**
* Handle a tap on the media element. It will toggle the user
* activity state, which hides and shows the controls.
*
* @private
* @method handleTechTap_
*/
Player.prototype.handleTechTap_ = function handleTechTap_() {
this.userActive(!this.userActive());
};
/**
* Handle touch to start
*
* @private
* @method handleTechTouchStart_
*/
Player.prototype.handleTechTouchStart_ = function handleTechTouchStart_() {
this.userWasActive = this.userActive();
};
/**
* Handle touch to move
*
* @private
* @method handleTechTouchMove_
*/
Player.prototype.handleTechTouchMove_ = function handleTechTouchMove_() {
if (this.userWasActive) {
this.reportUserActivity();
}
};
/**
* Handle touch to end
*
* @private
* @method handleTechTouchEnd_
*/
Player.prototype.handleTechTouchEnd_ = function handleTechTouchEnd_(event) {
// Stop the mouse events from also happening
event.preventDefault();
};
/**
* Fired when the player switches in or out of fullscreen mode
*
* @private
* @method handleFullscreenChange_
*/
Player.prototype.handleFullscreenChange_ = function handleFullscreenChange_() {
if (this.isFullscreen()) {
this.addClass('vjs-fullscreen');
} else {
this.removeClass('vjs-fullscreen');
}
};
/**
* native click events on the SWF aren't triggered on IE11, Win8.1RT
* use stageclick events triggered from inside the SWF instead
*
* @private
* @method handleStageClick_
*/
Player.prototype.handleStageClick_ = function handleStageClick_() {
this.reportUserActivity();
};
/**
* Handle Tech Fullscreen Change
*
* @private
* @method handleTechFullscreenChange_
*/
Player.prototype.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) {
if (data) {
this.isFullscreen(data.isFullscreen);
}
this.trigger('fullscreenchange');
};
/**
* Fires when an error occurred during the loading of an audio/video
*
* @private
* @method handleTechError_
*/
Player.prototype.handleTechError_ = function handleTechError_() {
var error = this.tech_.error();
this.error(error && error.code);
};
/**
* Fires when the browser is intentionally not getting media data
*
* @private
* @method handleTechSuspend_
*/
Player.prototype.handleTechSuspend_ = function handleTechSuspend_() {
this.trigger('suspend');
};
/**
* Fires when the loading of an audio/video is aborted
*
* @private
* @method handleTechAbort_
*/
Player.prototype.handleTechAbort_ = function handleTechAbort_() {
this.trigger('abort');
};
/**
* Fires when the current playlist is empty
*
* @private
* @method handleTechEmptied_
*/
Player.prototype.handleTechEmptied_ = function handleTechEmptied_() {
this.trigger('emptied');
};
/**
* Fires when the browser is trying to get media data, but data is not available
*
* @private
* @method handleTechStalled_
*/
Player.prototype.handleTechStalled_ = function handleTechStalled_() {
this.trigger('stalled');
};
/**
* Fires when the browser has loaded meta data for the audio/video
*
* @private
* @method handleTechLoadedMetaData_
*/
Player.prototype.handleTechLoadedMetaData_ = function handleTechLoadedMetaData_() {
this.trigger('loadedmetadata');
};
/**
* Fires when the browser has loaded the current frame of the audio/video
*
* @private
* @method handleTechLoadedData_
*/
Player.prototype.handleTechLoadedData_ = function handleTechLoadedData_() {
this.trigger('loadeddata');
};
/**
* Fires when the current playback position has changed
*
* @private
* @method handleTechTimeUpdate_
*/
Player.prototype.handleTechTimeUpdate_ = function handleTechTimeUpdate_() {
this.trigger('timeupdate');
};
/**
* Fires when the playing speed of the audio/video is changed
*
* @private
* @method handleTechRateChange_
*/
Player.prototype.handleTechRateChange_ = function handleTechRateChange_() {
this.trigger('ratechange');
};
/**
* Fires when the volume has been changed
*
* @private
* @method handleTechVolumeChange_
*/
Player.prototype.handleTechVolumeChange_ = function handleTechVolumeChange_() {
this.trigger('volumechange');
};
/**
* Fires when the text track has been changed
*
* @private
* @method handleTechTextTrackChange_
*/
Player.prototype.handleTechTextTrackChange_ = function handleTechTextTrackChange_() {
this.trigger('texttrackchange');
};
/**
* Get object for cached values.
*
* @return {Object}
* @method getCache
*/
Player.prototype.getCache = function getCache() {
return this.cache_;
};
/**
* Pass values to the playback tech
*
* @param {String=} method Method
* @param {Object=} arg Argument
* @private
* @method techCall_
*/
Player.prototype.techCall_ = function techCall_(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);
}, true);
// Otherwise call method now
} else {
try {
this.tech_[method](arg);
} catch (e) {
_utilsLogJs2['default'](e);
throw e;
}
}
};
/**
* Get calls can't wait for the tech, and sometimes don't need to.
*
* @param {String} method Tech method
* @return {Method}
* @private
* @method techGet_
*/
Player.prototype.techGet_ = function techGet_(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) {
_utilsLogJs2['default']('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') {
_utilsLogJs2['default']('Video.js: ' + method + ' unavailable on ' + this.techName_ + ' playback technology element.', e);
this.tech_.isReady_ = false;
} else {
_utilsLogJs2['default'](e);
}
}
throw e;
}
}
return;
};
/**
* start media playback
* ```js
* myPlayer.play();
* ```
*
* @return {Player} self
* @method play
*/
Player.prototype.play = function play() {
this.techCall_('play');
return this;
};
/**
* Pause the video playback
* ```js
* myPlayer.pause();
* ```
*
* @return {Player} self
* @method pause
*/
Player.prototype.pause = function pause() {
this.techCall_('pause');
return this;
};
/**
* Check if the player is paused
* ```js
* var isPaused = myPlayer.paused();
* var isPlaying = !myPlayer.paused();
* ```
*
* @return {Boolean} false if the media is currently playing, or true otherwise
* @method paused
*/
Player.prototype.paused = function paused() {
// The initial state of paused should be true (in Safari it's actually false)
return this.techGet_('paused') === false ? false : true;
};
/**
* Returns whether or not the user is "scrubbing". Scrubbing is when the user
* has clicked the progress bar handle and is dragging it along the progress bar.
*
* @param {Boolean} isScrubbing True/false the user is scrubbing
* @return {Boolean} The scrubbing status when getting
* @return {Object} The player when setting
* @method scrubbing
*/
Player.prototype.scrubbing = function scrubbing(isScrubbing) {
if (isScrubbing !== undefined) {
this.scrubbing_ = !!isScrubbing;
if (isScrubbing) {
this.addClass('vjs-scrubbing');
} else {
this.removeClass('vjs-scrubbing');
}
return this;
}
return this.scrubbing_;
};
/**
* Get or set the current time (in seconds)
* ```js
* // 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 {Player} self, when the current time is set
* @method currentTime
*/
Player.prototype.currentTime = function currentTime(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 performance 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
* ```js
* 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.
*
* @param {Number} seconds Duration when setting
* @return {Number} The duration of the video in seconds when getting
* @method duration
*/
Player.prototype.duration = function duration(seconds) {
if (seconds === undefined) {
return this.cache_.duration || 0;
}
seconds = parseFloat(seconds) || 0;
// Standardize on Inifity for signaling video is live
if (seconds < 0) {
seconds = Infinity;
}
if (seconds !== this.cache_.duration) {
// Cache the last set value for optimized scrubbing (esp. Flash)
this.cache_.duration = seconds;
if (seconds === Infinity) {
this.addClass('vjs-live');
} else {
this.removeClass('vjs-live');
}
this.trigger('durationchange');
}
return this;
};
/**
* Calculates how much time is left.
* ```js
* var timeLeft = myPlayer.remainingTime();
* ```
* Not a native video element function, but useful
*
* @return {Number} The time remaining in seconds
* @method remainingTime
*/
Player.prototype.remainingTime = function remainingTime() {
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.
* ```js
* // 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)
* @method buffered
*/
Player.prototype.buffered = function buffered() {
var buffered = this.techGet_('buffered');
if (!buffered || !buffered.length) {
buffered = _utilsTimeRangesJs.createTimeRange(0, 0);
}
return buffered;
};
/**
* Get the percent (as a decimal) of the video that's been downloaded
* ```js
* 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
* @method bufferedPercent
*/
Player.prototype.bufferedPercent = function bufferedPercent() {
return _utilsBufferJs.bufferedPercent(this.buffered(), this.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
* @method bufferedEnd
*/
Player.prototype.bufferedEnd = function bufferedEnd() {
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
* ```js
* // 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 {Player} self when setting
* @method volume
*/
Player.prototype.volume = function volume(percentAsDecimal) {
var vol = undefined;
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);
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
* ```js
* // 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 {Player} self when setting mute
* @method muted
*/
Player.prototype.muted = function muted(_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 like iOS, so not our flash swf)
/**
* Check to see if fullscreen is supported
*
* @return {Boolean}
* @method supportsFullScreen
*/
Player.prototype.supportsFullScreen = function supportsFullScreen() {
return this.techGet_('supportsFullScreen') || false;
};
/**
* Check if the player is in fullscreen mode
* ```js
* // 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 when getting
* @return {Player} self when setting
* @method isFullscreen
*/
Player.prototype.isFullscreen = function isFullscreen(isFS) {
if (isFS !== undefined) {
this.isFullscreen_ = !!isFS;
return this;
}
return !!this.isFullscreen_;
};
/**
* Increase the size of the video to full screen
* ```js
* 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 {Player} self
* @method requestFullscreen
*/
Player.prototype.requestFullscreen = function requestFullscreen() {
var fsApi = _fullscreenApiJs2['default'];
this.isFullscreen(true);
if (fsApi.requestFullscreen) {
// 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 canceling fullscreen. Otherwise if there's multiple
// players on a page, they would all be reacting to the same fullscreen
// events
Events.on(_globalDocument2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) {
this.isFullscreen(_globalDocument2['default'][fsApi.fullscreenElement]);
// If cancelling fullscreen, remove event listener.
if (this.isFullscreen() === false) {
Events.off(_globalDocument2['default'], fsApi.fullscreenchange, documentFullscreenChange);
}
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;
};
/**
* Return the video to its normal size after having been in full screen mode
* ```js
* myPlayer.exitFullscreen();
* ```
*
* @return {Player} self
* @method exitFullscreen
*/
Player.prototype.exitFullscreen = function exitFullscreen() {
var fsApi = _fullscreenApiJs2['default'];
this.isFullscreen(false);
// Check for browser element fullscreen support
if (fsApi.requestFullscreen) {
_globalDocument2['default'][fsApi.exitFullscreen]();
} else if (this.tech_.supportsFullScreen()) {
this.techCall_('exitFullScreen');
} else {
this.exitFullWindow();
this.trigger('fullscreenchange');
}
return this;
};
/**
* When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us.
*
* @method enterFullWindow
*/
Player.prototype.enterFullWindow = function enterFullWindow() {
this.isFullWindow = true;
// Storing original doc overflow value to return to when fullscreen is off
this.docOrigOverflow = _globalDocument2['default'].documentElement.style.overflow;
// Add listener for esc key to exit fullscreen
Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey));
// Hide any scroll bars
_globalDocument2['default'].documentElement.style.overflow = 'hidden';
// Apply fullscreen styles
Dom.addElClass(_globalDocument2['default'].body, 'vjs-full-window');
this.trigger('enterFullWindow');
};
/**
* Check for call to either exit full window or full screen on ESC key
*
* @param {String} event Event to check for key press
* @method fullWindowOnEscKey
*/
Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) {
if (event.keyCode === 27) {
if (this.isFullscreen() === true) {
this.exitFullscreen();
} else {
this.exitFullWindow();
}
}
};
/**
* Exit full window
*
* @method exitFullWindow
*/
Player.prototype.exitFullWindow = function exitFullWindow() {
this.isFullWindow = false;
Events.off(_globalDocument2['default'], 'keydown', this.fullWindowOnEscKey);
// Unhide scroll bars.
_globalDocument2['default'].documentElement.style.overflow = this.docOrigOverflow;
// Remove fullscreen styles
Dom.removeElClass(_globalDocument2['default'].body, 'vjs-full-window');
// Resize the box, controller, and poster to original sizes
// this.positionAll();
this.trigger('exitFullWindow');
};
/**
* Select source based on tech order
*
* @param {Array} sources The sources for a media asset
* @return {Object|Boolean} Object of source and tech order, otherwise false
* @method selectSource
*/
Player.prototype.selectSource = function selectSource(sources) {
// Loop through each playback technology in the options order
for (var i = 0, j = this.options_.techOrder; i < j.length; i++) {
var techName = _utilsToTitleCaseJs2['default'](j[i]);
var tech = _componentJs2['default'].getComponent(techName);
// Check if the current tech is defined before continuing
if (!tech) {
_utilsLogJs2['default'].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.
* ```js
* 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.
* ```js
* 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.
* ```js
* 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
* @method src
*/
Player.prototype.src = function src(source) {
if (source === undefined) {
return this.techGet_('src');
}
var currentTech = _componentJs2['default'].getComponent(this.techName_);
// case: Array of source objects to choose from and pick the best to play
if (Array.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 && !currentTech.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 () {
// The setSource tech method was added with source handlers
// so older techs won't support it
// We need to check the direct prototype for the case where subclasses
// of the tech do not support source handlers
if (currentTech.prototype.hasOwnProperty('setSource')) {
this.techCall_('setSource', source);
} else {
this.techCall_('src', source.src);
}
if (this.options_.preload === 'auto') {
this.load();
}
if (this.options_.autoplay) {
this.play();
}
// Set the source synchronously if possible (#2326)
}, true);
}
}
return this;
};
/**
* Handle an array of source objects
*
* @param {Array} sources Array of source objects
* @private
* @method sourceList_
*/
Player.prototype.sourceList_ = function sourceList_(sources) {
var sourceTech = this.selectSource(sources);
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
this.setTimeout(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();
}
};
/**
* Begin loading the src data.
*
* @return {Player} Returns the player
* @method load
*/
Player.prototype.load = function load() {
this.techCall_('load');
return this;
};
/**
* Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
* Can be used in conjuction with `currentType` to assist in rebuilding the current source object.
*
* @return {String} The current source
* @method currentSrc
*/
Player.prototype.currentSrc = function currentSrc() {
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
* @method currentType
*/
Player.prototype.currentType = function currentType() {
return this.currentType_ || '';
};
/**
* Get or set the preload attribute
*
* @param {Boolean} value Boolean to determine if preload should be used
* @return {String} The preload attribute value when getting
* @return {Player} Returns the player when setting
* @method preload
*/
Player.prototype.preload = function preload(value) {
if (value !== undefined) {
this.techCall_('setPreload', value);
this.options_.preload = value;
return this;
}
return this.techGet_('preload');
};
/**
* Get or set the autoplay attribute.
*
* @param {Boolean} value Boolean to determine if preload should be used
* @return {String} The autoplay attribute value when getting
* @return {Player} Returns the player when setting
* @method autoplay
*/
Player.prototype.autoplay = function autoplay(value) {
if (value !== undefined) {
this.techCall_('setAutoplay', value);
this.options_.autoplay = value;
return this;
}
return this.techGet_('autoplay', value);
};
/**
* Get or set the loop attribute on the video element.
*
* @param {Boolean} value Boolean to determine if preload should be used
* @return {String} The loop attribute value when getting
* @return {Player} Returns the player when setting
* @method loop
*/
Player.prototype.loop = function loop(value) {
if (value !== undefined) {
this.techCall_('setLoop', value);
this.options_['loop'] = value;
return this;
}
return this.techGet_('loop');
};
/**
* get or set the poster image source url
* ##### EXAMPLE:
* ```js
* // get
* var currentPoster = myPlayer.poster();
* // set
* myPlayer.poster('http://example.com/myImage.jpg');
* ```
*
* @param {String=} src Poster image source URL
* @return {String} poster URL when getting
* @return {Player} self when setting
* @method poster
*/
Player.prototype.poster = function poster(src) {
if (src === undefined) {
return this.poster_;
}
// The correct way to remove a poster is to set as an empty string
// other falsey values will throw errors
if (!src) {
src = '';
}
// 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');
return this;
};
/**
* Get or set whether or not the controls are showing.
*
* @param {Boolean} bool Set controls to showing or not
* @return {Boolean} Controls are showing
* @method controls
*/
Player.prototype.controls = function controls(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 (this.usingNativeControls()) {
this.techCall_('setControls', bool);
}
if (bool) {
this.removeClass('vjs-controls-disabled');
this.addClass('vjs-controls-enabled');
this.trigger('controlsenabled');
if (!this.usingNativeControls()) {
this.addTechControlsListeners_();
}
} else {
this.removeClass('vjs-controls-enabled');
this.addClass('vjs-controls-disabled');
this.trigger('controlsdisabled');
if (!this.usingNativeControls()) {
this.removeTechControlsListeners_();
}
}
}
return this;
}
return !!this.controls_;
};
/**
* 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 {Player} Returns the player
* @private
* @method usingNativeControls
*/
Player.prototype.usingNativeControls = function usingNativeControls(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 Player
* @instance
* @private
*/
this.trigger('usingnativecontrols');
} else {
this.removeClass('vjs-using-native-controls');
/**
* player is using the custom HTML controls
*
* @event usingcustomcontrols
* @memberof Player
* @instance
* @private
*/
this.trigger('usingcustomcontrols');
}
}
return this;
}
return !!this.usingNativeControls_;
};
/**
* Set or get the current MediaError
*
* @param {*} err A MediaError or a String/Number to be turned into a MediaError
* @return {MediaError|null} when getting
* @return {Player} when setting
* @method error
*/
Player.prototype.error = function error(err) {
if (err === undefined) {
return this.error_ || null;
}
// restoring to default
if (err === null) {
this.error_ = err;
this.removeClass('vjs-error');
return this;
}
// error instance
if (err instanceof _mediaErrorJs2['default']) {
this.error_ = err;
} else {
this.error_ = new _mediaErrorJs2['default'](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
_utilsLogJs2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaErrorJs2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_);
return this;
};
/**
* Returns whether or not the player is in the "ended" state.
*
* @return {Boolean} True if the player is in the ended state, false if not.
* @method ended
*/
Player.prototype.ended = function ended() {
return this.techGet_('ended');
};
/**
* Returns whether or not the player is in the "seeking" state.
*
* @return {Boolean} True if the player is in the seeking state, false if not.
* @method seeking
*/
Player.prototype.seeking = function seeking() {
return this.techGet_('seeking');
};
/**
* Returns the TimeRanges of the media that are currently available
* for seeking to.
*
* @return {TimeRanges} the seekable intervals of the media timeline
* @method seekable
*/
Player.prototype.seekable = function seekable() {
return this.techGet_('seekable');
};
/**
* Report user activity
*
* @param {Object} event Event object
* @method reportUserActivity
*/
Player.prototype.reportUserActivity = function reportUserActivity(event) {
this.userActivity_ = true;
};
/**
* Get/set if user is active
*
* @param {Boolean} bool Value when setting
* @return {Boolean} Value if user is active user when getting
* @method userActive
*/
Player.prototype.userActive = function userActive(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_;
};
/**
* Listen for user activity based on timeout value
*
* @private
* @method listenForUserActivity_
*/
Player.prototype.listenForUserActivity_ = function listenForUserActivity_() {
var mouseInProgress = undefined,
lastMoveX = undefined,
lastMoveY = undefined;
var handleActivity = Fn.bind(this, this.reportUserActivity);
var handleMouseMove = function handleMouseMove(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;
handleActivity();
}
};
var handleMouseDown = function handleMouseDown() {
handleActivity();
// 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
this.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 = this.setInterval(handleActivity, 250);
};
var handleMouseUp = function handleMouseUp(event) {
handleActivity();
// Stop the interval that maintains activity if the mouse/touch is down
this.clearInterval(mouseInProgress);
};
// Any mouse movement will be considered user activity
this.on('mousedown', handleMouseDown);
this.on('mousemove', handleMouseMove);
this.on('mouseup', handleMouseUp);
// Listen for keyboard navigation
// Shouldn't need to use inProgress interval because of key repeat
this.on('keydown', handleActivity);
this.on('keyup', handleActivity);
// 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/
var inactivityTimeout = undefined;
var activityCheck = this.setInterval(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
this.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 = this.setTimeout(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);
};
/**
* Gets or sets the current playback rate. A playback rate of
* 1.0 represents normal speed and 0.5 would indicate half-speed
* playback, for instance.
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
*
* @param {Number} rate New playback rate to set.
* @return {Number} Returns the new playback rate when setting
* @return {Number} Returns the current playback rate when getting
* @method playbackRate
*/
Player.prototype.playbackRate = function playbackRate(rate) {
if (rate !== undefined) {
this.techCall_('setPlaybackRate', rate);
return this;
}
if (this.tech_ && this.tech_['featuresPlaybackRate']) {
return this.techGet_('playbackRate');
} else {
return 1.0;
}
};
/**
* Gets or sets the audio flag
*
* @param {Boolean} bool True signals that this is an audio player.
* @return {Boolean} Returns true if player is audio, false if not when getting
* @return {Player} Returns the player if setting
* @private
* @method isAudio
*/
Player.prototype.isAudio = function isAudio(bool) {
if (bool !== undefined) {
this.isAudio_ = !!bool;
return this;
}
return !!this.isAudio_;
};
/**
* Returns the current state of network activity for the element, from
* the codes in the list below.
* - NETWORK_EMPTY (numeric value 0)
* The element has not yet been initialised. All attributes are in
* their initial states.
* - NETWORK_IDLE (numeric value 1)
* The element's resource selection algorithm is active and has
* selected a resource, but it is not actually using the network at
* this time.
* - NETWORK_LOADING (numeric value 2)
* The user agent is actively trying to download data.
* - NETWORK_NO_SOURCE (numeric value 3)
* The element's resource selection algorithm is active, but it has
* not yet found a resource to use.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
* @return {Number} the current network activity state
* @method networkState
*/
Player.prototype.networkState = function networkState() {
return this.techGet_('networkState');
};
/**
* Returns a value that expresses the current state of the element
* with respect to rendering the current playback position, from the
* codes in the list below.
* - HAVE_NOTHING (numeric value 0)
* No information regarding the media resource is available.
* - HAVE_METADATA (numeric value 1)
* Enough of the resource has been obtained that the duration of the
* resource is available.
* - HAVE_CURRENT_DATA (numeric value 2)
* Data for the immediate current playback position is available.
* - HAVE_FUTURE_DATA (numeric value 3)
* Data for the immediate current playback position is available, as
* well as enough data for the user agent to advance the current
* playback position in the direction of playback.
* - HAVE_ENOUGH_DATA (numeric value 4)
* The user agent estimates that enough data is available for
* playback to proceed uninterrupted.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
* @return {Number} the current playback rendering state
* @method readyState
*/
Player.prototype.readyState = function readyState() {
return this.techGet_('readyState');
};
/*
* Text tracks are tracks of timed text events.
* Captions - text displayed over the video for the hearing impaired
* Subtitles - text displayed over the video for those who don't understand language 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
*/
/**
* 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
* @method textTracks
*/
Player.prototype.textTracks = function textTracks() {
// cannot use techGet_ directly because it checks to see whether the tech is ready.
// Flash is unlikely to be ready in time but textTracks should still work.
return this.tech_ && this.tech_['textTracks']();
};
/**
* Get an array of remote text tracks
*
* @return {Array}
* @method remoteTextTracks
*/
Player.prototype.remoteTextTracks = function remoteTextTracks() {
return this.tech_ && this.tech_['remoteTextTracks']();
};
/**
* 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
* @method addTextTrack
*/
Player.prototype.addTextTrack = function addTextTrack(kind, label, language) {
return this.tech_ && this.tech_['addTextTrack'](kind, label, language);
};
/**
* Add a remote text track
*
* @param {Object} options Options for remote text track
* @method addRemoteTextTrack
*/
Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) {
return this.tech_ && this.tech_['addRemoteTextTrack'](options);
};
/**
* Remove a remote text track
*
* @param {Object} track Remote text track to remove
* @method removeRemoteTextTrack
*/
Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
this.tech_ && this.tech_['removeRemoteTextTrack'](track);
};
/**
* Get video width
*
* @return {Number} Video width
* @method videoWidth
*/
Player.prototype.videoWidth = function videoWidth() {
return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
};
/**
* Get video height
*
* @return {Number} Video height
* @method videoHeight
*/
Player.prototype.videoHeight = function videoHeight() {
return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
};
// Methods to add support for
// initialTime: function(){ return this.techCall_('initialTime'); },
// startOffsetTime: function(){ return this.techCall_('startOffsetTime'); },
// played: function(){ return this.techCall_('played'); },
// videoTracks: function(){ return this.techCall_('videoTracks'); },
// audioTracks: function(){ return this.techCall_('audioTracks'); },
// defaultPlaybackRate: function(){ return this.techCall_('defaultPlaybackRate'); },
// defaultMuted: function(){ return this.techCall_('defaultMuted'); }
/**
* The player's language code
* NOTE: The language should be set in the player options if you want the
* the controls to be built with a specific language. Changing the lanugage
* later will not update controls text.
*
* @param {String} code The locale string
* @return {String} The locale string when getting
* @return {Player} self when setting
* @method language
*/
Player.prototype.language = function language(code) {
if (code === undefined) {
return this.language_;
}
this.language_ = ('' + code).toLowerCase();
return this;
};
/**
* Get the player's language dictionary
* Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
* Languages specified directly in the player options have precedence
*
* @return {Array} Array of languages
* @method languages
*/
Player.prototype.languages = function languages() {
return _utilsMergeOptionsJs2['default'](Player.prototype.options_.languages, this.languages_);
};
/**
* Converts track info to JSON
*
* @return {Object} JSON object of options
* @method toJSON
*/
Player.prototype.toJSON = function toJSON() {
var options = _utilsMergeOptionsJs2['default'](this.options_);
var tracks = options.tracks;
options.tracks = [];
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
// deep merge tracks and null out player so no circular references
track = _utilsMergeOptionsJs2['default'](track);
track.player = undefined;
options.tracks[i] = track;
}
return options;
};
/**
* Gets tag settings
*
* @param {Element} tag The player tag
* @return {Array} An array of sources and track objects
* @static
* @method getTagSettings
*/
Player.getTagSettings = function getTagSettings(tag) {
var baseOptions = {
'sources': [],
'tracks': []
};
var tagOptions = Dom.getElAttributes(tag);
var dataSetup = tagOptions['data-setup'];
// Check if data-setup attr exists.
if (dataSetup !== null) {
// Parse options JSON
var _safeParseTuple = _safeJsonParseTuple2['default'](dataSetup || '{}');
var err = _safeParseTuple[0];
var data = _safeParseTuple[1];
if (err) {
_utilsLogJs2['default'].error(err);
}
_objectAssign2['default'](tagOptions, data);
}
_objectAssign2['default'](baseOptions, tagOptions);
// Get tag children settings
if (tag.hasChildNodes()) {
var children = tag.childNodes;
for (var i = 0, j = children.length; i < j; i++) {
var child = children[i];
// Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
var childName = child.nodeName.toLowerCase();
if (childName === 'source') {
baseOptions.sources.push(Dom.getElAttributes(child));
} else if (childName === 'track') {
baseOptions.tracks.push(Dom.getElAttributes(child));
}
}
}
return baseOptions;
};
return Player;
})(_componentJs2['default']);
Player.players = {};
var navigator = _globalWindow2['default'].navigator;
/*
* Player instance options, surfaced using options
* options = Player.prototype.options_
* Make changes in options, not here.
*
* @type {Object}
* @private
*/
Player.prototype.options_ = {
// Default order of fallback technology
techOrder: ['html5', 'flash'],
// techOrder: ['flash','html5'],
html5: {},
flash: {},
// defaultVolume: 0.85,
defaultVolume: 0.00, // The freakin seaguls are driving me crazy!
// default inactivity timeout
inactivityTimeout: 2000,
// default playback rates
playbackRates: [],
// Add playback rate selection by adding rates
// 'playbackRates': [0.5, 1, 1.5, 2],
// Included control sets
children: {
mediaLoader: {},
posterImage: {},
textTrackDisplay: {},
loadingSpinner: {},
bigPlayButton: {},
controlBar: {},
errorDisplay: {},
textTrackSettings: {}
},
language: _globalDocument2['default'].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.'
};
/**
* Fired when the player has initial duration and dimension information
*
* @event loadedmetadata
*/
Player.prototype.handleLoadedMetaData_;
/**
* Fired when the player has downloaded data at the current playback position
*
* @event loadeddata
*/
Player.prototype.handleLoadedData_;
/**
* Fired when the user is active, e.g. moves the mouse over the player
*
* @event useractive
*/
Player.prototype.handleUserActive_;
/**
* Fired when the user is inactive, e.g. a short delay after the last mouse move or control interaction
*
* @event userinactive
*/
Player.prototype.handleUserInactive_;
/**
* Fired when the current playback position has changed *
* During playback this is fired every 15-250 milliseconds, depending on the
* playback technology in use.
*
* @event timeupdate
*/
Player.prototype.handleTimeUpdate_;
/**
* Fired when the volume changes
*
* @event volumechange
*/
Player.prototype.handleVolumeChange_;
/**
* Fired when an error occurs
*
* @event error
*/
Player.prototype.handleError_;
Player.prototype.flexNotSupported_ = function () {
var elem = _globalDocument2['default'].createElement('i');
// Note: We don't actually use flexBasis (or flexOrder), but it's one of the more
// common flex features that we can rely on when checking for flex support.
return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || 'msFlexOrder' in elem.style) /* IE10-specific (2012 flex spec) */;
};
_componentJs2['default'].registerComponent('Player', Player);
exports['default'] = Player;
module.exports = exports['default'];
// If empty string, make it a parsable json object.
},{"./big-play-button.js":56,"./component.js":58,"./control-bar/control-bar.js":59,"./error-display.js":89,"./fullscreen-api.js":92,"./loading-spinner.js":93,"./media-error.js":94,"./poster-image.js":100,"./tech/html5.js":105,"./tech/loader.js":106,"./tracks/text-track-display.js":109,"./tracks/text-track-list-converter.js":111,"./tracks/text-track-settings.js":113,"./utils/browser.js":115,"./utils/buffer.js":116,"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"./utils/guid.js":122,"./utils/log.js":123,"./utils/merge-options.js":124,"./utils/stylesheet.js":125,"./utils/time-ranges.js":126,"./utils/to-title-case.js":127,"global/document":1,"global/window":2,"object.assign":43,"safe-json-parse/tuple":48}],99:[function(_dereq_,module,exports){
/**
* @file plugins.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _playerJs = _dereq_('./player.js');
var _playerJs2 = _interopRequireDefault(_playerJs);
/**
* 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
* @method plugin
*/
var plugin = function plugin(name, init) {
_playerJs2['default'].prototype[name] = init;
};
exports['default'] = plugin;
module.exports = exports['default'];
},{"./player.js":98}],100:[function(_dereq_,module,exports){
/**
* @file poster-image.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('./button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('./component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsBrowserJs = _dereq_('./utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
/**
* The component that handles showing the poster image.
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class PosterImage
*/
var PosterImage = (function (_Button) {
_inherits(PosterImage, _Button);
function PosterImage(player, options) {
_classCallCheck(this, PosterImage);
_Button.call(this, player, options);
this.update();
player.on('posterchange', Fn.bind(this, this.update));
}
/**
* Clean up the poster image
*
* @method dispose
*/
PosterImage.prototype.dispose = function dispose() {
this.player().off('posterchange', this.update);
_Button.prototype.dispose.call(this);
};
/**
* Create the poster's image element
*
* @return {Element}
* @method createEl
*/
PosterImage.prototype.createEl = function createEl() {
var el = Dom.createEl('div', {
className: 'vjs-poster',
// Don't want poster to be tabbable.
tabIndex: -1
});
// 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 (!browser.BACKGROUND_SIZE_SUPPORTED) {
this.fallbackImg_ = Dom.createEl('img');
el.appendChild(this.fallbackImg_);
}
return el;
};
/**
* Event handler for updates to the player's poster source
*
* @method update
*/
PosterImage.prototype.update = function update() {
var url = this.player().poster();
this.setSrc(url);
// If there's no poster source we should display:none on this component
// so it's not still clickable or right-clickable
if (url) {
this.show();
} else {
this.hide();
}
};
/**
* Set the poster source depending on the display method
*
* @param {String} url The URL to the poster source
* @method setSrc
*/
PosterImage.prototype.setSrc = function setSrc(url) {
if (this.fallbackImg_) {
this.fallbackImg_.src = url;
} else {
var backgroundImage = '';
// Any falsey values should stay as an empty string, otherwise
// this will throw an extra error
if (url) {
backgroundImage = 'url("' + url + '")';
}
this.el_.style.backgroundImage = backgroundImage;
}
};
/**
* Event handler for clicks on the poster image
*
* @method handleClick
*/
PosterImage.prototype.handleClick = function handleClick() {
// We don't want a click to trigger playback when controls are disabled
// but CSS should be hiding the poster to prevent that from happening
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
};
return PosterImage;
})(_buttonJs2['default']);
_componentJs2['default'].registerComponent('PosterImage', PosterImage);
exports['default'] = PosterImage;
module.exports = exports['default'];
},{"./button.js":57,"./component.js":58,"./utils/browser.js":115,"./utils/dom.js":118,"./utils/fn.js":120}],101:[function(_dereq_,module,exports){
/**
* @file setup.js
*
* Functions for automatically setting up a player
* based on the data-setup attribute of the video tag
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _windowLoaded = false;
var videojs = undefined;
// Automatically set up any tags that have a data-setup attribute
var autoSetup = function autoSetup() {
// One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack*
// var vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
// var audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
// var mediaEls = vids.concat(audios);
// Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements
// to build up a new, combined list of elements.
var vids = _globalDocument2['default'].getElementsByTagName('video');
var audios = _globalDocument2['default'].getElementsByTagName('audio');
var mediaEls = [];
if (vids && vids.length > 0) {
for (var i = 0, e = vids.length; i < e; i++) {
mediaEls.push(vids[i]);
}
}
if (audios && audios.length > 0) {
for (var i = 0, e = audios.length; i < e; i++) {
mediaEls.push(audios[i]);
}
}
// Check if any media elements exist
if (mediaEls && mediaEls.length > 0) {
for (var i = 0, e = mediaEls.length; i < e; i++) {
var mediaEl = mediaEls[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 (mediaEl && mediaEl.getAttribute) {
// Make sure this player hasn't already been set up.
if (mediaEl['player'] === undefined) {
var options = mediaEl.getAttribute('data-setup');
// Check if data-setup attr exists.
// We only auto-setup if they've added the data-setup attr.
if (options !== null) {
// Create new video.js instance.
var player = videojs(mediaEl);
}
}
// If getAttribute isn't defined, we need to wait for the DOM.
} else {
autoSetupTimeout(1);
break;
}
}
// No videos were found, so keep looping unless page is finished loading.
} else if (!_windowLoaded) {
autoSetupTimeout(1);
}
};
// Pause to let the DOM keep processing
var autoSetupTimeout = function autoSetupTimeout(wait, vjs) {
videojs = vjs;
setTimeout(autoSetup, wait);
};
if (_globalDocument2['default'].readyState === 'complete') {
_windowLoaded = true;
} else {
Events.one(_globalWindow2['default'], 'load', function () {
_windowLoaded = true;
});
}
var hasLoaded = function hasLoaded() {
return _windowLoaded;
};
exports.autoSetup = autoSetup;
exports.autoSetupTimeout = autoSetupTimeout;
exports.hasLoaded = hasLoaded;
},{"./utils/events.js":119,"global/document":1,"global/window":2}],102:[function(_dereq_,module,exports){
/**
* @file slider.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* The base functionality for sliders like the volume bar and seek bar
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class Slider
*/
var Slider = (function (_Component) {
_inherits(Slider, _Component);
function Slider(player, options) {
_classCallCheck(this, Slider);
_Component.call(this, player, options);
// Set property names to bar to match with the child Slider class is looking for
this.bar = this.getChild(this.options_.barName);
// Set a horizontal or vertical class on the slider depending on the slider type
this.vertical(!!this.options_.vertical);
this.on('mousedown', this.handleMouseDown);
this.on('touchstart', this.handleMouseDown);
this.on('focus', this.handleFocus);
this.on('blur', this.handleBlur);
this.on('click', this.handleClick);
this.on(player, 'controlsvisible', this.update);
this.on(player, this.playerEvent, this.update);
}
/**
* Create the component's DOM element
*
* @param {String} type Type of element to create
* @param {Object=} props List of properties in Object form
* @return {Element}
* @method createEl
*/
Slider.prototype.createEl = function createEl(type) {
var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
// Add the slider element class to all sub classes
props.className = props.className + ' vjs-slider';
props = _objectAssign2['default']({
tabIndex: 0
}, props);
attributes = _objectAssign2['default']({
'role': 'slider',
'aria-valuenow': 0,
'aria-valuemin': 0,
'aria-valuemax': 100,
tabIndex: 0
}, attributes);
return _Component.prototype.createEl.call(this, type, props, attributes);
};
/**
* Handle mouse down on slider
*
* @param {Object} event Mouse down event object
* @method handleMouseDown
*/
Slider.prototype.handleMouseDown = function handleMouseDown(event) {
event.preventDefault();
Dom.blockTextSelection();
this.addClass('vjs-sliding');
this.trigger('slideractive');
this.on(_globalDocument2['default'], 'mousemove', this.handleMouseMove);
this.on(_globalDocument2['default'], 'mouseup', this.handleMouseUp);
this.on(_globalDocument2['default'], 'touchmove', this.handleMouseMove);
this.on(_globalDocument2['default'], 'touchend', this.handleMouseUp);
this.handleMouseMove(event);
};
/**
* To be overridden by a subclass
*
* @method handleMouseMove
*/
Slider.prototype.handleMouseMove = function handleMouseMove() {};
/**
* Handle mouse up on Slider
*
* @method handleMouseUp
*/
Slider.prototype.handleMouseUp = function handleMouseUp() {
Dom.unblockTextSelection();
this.removeClass('vjs-sliding');
this.trigger('sliderinactive');
this.off(_globalDocument2['default'], 'mousemove', this.handleMouseMove);
this.off(_globalDocument2['default'], 'mouseup', this.handleMouseUp);
this.off(_globalDocument2['default'], 'touchmove', this.handleMouseMove);
this.off(_globalDocument2['default'], 'touchend', this.handleMouseUp);
this.update();
};
/**
* Update slider
*
* @method update
*/
Slider.prototype.update = function update() {
// 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 progress = this.getPercent();
var bar = this.bar;
// If there's no bar...
if (!bar) return;
// Protect against no duration and other division issues
if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) {
progress = 0;
}
// Convert to a percentage for setting
var percentage = (progress * 100).toFixed(2) + '%';
// Set the new bar width or height
if (this.vertical()) {
bar.el().style.height = percentage;
} else {
bar.el().style.width = percentage;
}
};
/**
* Calculate distance for slider
*
* @param {Object} event Event object
* @method calculateDistance
*/
Slider.prototype.calculateDistance = function calculateDistance(event) {
var position = Dom.getPointerPosition(this.el_, event);
if (this.vertical()) {
return position.y;
}
return position.x;
};
/**
* Handle on focus for slider
*
* @method handleFocus
*/
Slider.prototype.handleFocus = function handleFocus() {
this.on(_globalDocument2['default'], 'keydown', this.handleKeyPress);
};
/**
* Handle key press for slider
*
* @param {Object} event Event object
* @method handleKeyPress
*/
Slider.prototype.handleKeyPress = function handleKeyPress(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();
}
};
/**
* Handle on blur for slider
*
* @method handleBlur
*/
Slider.prototype.handleBlur = function handleBlur() {
this.off(_globalDocument2['default'], 'keydown', this.handleKeyPress);
};
/**
* Listener for click events on slider, used to prevent clicks
* from bubbling up to parent elements like button menus.
*
* @param {Object} event Event object
* @method handleClick
*/
Slider.prototype.handleClick = function handleClick(event) {
event.stopImmediatePropagation();
event.preventDefault();
};
/**
* Get/set if slider is horizontal for vertical
*
* @param {Boolean} bool True if slider is vertical, false is horizontal
* @return {Boolean} True if slider is vertical, false is horizontal
* @method vertical
*/
Slider.prototype.vertical = function vertical(bool) {
if (bool === undefined) {
return this.vertical_ || false;
}
this.vertical_ = !!bool;
if (this.vertical_) {
this.addClass('vjs-slider-vertical');
} else {
this.addClass('vjs-slider-horizontal');
}
return this;
};
return Slider;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('Slider', Slider);
exports['default'] = Slider;
module.exports = exports['default'];
},{"../component.js":58,"../utils/dom.js":118,"global/document":1,"object.assign":43}],103:[function(_dereq_,module,exports){
/**
* @file flash-rtmp.js
*/
'use strict';
exports.__esModule = true;
function FlashRtmpDecorator(Flash) {
Flash.streamingFormats = {
'rtmp/mp4': 'MP4',
'rtmp/flv': 'FLV'
};
Flash.streamFromParts = function (connection, stream) {
return connection + '&' + stream;
};
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 = undefined;
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;
};
Flash.isStreamingType = function (srcType) {
return srcType in Flash.streamingFormats;
};
// RTMP has four variations, any string starting
// with one of these protocols should be valid
Flash.RTMP_RE = /^rtmp[set]?:\/\//i;
Flash.isStreamingSrc = function (src) {
return Flash.RTMP_RE.test(src);
};
/**
* A source handler for RTMP urls
* @type {Object}
*/
Flash.rtmpSourceHandler = {};
/**
* Check Flash can handle the source natively
* @param {Object} source The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Flash.rtmpSourceHandler.canHandleSource = function (source) {
if (Flash.isStreamingType(source.type) || Flash.isStreamingSrc(source.src)) {
return 'maybe';
}
return '';
};
/**
* Pass the source to the flash object
* Adaptive source handlers will have more complicated workflows before passing
* video data to the video element
* @param {Object} source The source object
* @param {Flash} tech The instance of the Flash tech
*/
Flash.rtmpSourceHandler.handleSource = function (source, tech) {
var srcParts = Flash.streamToParts(source.src);
tech['setRtmpConnection'](srcParts.connection);
tech['setRtmpStream'](srcParts.stream);
};
// Register the native source handler
Flash.registerSourceHandler(Flash.rtmpSourceHandler);
return Flash;
}
exports['default'] = FlashRtmpDecorator;
module.exports = exports['default'];
},{}],104:[function(_dereq_,module,exports){
/**
* @file flash.js
* 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
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _tech = _dereq_('./tech');
var _tech2 = _interopRequireDefault(_tech);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsUrlJs = _dereq_('../utils/url.js');
var Url = _interopRequireWildcard(_utilsUrlJs);
var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js');
var _flashRtmp = _dereq_('./flash-rtmp');
var _flashRtmp2 = _interopRequireDefault(_flashRtmp);
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var navigator = _globalWindow2['default'].navigator;
/**
* Flash Media Controller - Wrapper for fallback SWF API
*
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Tech
* @class Flash
*/
var Flash = (function (_Tech) {
_inherits(Flash, _Tech);
function Flash(options, ready) {
_classCallCheck(this, Flash);
_Tech.call(this, options, ready);
// Set the source when ready
if (options.source) {
this.ready(function () {
this.setSource(options.source);
}, true);
}
// 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);
}, true);
}
// Add global window functions that the swf expects
// A 4.x workflow we weren't able to solve for in 5.0
// because of the need to hard code these functions
// into the swf for security reasons
_globalWindow2['default'].videojs = _globalWindow2['default'].videojs || {};
_globalWindow2['default'].videojs.Flash = _globalWindow2['default'].videojs.Flash || {};
_globalWindow2['default'].videojs.Flash.onReady = Flash.onReady;
_globalWindow2['default'].videojs.Flash.onEvent = Flash.onEvent;
_globalWindow2['default'].videojs.Flash.onError = Flash.onError;
this.on('seeked', function () {
this.lastSeekTarget_ = undefined;
});
}
// Create setters and getters for attributes
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Flash.prototype.createEl = function createEl() {
var options = this.options_;
// If video.js is hosted locally you should also set the location
// for the hosted swf, which should be relative to the page (not video.js)
// Otherwise this adds a CDN url.
// The CDN also auto-adds a swf URL for that specific version.
if (!options.swf) {
options.swf = '//vjs.zencdn.net/swf/5.0.0-rc1/video-js.swf';
}
// Generate ID for swf object
var objId = options.techId;
// Merge default flashvars with ones passed in to init
var flashVars = _objectAssign2['default']({
// SWF Callback Functions
'readyFunction': 'videojs.Flash.onReady',
'eventProxyFunction': 'videojs.Flash.onEvent',
'errorEventProxyFunction': 'videojs.Flash.onError',
// Player Settings
'autoplay': options.autoplay,
'preload': options.preload,
'loop': options.loop,
'muted': options.muted
}, options.flashVars);
// Merge default parames with ones passed in
var params = _objectAssign2['default']({
'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
var attributes = _objectAssign2['default']({
'id': objId,
'name': objId, // Both ID and Name needed or swf to identify itself
'class': 'vjs-tech'
}, options.attributes);
this.el_ = Flash.embed(options.swf, flashVars, params, attributes);
this.el_.tech = this;
return this.el_;
};
/**
* Play for flash tech
*
* @method play
*/
Flash.prototype.play = function play() {
if (this.ended()) {
this.setCurrentTime(0);
}
this.el_.vjs_play();
};
/**
* Pause for flash tech
*
* @method pause
*/
Flash.prototype.pause = function pause() {
this.el_.vjs_pause();
};
/**
* Get/set video
*
* @param {Object=} src Source object
* @return {Object}
* @method src
*/
Flash.prototype.src = function src(_src) {
if (_src === undefined) {
return this.currentSrc();
}
// Setting src through `src` not `setSrc` will be deprecated
return this.setSrc(_src);
};
/**
* Set video
*
* @param {Object=} src Source object
* @deprecated
* @method setSrc
*/
Flash.prototype.setSrc = function setSrc(src) {
// Make sure source URL is absolute.
src = Url.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.autoplay()) {
var tech = this;
this.setTimeout(function () {
tech.play();
}, 0);
}
};
/**
* Returns true if the tech is currently seeking.
* @return {boolean} true if seeking
*/
Flash.prototype.seeking = function seeking() {
return this.lastSeekTarget_ !== undefined;
};
/**
* Set current time
*
* @param {Number} time Current time of video
* @method setCurrentTime
*/
Flash.prototype.setCurrentTime = function setCurrentTime(time) {
var seekable = this.seekable();
if (seekable.length) {
// clamp to the current seekable range
time = time > seekable.start(0) ? time : seekable.start(0);
time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1);
this.lastSeekTarget_ = time;
this.trigger('seeking');
this.el_.vjs_setProperty('currentTime', time);
_Tech.prototype.setCurrentTime.call(this);
}
};
/**
* Get current time
*
* @param {Number=} time Current time of video
* @return {Number} Current time
* @method currentTime
*/
Flash.prototype.currentTime = function currentTime(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');
};
/**
* Get current source
*
* @method currentSrc
*/
Flash.prototype.currentSrc = function currentSrc() {
if (this.currentSource_) {
return this.currentSource_.src;
} else {
return this.el_.vjs_getProperty('currentSrc');
}
};
/**
* Load media into player
*
* @method load
*/
Flash.prototype.load = function load() {
this.el_.vjs_load();
};
/**
* Get poster
*
* @method poster
*/
Flash.prototype.poster = function poster() {
this.el_.vjs_getProperty('poster');
};
/**
* Poster images are not handled by the Flash tech so make this a no-op
*
* @method setPoster
*/
Flash.prototype.setPoster = function setPoster() {};
/**
* Determine if can seek in media
*
* @return {TimeRangeObject}
* @method seekable
*/
Flash.prototype.seekable = function seekable() {
var duration = this.duration();
if (duration === 0) {
return _utilsTimeRangesJs.createTimeRange();
}
return _utilsTimeRangesJs.createTimeRange(0, duration);
};
/**
* Get buffered time range
*
* @return {TimeRangeObject}
* @method buffered
*/
Flash.prototype.buffered = function buffered() {
var ranges = this.el_.vjs_getProperty('buffered');
if (ranges.length === 0) {
return _utilsTimeRangesJs.createTimeRange();
}
return _utilsTimeRangesJs.createTimeRange(ranges[0][0], ranges[0][1]);
};
/**
* Get fullscreen support -
* Flash does not allow fullscreen through javascript
* so always returns false
*
* @return {Boolean} false
* @method supportsFullScreen
*/
Flash.prototype.supportsFullScreen = function supportsFullScreen() {
return false; // Flash does not allow fullscreen through javascript
};
/**
* Request to enter fullscreen
* Flash does not allow fullscreen through javascript
* so always returns false
*
* @return {Boolean} false
* @method enterFullScreen
*/
Flash.prototype.enterFullScreen = function enterFullScreen() {
return false;
};
return Flash;
})(_tech2['default']);
var _api = Flash.prototype;
var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(',');
var _readOnly = 'networkState,readyState,initialTime,duration,startOffsetTime,paused,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(',');
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 (var i = 0; i < _readWrite.length; i++) {
_createGetter(_readWrite[i]);
_createSetter(_readWrite[i]);
}
// Create getters for read-only attributes
for (var i = 0; i < _readOnly.length; i++) {
_createGetter(_readOnly[i]);
}
/* Flash Support Testing -------------------------------------------------------- */
Flash.isSupported = function () {
return Flash.version()[0] >= 10;
// return swfobject.hasFlashPlayerVersion('10');
};
// Add Source Handler pattern functions to this tech
_tech2['default'].withSourceHandlers(Flash);
/*
* The default native source handler.
* This simply passes the source to the video element. Nothing fancy.
*
* @param {Object} source The source object
* @param {Flash} tech The instance of the Flash tech
*/
Flash.nativeSourceHandler = {};
/*
* Check Flash can handle the source natively
*
* @param {Object} source The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Flash.nativeSourceHandler.canHandleSource = function (source) {
var type;
function guessMimeType(src) {
var ext = Url.getFileExtension(src);
if (ext) {
return 'video/' + ext;
}
return '';
}
if (!source.type) {
type = guessMimeType(source.src);
} else {
// Strip code information from the type because we don't get that specific
type = source.type.replace(/;.*/, '').toLowerCase();
}
if (type in Flash.formats) {
return 'maybe';
}
return '';
};
/*
* Pass the source to the flash object
* Adaptive source handlers will have more complicated workflows before passing
* video data to the video element
*
* @param {Object} source The source object
* @param {Flash} tech The instance of the Flash tech
*/
Flash.nativeSourceHandler.handleSource = function (source, tech) {
tech.setSrc(source.src);
};
/*
* Clean up the source handler when disposing the player or switching sources..
* (no cleanup is needed when supporting the format natively)
*/
Flash.nativeSourceHandler.dispose = function () {};
// Register the native source handler
Flash.registerSourceHandler(Flash.nativeSourceHandler);
Flash.formats = {
'video/flv': 'FLV',
'video/x-flv': 'FLV',
'video/mp4': 'MP4',
'video/m4v': 'MP4'
};
Flash.onReady = function (currSwf) {
var el = Dom.getEl(currSwf);
var tech = el && el.tech;
// if there is no el then the tech has been disposed
// and the tech element was removed from the player div
if (tech && tech.el()) {
// check that the flash object is really ready
Flash.checkReady(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.
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
this.setTimeout(function () {
Flash['checkReady'](tech);
}, 50);
}
};
// Trigger events from the swf on the player
Flash.onEvent = function (swfID, eventName) {
var tech = Dom.getEl(swfID).tech;
tech.trigger(eventName);
};
// Log errors from the swf
Flash.onError = function (swfID, err) {
var tech = Dom.getEl(swfID).tech;
// trigger MEDIA_ERR_SRC_NOT_SUPPORTED
if (err === 'srcnotfound') {
return tech.error(4);
}
// trigger a custom error
tech.error('FLASH: ' + err);
};
// Flash Version Check
Flash.version = function () {
var version = '0,0,0';
// IE
try {
version = new _globalWindow2['default'].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
Flash.embed = function (swf, flashVars, params, attributes) {
var code = Flash.getEmbedCode(swf, flashVars, params, attributes);
// Get element by embedding code and retrieving created element
var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0];
return obj;
};
Flash.getEmbedCode = function (swf, flashVars, params, attributes) {
var objTag = '<object type="application/x-shockwave-flash" ';
var flashVarsString = '';
var paramsString = '';
var attrsString = '';
// Convert flash vars to string
if (flashVars) {
Object.getOwnPropertyNames(flashVars).forEach(function (key) {
flashVarsString += key + '=' + flashVars[key] + '&';
});
}
// Add swf, flashVars, and other default params
params = _objectAssign2['default']({
'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
Object.getOwnPropertyNames(params).forEach(function (key) {
paramsString += '<param name="' + key + '" value="' + params[key] + '" />';
});
attributes = _objectAssign2['default']({
// 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
Object.getOwnPropertyNames(attributes).forEach(function (key) {
attrsString += key + '="' + attributes[key] + '" ';
});
return '' + objTag + attrsString + '>' + paramsString + '</object>';
};
// Run Flash through the RTMP decorator
_flashRtmp2['default'](Flash);
_component2['default'].registerComponent('Flash', Flash);
exports['default'] = Flash;
module.exports = exports['default'];
},{"../component":58,"../utils/dom.js":118,"../utils/time-ranges.js":126,"../utils/url.js":128,"./flash-rtmp":103,"./tech":107,"global/window":2,"object.assign":43}],105:[function(_dereq_,module,exports){
/**
* @file html5.js
* HTML5 Media Controller - Wrapper for HTML5 Media API
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _techJs = _dereq_('./tech.js');
var _techJs2 = _interopRequireDefault(_techJs);
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsUrlJs = _dereq_('../utils/url.js');
var Url = _interopRequireWildcard(_utilsUrlJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsMergeOptionsJs = _dereq_('../utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
/**
* HTML5 Media Controller - Wrapper for HTML5 Media API
*
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Tech
* @class Html5
*/
var Html5 = (function (_Tech) {
_inherits(Html5, _Tech);
function Html5(options, ready) {
_classCallCheck(this, Html5);
_Tech.call(this, options, ready);
var source = options.source;
// Set the source if one is provided
// 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
// 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
// anyway so the error gets fired.
if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
this.setSource(source);
} else {
this.handleLateInit_(this.el_);
}
if (this.el_.hasChildNodes()) {
var nodes = this.el_.childNodes;
var nodesLength = nodes.length;
var removeNodes = [];
while (nodesLength--) {
var node = nodes[nodesLength];
var nodeName = node.nodeName.toLowerCase();
if (nodeName === 'track') {
if (!this.featuresNativeTextTracks) {
// 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
removeNodes.push(node);
} else {
this.remoteTextTracks().addTrack_(node.track);
}
}
}
for (var i = 0; i < removeNodes.length; i++) {
this.el_.removeChild(removeNodes[i]);
}
}
if (this.featuresNativeTextTracks) {
this.handleTextTrackChange_ = Fn.bind(this, this.handleTextTrackChange);
this.handleTextTrackAdd_ = Fn.bind(this, this.handleTextTrackAdd);
this.handleTextTrackRemove_ = Fn.bind(this, this.handleTextTrackRemove);
this.proxyNativeTextTracks_();
}
// 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 (browser.TOUCH_ENABLED && options.nativeControlsForTouch === true || browser.IS_IPHONE || browser.IS_NATIVE_ANDROID) {
this.setControls(true);
}
this.triggerReady();
}
/* HTML5 Support Testing ---------------------------------------------------- */
/*
* Element for testing browser HTML5 video capabilities
*
* @type {Element}
* @constant
* @private
*/
/**
* Dispose of html5 media element
*
* @method dispose
*/
Html5.prototype.dispose = function dispose() {
var tt = this.el().textTracks;
var emulatedTt = this.textTracks();
// remove native event listeners
if (tt && tt.removeEventListener) {
tt.removeEventListener('change', this.handleTextTrackChange_);
tt.removeEventListener('addtrack', this.handleTextTrackAdd_);
tt.removeEventListener('removetrack', this.handleTextTrackRemove_);
}
// clearout the emulated text track list.
var i = emulatedTt.length;
while (i--) {
emulatedTt.removeTrack_(emulatedTt[i]);
}
Html5.disposeMediaElement(this.el_);
_Tech.prototype.dispose.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Html5.prototype.createEl = function createEl() {
var el = this.options_.tag;
// 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) {
var clone = el.cloneNode(true);
el.parentNode.insertBefore(clone, el);
Html5.disposeMediaElement(el);
el = clone;
} else {
el = _globalDocument2['default'].createElement('video');
// determine if native controls should be used
var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag);
var attributes = _utilsMergeOptionsJs2['default']({}, tagAttributes);
if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
delete attributes.controls;
}
Dom.setElAttributes(el, _objectAssign2['default'](attributes, {
id: this.options_.techId,
'class': 'vjs-tech'
}));
}
}
// 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 this.options_[attr] !== 'undefined') {
overwriteAttrs[attr] = this.options_[attr];
}
Dom.setElAttributes(el, overwriteAttrs);
}
return el;
// jenniisawesome = true;
};
// 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.
Html5.prototype.handleLateInit_ = function handleLateInit_(el) {
var _this = this;
if (el.networkState === 0 || el.networkState === 3) {
// The video element hasn't started loading the source yet
// or didn't find a source
return;
}
if (el.readyState === 0) {
var _ret = (function () {
// NetworkState is set synchronously BUT loadstart is fired at the
// end of the current stack, usually before setInterval(fn, 0).
// So at this point we know loadstart may have already fired or is
// about to fire, and either way the player hasn't seen it yet.
// We don't want to fire loadstart prematurely here and cause a
// double loadstart so we'll wait and see if it happens between now
// and the next loop, and fire it if not.
// HOWEVER, we also want to make sure it fires before loadedmetadata
// which could also happen between now and the next loop, so we'll
// watch for that also.
var loadstartFired = false;
var setLoadstartFired = function setLoadstartFired() {
loadstartFired = true;
};
_this.on('loadstart', setLoadstartFired);
var triggerLoadstart = function triggerLoadstart() {
// We did miss the original loadstart. Make sure the player
// sees loadstart before loadedmetadata
if (!loadstartFired) {
this.trigger('loadstart');
}
};
_this.on('loadedmetadata', triggerLoadstart);
_this.ready(function () {
this.off('loadstart', setLoadstartFired);
this.off('loadedmetadata', triggerLoadstart);
if (!loadstartFired) {
// We did miss the original native loadstart. Fire it now.
this.trigger('loadstart');
}
});
return {
v: undefined
};
})();
if (typeof _ret === 'object') return _ret.v;
}
// From here on we know that loadstart already fired and we missed it.
// The other readyState events aren't as much of a problem if we double
// them, so not going to go to as much trouble as loadstart to prevent
// that unless we find reason to.
var eventsToTrigger = ['loadstart'];
// loadedmetadata: newly equal to HAVE_METADATA (1) or greater
eventsToTrigger.push('loadedmetadata');
// loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
if (el.readyState >= 2) {
eventsToTrigger.push('loadeddata');
}
// canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
if (el.readyState >= 3) {
eventsToTrigger.push('canplay');
}
// canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
if (el.readyState >= 4) {
eventsToTrigger.push('canplaythrough');
}
// We still need to give the player time to add event listeners
this.ready(function () {
eventsToTrigger.forEach(function (type) {
this.trigger(type);
}, this);
});
};
Html5.prototype.proxyNativeTextTracks_ = function proxyNativeTextTracks_() {
var tt = this.el().textTracks;
if (tt && tt.addEventListener) {
tt.addEventListener('change', this.handleTextTrackChange_);
tt.addEventListener('addtrack', this.handleTextTrackAdd_);
tt.addEventListener('removetrack', this.handleTextTrackRemove_);
}
};
Html5.prototype.handleTextTrackChange = function handleTextTrackChange(e) {
var tt = this.textTracks();
this.textTracks().trigger({
type: 'change',
target: tt,
currentTarget: tt,
srcElement: tt
});
};
Html5.prototype.handleTextTrackAdd = function handleTextTrackAdd(e) {
this.textTracks().addTrack_(e.track);
};
Html5.prototype.handleTextTrackRemove = function handleTextTrackRemove(e) {
this.textTracks().removeTrack_(e.track);
};
/**
* Play for html5 tech
*
* @method play
*/
Html5.prototype.play = function play() {
this.el_.play();
};
/**
* Pause for html5 tech
*
* @method pause
*/
Html5.prototype.pause = function pause() {
this.el_.pause();
};
/**
* Paused for html5 tech
*
* @return {Boolean}
* @method paused
*/
Html5.prototype.paused = function paused() {
return this.el_.paused;
};
/**
* Get current time
*
* @return {Number}
* @method currentTime
*/
Html5.prototype.currentTime = function currentTime() {
return this.el_.currentTime;
};
/**
* Set current time
*
* @param {Number} seconds Current time of video
* @method setCurrentTime
*/
Html5.prototype.setCurrentTime = function setCurrentTime(seconds) {
try {
this.el_.currentTime = seconds;
} catch (e) {
_utilsLogJs2['default'](e, 'Video is not ready. (Video.js)');
// this.warning(VideoJS.warnings.videoNotReady);
}
};
/**
* Get duration
*
* @return {Number}
* @method duration
*/
Html5.prototype.duration = function duration() {
return this.el_.duration || 0;
};
/**
* Get a TimeRange object that represents the intersection
* of the time ranges for which the user agent has all
* relevant media
*
* @return {TimeRangeObject}
* @method buffered
*/
Html5.prototype.buffered = function buffered() {
return this.el_.buffered;
};
/**
* Get volume level
*
* @return {Number}
* @method volume
*/
Html5.prototype.volume = function volume() {
return this.el_.volume;
};
/**
* Set volume level
*
* @param {Number} percentAsDecimal Volume percent as a decimal
* @method setVolume
*/
Html5.prototype.setVolume = function setVolume(percentAsDecimal) {
this.el_.volume = percentAsDecimal;
};
/**
* Get if muted
*
* @return {Boolean}
* @method muted
*/
Html5.prototype.muted = function muted() {
return this.el_.muted;
};
/**
* Set muted
*
* @param {Boolean} If player is to be muted or note
* @method setMuted
*/
Html5.prototype.setMuted = function setMuted(muted) {
this.el_.muted = muted;
};
/**
* Get player width
*
* @return {Number}
* @method width
*/
Html5.prototype.width = function width() {
return this.el_.offsetWidth;
};
/**
* Get player height
*
* @return {Number}
* @method height
*/
Html5.prototype.height = function height() {
return this.el_.offsetHeight;
};
/**
* Get if there is fullscreen support
*
* @return {Boolean}
* @method supportsFullScreen
*/
Html5.prototype.supportsFullScreen = function supportsFullScreen() {
if (typeof this.el_.webkitEnterFullScreen === 'function') {
var userAgent = _globalWindow2['default'].navigator.userAgent;
// Seems to be broken in Chromium/Chrome && Safari in Leopard
if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) {
return true;
}
}
return false;
};
/**
* Request to enter fullscreen
*
* @method enterFullScreen
*/
Html5.prototype.enterFullScreen = function enterFullScreen() {
var video = this.el_;
if ('webkitDisplayingFullscreen' in video) {
this.one('webkitbeginfullscreen', function () {
this.one('webkitendfullscreen', function () {
this.trigger('fullscreenchange', { isFullscreen: false });
});
this.trigger('fullscreenchange', { isFullscreen: true });
});
}
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
this.setTimeout(function () {
video.pause();
video.webkitEnterFullScreen();
}, 0);
} else {
video.webkitEnterFullScreen();
}
};
/**
* Request to exit fullscreen
*
* @method exitFullScreen
*/
Html5.prototype.exitFullScreen = function exitFullScreen() {
this.el_.webkitExitFullScreen();
};
/**
* Get/set video
*
* @param {Object=} src Source object
* @return {Object}
* @method src
*/
Html5.prototype.src = function src(_src) {
if (_src === undefined) {
return this.el_.src;
} else {
// Setting src through `src` instead of `setSrc` will be deprecated
this.setSrc(_src);
}
};
/**
* Set video
*
* @param {Object} src Source object
* @deprecated
* @method setSrc
*/
Html5.prototype.setSrc = function setSrc(src) {
this.el_.src = src;
};
/**
* Load media into player
*
* @method load
*/
Html5.prototype.load = function load() {
this.el_.load();
};
/**
* Get current source
*
* @return {Object}
* @method currentSrc
*/
Html5.prototype.currentSrc = function currentSrc() {
return this.el_.currentSrc;
};
/**
* Get poster
*
* @return {String}
* @method poster
*/
Html5.prototype.poster = function poster() {
return this.el_.poster;
};
/**
* Set poster
*
* @param {String} val URL to poster image
* @method
*/
Html5.prototype.setPoster = function setPoster(val) {
this.el_.poster = val;
};
/**
* Get preload attribute
*
* @return {String}
* @method preload
*/
Html5.prototype.preload = function preload() {
return this.el_.preload;
};
/**
* Set preload attribute
*
* @param {String} val Value for preload attribute
* @method setPreload
*/
Html5.prototype.setPreload = function setPreload(val) {
this.el_.preload = val;
};
/**
* Get autoplay attribute
*
* @return {String}
* @method autoplay
*/
Html5.prototype.autoplay = function autoplay() {
return this.el_.autoplay;
};
/**
* Set autoplay attribute
*
* @param {String} val Value for preload attribute
* @method setAutoplay
*/
Html5.prototype.setAutoplay = function setAutoplay(val) {
this.el_.autoplay = val;
};
/**
* Get controls attribute
*
* @return {String}
* @method controls
*/
Html5.prototype.controls = function controls() {
return this.el_.controls;
};
/**
* Set controls attribute
*
* @param {String} val Value for controls attribute
* @method setControls
*/
Html5.prototype.setControls = function setControls(val) {
this.el_.controls = !!val;
};
/**
* Get loop attribute
*
* @return {String}
* @method loop
*/
Html5.prototype.loop = function loop() {
return this.el_.loop;
};
/**
* Set loop attribute
*
* @param {String} val Value for loop attribute
* @method setLoop
*/
Html5.prototype.setLoop = function setLoop(val) {
this.el_.loop = val;
};
/**
* Get error value
*
* @return {String}
* @method error
*/
Html5.prototype.error = function error() {
return this.el_.error;
};
/**
* Get whether or not the player is in the "seeking" state
*
* @return {Boolean}
* @method seeking
*/
Html5.prototype.seeking = function seeking() {
return this.el_.seeking;
};
/**
* Get a TimeRanges object that represents the
* ranges of the media resource to which it is possible
* for the user agent to seek.
*
* @return {TimeRangeObject}
* @method seekable
*/
Html5.prototype.seekable = function seekable() {
return this.el_.seekable;
};
/**
* Get if video ended
*
* @return {Boolean}
* @method ended
*/
Html5.prototype.ended = function ended() {
return this.el_.ended;
};
/**
* Get the value of the muted content attribute
* This attribute has no dynamic effect, it only
* controls the default state of the element
*
* @return {Boolean}
* @method defaultMuted
*/
Html5.prototype.defaultMuted = function defaultMuted() {
return this.el_.defaultMuted;
};
/**
* Get desired speed at which the media resource is to play
*
* @return {Number}
* @method playbackRate
*/
Html5.prototype.playbackRate = function playbackRate() {
return this.el_.playbackRate;
};
/**
* Returns a TimeRanges object that represents the ranges of the
* media resource that the user agent has played.
* @return {TimeRangeObject} the range of points on the media
* timeline that has been reached through normal playback
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-played
*/
Html5.prototype.played = function played() {
return this.el_.played;
};
/**
* Set desired speed at which the media resource is to play
*
* @param {Number} val Speed at which the media resource is to play
* @method setPlaybackRate
*/
Html5.prototype.setPlaybackRate = function setPlaybackRate(val) {
this.el_.playbackRate = val;
};
/**
* Get the current state of network activity for the element, from
* the list below
* NETWORK_EMPTY (numeric value 0)
* NETWORK_IDLE (numeric value 1)
* NETWORK_LOADING (numeric value 2)
* NETWORK_NO_SOURCE (numeric value 3)
*
* @return {Number}
* @method networkState
*/
Html5.prototype.networkState = function networkState() {
return this.el_.networkState;
};
/**
* Get a value that expresses the current state of the element
* with respect to rendering the current playback position, from
* the codes in the list below
* HAVE_NOTHING (numeric value 0)
* HAVE_METADATA (numeric value 1)
* HAVE_CURRENT_DATA (numeric value 2)
* HAVE_FUTURE_DATA (numeric value 3)
* HAVE_ENOUGH_DATA (numeric value 4)
*
* @return {Number}
* @method readyState
*/
Html5.prototype.readyState = function readyState() {
return this.el_.readyState;
};
/**
* Get width of video
*
* @return {Number}
* @method videoWidth
*/
Html5.prototype.videoWidth = function videoWidth() {
return this.el_.videoWidth;
};
/**
* Get height of video
*
* @return {Number}
* @method videoHeight
*/
Html5.prototype.videoHeight = function videoHeight() {
return this.el_.videoHeight;
};
/**
* Get text tracks
*
* @return {TextTrackList}
* @method textTracks
*/
Html5.prototype.textTracks = function textTracks() {
return _Tech.prototype.textTracks.call(this);
};
/**
* Creates and returns a text track object
*
* @param {String} kind Text track kind (subtitles, captions, descriptions
* chapters and metadata)
* @param {String=} label Label to identify the text track
* @param {String=} language Two letter language abbreviation
* @return {TextTrackObject}
* @method addTextTrack
*/
Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) {
if (!this['featuresNativeTextTracks']) {
return _Tech.prototype.addTextTrack.call(this, kind, label, language);
}
return this.el_.addTextTrack(kind, label, language);
};
/**
* Creates and returns a remote text track object
*
* @param {Object} options The object should contain values for
* kind, language, label and src (location of the WebVTT file)
* @return {TextTrackObject}
* @method addRemoteTextTrack
*/
Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (!this['featuresNativeTextTracks']) {
return _Tech.prototype.addRemoteTextTrack.call(this, options);
}
var track = _globalDocument2['default'].createElement('track');
if (options['kind']) {
track['kind'] = options['kind'];
}
if (options['label']) {
track['label'] = options['label'];
}
if (options['language'] || options['srclang']) {
track['srclang'] = options['language'] || options['srclang'];
}
if (options['default']) {
track['default'] = options['default'];
}
if (options['id']) {
track['id'] = options['id'];
}
if (options['src']) {
track['src'] = options['src'];
}
this.el().appendChild(track);
this.remoteTextTracks().addTrack_(track.track);
return track;
};
/**
* Remove remote text track from TextTrackList object
*
* @param {TextTrackObject} track Texttrack object to remove
* @method removeRemoteTextTrack
*/
Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
if (!this['featuresNativeTextTracks']) {
return _Tech.prototype.removeRemoteTextTrack.call(this, track);
}
var tracks, i;
this.remoteTextTracks().removeTrack_(track);
tracks = this.el().querySelectorAll('track');
i = tracks.length;
while (i--) {
if (track === tracks[i] || track === tracks[i].track) {
this.el().removeChild(tracks[i]);
}
}
};
return Html5;
})(_techJs2['default']);
Html5.TEST_VID = _globalDocument2['default'].createElement('video');
var track = _globalDocument2['default'].createElement('track');
track.kind = 'captions';
track.srclang = 'en';
track.label = 'English';
Html5.TEST_VID.appendChild(track);
/*
* Check if HTML5 video is supported by this browser/device
*
* @return {Boolean}
*/
Html5.isSupported = function () {
// IE9 with no Media Player is a LIAR! (#984)
try {
Html5.TEST_VID['volume'] = 0.5;
} catch (e) {
return false;
}
return !!Html5.TEST_VID.canPlayType;
};
// Add Source Handler pattern functions to this tech
_techJs2['default'].withSourceHandlers(Html5);
/*
* The default native source handler.
* This simply passes the source to the video element. Nothing fancy.
*
* @param {Object} source The source object
* @param {Html5} tech The instance of the HTML5 tech
*/
Html5.nativeSourceHandler = {};
/*
* Check if the video element can handle the source natively
*
* @param {Object} source The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
Html5.nativeSourceHandler.canHandleSource = function (source) {
var match, ext;
function canPlayType(type) {
// IE9 on Windows 7 without MediaPlayer throws an error here
// https://github.com/videojs/video.js/issues/519
try {
return Html5.TEST_VID.canPlayType(type);
} catch (e) {
return '';
}
}
// If a type was provided we should rely on that
if (source.type) {
return canPlayType(source.type);
} else if (source.src) {
// If no type, fall back to checking 'video/[EXTENSION]'
ext = Url.getFileExtension(source.src);
return canPlayType('video/' + ext);
}
return '';
};
/*
* Pass the source to the video element
* Adaptive source handlers will have more complicated workflows before passing
* video data to the video element
*
* @param {Object} source The source object
* @param {Html5} tech The instance of the Html5 tech
*/
Html5.nativeSourceHandler.handleSource = function (source, tech) {
tech.setSrc(source.src);
};
/*
* Clean up the source handler when disposing the player or switching sources..
* (no cleanup is needed when supporting the format natively)
*/
Html5.nativeSourceHandler.dispose = function () {};
// Register the native source handler
Html5.registerSourceHandler(Html5.nativeSourceHandler);
/*
* Check if the volume can be changed in this browser/device.
* Volume cannot be changed in a lot of mobile devices.
* Specifically, it can't be changed from 1 on iOS.
*
* @return {Boolean}
*/
Html5.canControlVolume = function () {
var volume = Html5.TEST_VID.volume;
Html5.TEST_VID.volume = volume / 2 + 0.1;
return volume !== Html5.TEST_VID.volume;
};
/*
* Check if playbackRate is supported in this browser/device.
*
* @return {Number} [description]
*/
Html5.canControlPlaybackRate = function () {
var playbackRate = Html5.TEST_VID.playbackRate;
Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
return playbackRate !== Html5.TEST_VID.playbackRate;
};
/*
* Check to see if native text tracks are supported by this browser/device
*
* @return {Boolean}
*/
Html5.supportsNativeTextTracks = function () {
var supportsTextTracks;
// Figure out native text track support
// If mode is a number, we cannot change it because it'll disappear from view.
// Browsers with numeric modes include IE10 and older (<=2013) samsung android models.
// Firefox isn't playing nice either with modifying the mode
// TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862
supportsTextTracks = !!Html5.TEST_VID.textTracks;
if (supportsTextTracks && Html5.TEST_VID.textTracks.length > 0) {
supportsTextTracks = typeof Html5.TEST_VID.textTracks[0]['mode'] !== 'number';
}
if (supportsTextTracks && browser.IS_FIREFOX) {
supportsTextTracks = false;
}
if (supportsTextTracks && !('onremovetrack' in Html5.TEST_VID.textTracks)) {
supportsTextTracks = false;
}
return supportsTextTracks;
};
/**
* An array of events available on the Html5 tech.
*
* @private
* @type {Array}
*/
Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'volumechange'];
/*
* Set the tech's volume control support status
*
* @type {Boolean}
*/
Html5.prototype['featuresVolumeControl'] = Html5.canControlVolume();
/*
* Set the tech's playbackRate support status
*
* @type {Boolean}
*/
Html5.prototype['featuresPlaybackRate'] = Html5.canControlPlaybackRate();
/*
* Set the tech's status on moving the video element.
* In iOS, if you move a video element in the DOM, it breaks video playback.
*
* @type {Boolean}
*/
Html5.prototype['movingMediaElementInDOM'] = !browser.IS_IOS;
/*
* Set the the tech's fullscreen resize support status.
* HTML video is able to automatically resize when going to fullscreen.
* (No longer appears to be used. Can probably be removed.)
*/
Html5.prototype['featuresFullscreenResize'] = true;
/*
* Set the tech's progress event support status
* (this disables the manual progress events of the Tech)
*/
Html5.prototype['featuresProgressEvents'] = true;
/*
* Sets the tech's status on native text track support
*
* @type {Boolean}
*/
Html5.prototype['featuresNativeTextTracks'] = Html5.supportsNativeTextTracks();
// HTML5 Feature detection and Device Fixes --------------------------------- //
var canPlayType = undefined;
var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
var mp4RE = /^video\/mp4/i;
Html5.patchCanPlayType = function () {
// Android 4.0 and above can play HLS to some extent but it reports being unable to do so
if (browser.ANDROID_VERSION >= 4.0) {
if (!canPlayType) {
canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType;
}
Html5.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 (browser.IS_OLD_ANDROID) {
if (!canPlayType) {
canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType;
}
Html5.TEST_VID.constructor.prototype.canPlayType = function (type) {
if (type && mp4RE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
}
};
Html5.unpatchCanPlayType = function () {
var r = Html5.TEST_VID.constructor.prototype.canPlayType;
Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType;
canPlayType = null;
return r;
};
// by default, patch the video element
Html5.patchCanPlayType();
Html5.disposeMediaElement = function (el) {
if (!el) {
return;
}
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
}
})();
}
};
_component2['default'].registerComponent('Html5', Html5);
exports['default'] = Html5;
module.exports = exports['default'];
},{"../component":58,"../utils/browser.js":115,"../utils/dom.js":118,"../utils/fn.js":120,"../utils/log.js":123,"../utils/merge-options.js":124,"../utils/url.js":128,"./tech.js":107,"global/document":1,"global/window":2,"object.assign":43}],106:[function(_dereq_,module,exports){
/**
* @file loader.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
/**
* The Media Loader is the component that decides which playback technology to load
* when the player is initialized.
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Component
* @class MediaLoader
*/
var MediaLoader = (function (_Component) {
_inherits(MediaLoader, _Component);
function MediaLoader(player, options, ready) {
_classCallCheck(this, MediaLoader);
_Component.call(this, player, options, ready);
// If there are no sources when the player is initialized,
// load the first supported playback technology.
if (!options.playerOptions['sources'] || options.playerOptions['sources'].length === 0) {
for (var i = 0, j = options.playerOptions['techOrder']; i < j.length; i++) {
var techName = _utilsToTitleCaseJs2['default'](j[i]);
var tech = _component2['default'].getComponent(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(options.playerOptions['sources']);
}
}
return MediaLoader;
})(_component2['default']);
_component2['default'].registerComponent('MediaLoader', MediaLoader);
exports['default'] = MediaLoader;
module.exports = exports['default'];
},{"../component":58,"../utils/to-title-case.js":127,"global/window":2}],107:[function(_dereq_,module,exports){
/**
* @file tech.js
* Media Technology Controller - Base class for media playback
* technology controllers like Flash and HTML5
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _tracksTextTrack = _dereq_('../tracks/text-track');
var _tracksTextTrack2 = _interopRequireDefault(_tracksTextTrack);
var _tracksTextTrackList = _dereq_('../tracks/text-track-list');
var _tracksTextTrackList2 = _interopRequireDefault(_tracksTextTrackList);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js');
var _utilsBufferJs = _dereq_('../utils/buffer.js');
var _mediaErrorJs = _dereq_('../media-error.js');
var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* Base class for media (HTML5 Video, Flash) controllers
*
* @param {Object=} options Options object
* @param {Function=} ready Ready callback function
* @extends Component
* @class Tech
*/
var Tech = (function (_Component) {
_inherits(Tech, _Component);
function Tech() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var ready = arguments.length <= 1 || arguments[1] === undefined ? function () {} : arguments[1];
_classCallCheck(this, Tech);
// we don't want the tech to report user activity automatically.
// This is done manually in addControlsListeners
options.reportTouchActivity = false;
_Component.call(this, null, options, ready);
// keep track of whether the current source has played at all to
// implement a very limited played()
this.hasStarted_ = false;
this.on('playing', function () {
this.hasStarted_ = true;
});
this.on('loadstart', function () {
this.hasStarted_ = false;
});
this.textTracks_ = options.textTracks;
// Manually track progress in cases where the browser/flash player doesn't report it.
if (!this.featuresProgressEvents) {
this.manualProgressOn();
}
// Manually track timeupdates in cases where the browser/flash player doesn't report it.
if (!this.featuresTimeupdateEvents) {
this.manualTimeUpdatesOn();
}
if (options.nativeCaptions === false || options.nativeTextTracks === false) {
this.featuresNativeTextTracks = false;
}
if (!this.featuresNativeTextTracks) {
this.emulateTextTracks();
}
this.initTextTrackListeners();
// Turn on component tap events
this.emitTapEvents();
}
/*
* List of associated text tracks
*
* @type {Array}
* @private
*/
/* 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
/**
* Turn on progress events
*
* @method manualProgressOn
*/
Tech.prototype.manualProgressOn = function manualProgressOn() {
this.on('durationchange', this.onDurationChange);
this.manualProgress = true;
// Trigger progress watching when a source begins loading
this.one('ready', this.trackProgress);
};
/**
* Turn off progress events
*
* @method manualProgressOff
*/
Tech.prototype.manualProgressOff = function manualProgressOff() {
this.manualProgress = false;
this.stopTrackingProgress();
this.off('durationchange', this.onDurationChange);
};
/**
* Track progress
*
* @method trackProgress
*/
Tech.prototype.trackProgress = function trackProgress() {
this.stopTrackingProgress();
this.progressInterval = this.setInterval(Fn.bind(this, function () {
// Don't trigger unless buffered amount is greater than last time
var numBufferedPercent = this.bufferedPercent();
if (this.bufferedPercent_ !== numBufferedPercent) {
this.trigger('progress');
}
this.bufferedPercent_ = numBufferedPercent;
if (numBufferedPercent === 1) {
this.stopTrackingProgress();
}
}), 500);
};
/**
* Update duration
*
* @method onDurationChange
*/
Tech.prototype.onDurationChange = function onDurationChange() {
this.duration_ = this.duration();
};
/**
* Create and get TimeRange object for buffering
*
* @return {TimeRangeObject}
* @method buffered
*/
Tech.prototype.buffered = function buffered() {
return _utilsTimeRangesJs.createTimeRange(0, 0);
};
/**
* Get buffered percent
*
* @return {Number}
* @method bufferedPercent
*/
Tech.prototype.bufferedPercent = function bufferedPercent() {
return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration_);
};
/**
* Stops tracking progress by clearing progress interval
*
* @method stopTrackingProgress
*/
Tech.prototype.stopTrackingProgress = function stopTrackingProgress() {
this.clearInterval(this.progressInterval);
};
/*! Time Tracking -------------------------------------------------------------- */
/**
* Set event listeners for on play and pause and tracking current time
*
* @method manualTimeUpdatesOn
*/
Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() {
this.manualTimeUpdates = true;
this.on('play', this.trackCurrentTime);
this.on('pause', this.stopTrackingCurrentTime);
};
/**
* Remove event listeners for on play and pause and tracking current time
*
* @method manualTimeUpdatesOff
*/
Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() {
this.manualTimeUpdates = false;
this.stopTrackingCurrentTime();
this.off('play', this.trackCurrentTime);
this.off('pause', this.stopTrackingCurrentTime);
};
/**
* Tracks current time
*
* @method trackCurrentTime
*/
Tech.prototype.trackCurrentTime = function trackCurrentTime() {
if (this.currentTimeInterval) {
this.stopTrackingCurrentTime();
}
this.currentTimeInterval = this.setInterval(function () {
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
}, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
};
/**
* Turn off play progress tracking (when paused or dragging)
*
* @method stopTrackingCurrentTime
*/
Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() {
this.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.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
};
/**
* Turn off any manual progress or timeupdate tracking
*
* @method dispose
*/
Tech.prototype.dispose = function dispose() {
// clear out text tracks because we can't reuse them between techs
var textTracks = this.textTracks();
if (textTracks) {
var i = textTracks.length;
while (i--) {
this.removeRemoteTextTrack(textTracks[i]);
}
}
// Turn off any manual progress or timeupdate tracking
if (this.manualProgress) {
this.manualProgressOff();
}
if (this.manualTimeUpdates) {
this.manualTimeUpdatesOff();
}
_Component.prototype.dispose.call(this);
};
/**
* When invoked without an argument, returns a MediaError object
* representing the current error state of the player or null if
* there is no error. When invoked with an argument, set the current
* error state of the player.
* @param {MediaError=} err Optional an error object
* @return {MediaError} the current error object or null
* @method error
*/
Tech.prototype.error = function error(err) {
if (err !== undefined) {
if (err instanceof _mediaErrorJs2['default']) {
this.error_ = err;
} else {
this.error_ = new _mediaErrorJs2['default'](err);
}
this.trigger('error');
}
return this.error_;
};
/**
* Return the time ranges that have been played through for the
* current source. This implementation is incomplete. It does not
* track the played time ranges, only whether the source has played
* at all or not.
* @return {TimeRangeObject} a single time range if this video has
* played or an empty set of ranges if not.
* @method played
*/
Tech.prototype.played = function played() {
if (this.hasStarted_) {
return _utilsTimeRangesJs.createTimeRange(0, 0);
}
return _utilsTimeRangesJs.createTimeRange();
};
/**
* Set current time
*
* @method setCurrentTime
*/
Tech.prototype.setCurrentTime = function setCurrentTime() {
// improve the accuracy of manual timeupdates
if (this.manualTimeUpdates) {
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
}
};
/**
* Initialize texttrack listeners
*
* @method initTextTrackListeners
*/
Tech.prototype.initTextTrackListeners = function initTextTrackListeners() {
var textTrackListChanges = Fn.bind(this, function () {
this.trigger('texttrackchange');
});
var tracks = this.textTracks();
if (!tracks) return;
tracks.addEventListener('removetrack', textTrackListChanges);
tracks.addEventListener('addtrack', textTrackListChanges);
this.on('dispose', Fn.bind(this, function () {
tracks.removeEventListener('removetrack', textTrackListChanges);
tracks.removeEventListener('addtrack', textTrackListChanges);
}));
};
/**
* Emulate texttracks
*
* @method emulateTextTracks
*/
Tech.prototype.emulateTextTracks = function emulateTextTracks() {
if (!_globalWindow2['default']['WebVTT'] && this.el().parentNode != null) {
var script = _globalDocument2['default'].createElement('script');
script.src = this.options_['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js';
this.el().parentNode.appendChild(script);
_globalWindow2['default']['WebVTT'] = true;
}
var tracks = this.textTracks();
if (!tracks) {
return;
}
var textTracksChanges = Fn.bind(this, function () {
var _this = this;
var updateDisplay = function updateDisplay() {
return _this.trigger('texttrackchange');
};
updateDisplay();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.removeEventListener('cuechange', updateDisplay);
if (track.mode === 'showing') {
track.addEventListener('cuechange', updateDisplay);
}
}
});
tracks.addEventListener('change', textTracksChanges);
this.on('dispose', function () {
tracks.removeEventListener('change', textTracksChanges);
});
};
/*
* Provide default methods for text tracks.
*
* Html5 tech overrides these.
*/
/**
* Get texttracks
*
* @returns {TextTrackList}
* @method textTracks
*/
Tech.prototype.textTracks = function textTracks() {
this.textTracks_ = this.textTracks_ || new _tracksTextTrackList2['default']();
return this.textTracks_;
};
/**
* Get remote texttracks
*
* @returns {TextTrackList}
* @method remoteTextTracks
*/
Tech.prototype.remoteTextTracks = function remoteTextTracks() {
this.remoteTextTracks_ = this.remoteTextTracks_ || new _tracksTextTrackList2['default']();
return this.remoteTextTracks_;
};
/**
* Creates and returns a remote text track object
*
* @param {String} kind Text track kind (subtitles, captions, descriptions
* chapters and metadata)
* @param {String=} label Label to identify the text track
* @param {String=} language Two letter language abbreviation
* @return {TextTrackObject}
* @method addTextTrack
*/
Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) {
if (!kind) {
throw new Error('TextTrack kind is required but was not provided');
}
return createTrackHelper(this, kind, label, language);
};
/**
* Creates and returns a remote text track object
*
* @param {Object} options The object should contain values for
* kind, language, label and src (location of the WebVTT file)
* @return {TextTrackObject}
* @method addRemoteTextTrack
*/
Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) {
var track = createTrackHelper(this, options.kind, options.label, options.language, options);
this.remoteTextTracks().addTrack_(track);
return {
track: track
};
};
/**
* Remove remote texttrack
*
* @param {TextTrackObject} track Texttrack to remove
* @method removeRemoteTextTrack
*/
Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
this.textTracks().removeTrack_(track);
this.remoteTextTracks().removeTrack_(track);
};
/**
* 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.
*
* @method setPoster
*/
Tech.prototype.setPoster = function setPoster() {};
return Tech;
})(_component2['default']);
Tech.prototype.textTracks_;
var createTrackHelper = function createTrackHelper(self, kind, label, language) {
var options = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4];
var tracks = self.textTracks();
options.kind = kind;
if (label) {
options.label = label;
}
if (language) {
options.language = language;
}
options.tech = self;
var track = new _tracksTextTrack2['default'](options);
tracks.addTrack_(track);
return track;
};
Tech.prototype.featuresVolumeControl = true;
// Resizing plugins using request fullscreen reloads the plugin
Tech.prototype.featuresFullscreenResize = false;
Tech.prototype.featuresPlaybackRate = false;
// Optional events that we can manually mimic with timers
// currently not triggered by video-js-swf
Tech.prototype.featuresProgressEvents = false;
Tech.prototype.featuresTimeupdateEvents = false;
Tech.prototype.featuresNativeTextTracks = false;
/*
* A functional mixin for techs that want to use the Source Handler pattern.
*
* ##### EXAMPLE:
*
* Tech.withSourceHandlers.call(MyTech);
*
*/
Tech.withSourceHandlers = function (_Tech) {
/*
* Register a source handler
* Source handlers are scripts for handling specific formats.
* The source handler pattern is used for adaptive formats (HLS, DASH) that
* manually load video data and feed it into a Source Buffer (Media Source Extensions)
* @param {Function} handler The source handler
* @param {Boolean} first Register it before any existing handlers
*/
_Tech.registerSourceHandler = function (handler, index) {
var handlers = _Tech.sourceHandlers;
if (!handlers) {
handlers = _Tech.sourceHandlers = [];
}
if (index === undefined) {
// add to the end of the list
index = handlers.length;
}
handlers.splice(index, 0, handler);
};
/*
* Return the first source handler that supports the source
* TODO: Answer question: should 'probably' be prioritized over 'maybe'
* @param {Object} source The source object
* @returns {Object} The first source handler that supports the source
* @returns {null} Null if no source handler is found
*/
_Tech.selectSourceHandler = function (source) {
var handlers = _Tech.sourceHandlers || [];
var can = undefined;
for (var i = 0; i < handlers.length; i++) {
can = handlers[i].canHandleSource(source);
if (can) {
return handlers[i];
}
}
return null;
};
/*
* Check if the tech can support the given source
* @param {Object} srcObj The source object
* @return {String} 'probably', 'maybe', or '' (empty string)
*/
_Tech.canPlaySource = function (srcObj) {
var sh = _Tech.selectSourceHandler(srcObj);
if (sh) {
return sh.canHandleSource(srcObj);
}
return '';
};
var originalSeekable = _Tech.prototype.seekable;
// when a source handler is registered, prefer its implementation of
// seekable when present.
_Tech.prototype.seekable = function () {
if (this.sourceHandler_ && this.sourceHandler_.seekable) {
return this.sourceHandler_.seekable();
}
return originalSeekable.call(this);
};
/*
* Create a function for setting the source using a source object
* and source handlers.
* Should never be called unless a source handler was found.
* @param {Object} source A source object with src and type keys
* @return {Tech} self
*/
_Tech.prototype.setSource = function (source) {
var sh = _Tech.selectSourceHandler(source);
if (!sh) {
// Fall back to a native source hander when unsupported sources are
// deliberately set
if (_Tech.nativeSourceHandler) {
sh = _Tech.nativeSourceHandler;
} else {
_utilsLogJs2['default'].error('No source hander found for the current source.');
}
}
// Dispose any existing source handler
this.disposeSourceHandler();
this.off('dispose', this.disposeSourceHandler);
this.currentSource_ = source;
this.sourceHandler_ = sh.handleSource(source, this);
this.on('dispose', this.disposeSourceHandler);
return this;
};
/*
* Clean up any existing source handler
*/
_Tech.prototype.disposeSourceHandler = function () {
if (this.sourceHandler_ && this.sourceHandler_.dispose) {
this.sourceHandler_.dispose();
}
};
};
_component2['default'].registerComponent('Tech', Tech);
// Old name for Tech
_component2['default'].registerComponent('MediaTechController', Tech);
exports['default'] = Tech;
module.exports = exports['default'];
},{"../component":58,"../media-error.js":94,"../tracks/text-track":114,"../tracks/text-track-list":112,"../utils/buffer.js":116,"../utils/fn.js":120,"../utils/log.js":123,"../utils/time-ranges.js":126,"global/document":1,"global/window":2}],108:[function(_dereq_,module,exports){
/**
* @file text-track-cue-list.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist
*
* interface TextTrackCueList {
* readonly attribute unsigned long length;
* getter TextTrackCue (unsigned long index);
* TextTrackCue? getCueById(DOMString id);
* };
*/
var TextTrackCueList = function TextTrackCueList(cues) {
var list = this;
if (browser.IS_IE8) {
list = _globalDocument2['default'].createElement('custom');
for (var prop in TextTrackCueList.prototype) {
list[prop] = TextTrackCueList.prototype[prop];
}
}
TextTrackCueList.prototype.setCues_.call(list, cues);
Object.defineProperty(list, 'length', {
get: function get() {
return this.length_;
}
});
if (browser.IS_IE8) {
return list;
}
};
TextTrackCueList.prototype.setCues_ = function (cues) {
var oldLength = this.length || 0;
var i = 0;
var l = cues.length;
this.cues_ = cues;
this.length_ = cues.length;
var defineProp = function defineProp(i) {
if (!('' + i in this)) {
Object.defineProperty(this, '' + i, {
get: function get() {
return this.cues_[i];
}
});
}
};
if (oldLength < l) {
i = oldLength;
for (; i < l; i++) {
defineProp.call(this, i);
}
}
};
TextTrackCueList.prototype.getCueById = function (id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var cue = this[i];
if (cue.id === id) {
result = cue;
break;
}
}
return result;
};
exports['default'] = TextTrackCueList;
module.exports = exports['default'];
},{"../utils/browser.js":115,"global/document":1}],109:[function(_dereq_,module,exports){
/**
* @file text-track-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _menuMenuJs = _dereq_('../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _menuMenuItemJs = _dereq_('../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _menuMenuButtonJs = _dereq_('../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var darkGray = '#222';
var lightGray = '#ccc';
var fontMap = {
monospace: 'monospace',
sansSerif: 'sans-serif',
serif: 'serif',
monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
monospaceSerif: '"Courier New", monospace',
proportionalSansSerif: 'sans-serif',
proportionalSerif: 'serif',
casual: '"Comic Sans MS", Impact, fantasy',
script: '"Monotype Corsiva", cursive',
smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
};
/**
* The component for displaying text track cues
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Component
* @class TextTrackDisplay
*/
var TextTrackDisplay = (function (_Component) {
_inherits(TextTrackDisplay, _Component);
function TextTrackDisplay(player, options, ready) {
_classCallCheck(this, TextTrackDisplay);
_Component.call(this, player, options, ready);
player.on('loadstart', Fn.bind(this, this.toggleDisplay));
player.on('texttrackchange', Fn.bind(this, this.updateDisplay));
// 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.
player.ready(Fn.bind(this, function () {
if (player.tech_ && player.tech_['featuresNativeTextTracks']) {
this.hide();
return;
}
player.on('fullscreenchange', Fn.bind(this, this.updateDisplay));
var tracks = this.options_.playerOptions['tracks'] || [];
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
this.player_.addRemoteTextTrack(track);
}
}));
}
/**
* Add cue HTML to display
*
* @param {Number} color Hex number for color, like #f0e
* @param {Number} opacity Value for opacity,0.0 - 1.0
* @return {RGBAColor} In the form 'rgba(255, 0, 0, 0.3)'
* @method constructColor
*/
/**
* Toggle display texttracks
*
* @method toggleDisplay
*/
TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() {
if (this.player_.tech_ && this.player_.tech_['featuresNativeTextTracks']) {
this.hide();
} else {
this.show();
}
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
TextTrackDisplay.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-text-track-display'
});
};
/**
* Clear display texttracks
*
* @method clearDisplay
*/
TextTrackDisplay.prototype.clearDisplay = function clearDisplay() {
if (typeof _globalWindow2['default']['WebVTT'] === 'function') {
_globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], [], this.el_);
}
};
/**
* Update display texttracks
*
* @method updateDisplay
*/
TextTrackDisplay.prototype.updateDisplay = function updateDisplay() {
var tracks = this.player_.textTracks();
this.clearDisplay();
if (!tracks) {
return;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
if (track['mode'] === 'showing') {
this.updateForTrack(track);
}
}
};
/**
* Add texttrack to texttrack list
*
* @param {TextTrackObject} track Texttrack object to be added to list
* @method updateForTrack
*/
TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) {
if (typeof _globalWindow2['default']['WebVTT'] !== 'function' || !track['activeCues']) {
return;
}
var overrides = this.player_['textTrackSettings'].getValues();
var cues = [];
for (var _i = 0; _i < track['activeCues'].length; _i++) {
cues.push(track['activeCues'][_i]);
}
_globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], track['activeCues'], this.el_);
var i = cues.length;
while (i--) {
var cueDiv = cues[i].displayState;
if (overrides.color) {
cueDiv.firstChild.style.color = overrides.color;
}
if (overrides.textOpacity) {
tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
}
if (overrides.backgroundColor) {
cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
}
if (overrides.backgroundOpacity) {
tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
}
if (overrides.windowColor) {
if (overrides.windowOpacity) {
tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
} else {
cueDiv.style.backgroundColor = overrides.windowColor;
}
}
if (overrides.edgeStyle) {
if (overrides.edgeStyle === 'dropshadow') {
cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray;
} else if (overrides.edgeStyle === 'raised') {
cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray;
} else if (overrides.edgeStyle === 'depressed') {
cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray;
} else if (overrides.edgeStyle === 'uniform') {
cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray;
}
}
if (overrides.fontPercent && overrides.fontPercent !== 1) {
var fontSize = _globalWindow2['default'].parseFloat(cueDiv.style.fontSize);
cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
cueDiv.style.height = 'auto';
cueDiv.style.top = 'auto';
cueDiv.style.bottom = '2px';
}
if (overrides.fontFamily && overrides.fontFamily !== 'default') {
if (overrides.fontFamily === 'small-caps') {
cueDiv.firstChild.style.fontVariant = 'small-caps';
} else {
cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
}
}
}
};
return TextTrackDisplay;
})(_component2['default']);
function constructColor(color, opacity) {
return 'rgba(' +
// color looks like "#f0e"
parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')';
}
/**
* Try to update style
* Some style changes will throw an error, particularly in IE8. Those should be noops.
*
* @param {Element} el The element to be styles
* @param {CSSProperty} style The CSS property to be styled
* @param {CSSStyle} rule The actual style to be applied to the property
* @method tryUpdateStyle
*/
function tryUpdateStyle(el, style, rule) {
//
try {
el.style[style] = rule;
} catch (e) {}
}
_component2['default'].registerComponent('TextTrackDisplay', TextTrackDisplay);
exports['default'] = TextTrackDisplay;
module.exports = exports['default'];
},{"../component":58,"../menu/menu-button.js":95,"../menu/menu-item.js":96,"../menu/menu.js":97,"../utils/fn.js":120,"global/document":1,"global/window":2}],110:[function(_dereq_,module,exports){
/**
* @file text-track-enums.js
*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
*
* enum TextTrackMode { "disabled", "hidden", "showing" };
*/
'use strict';
exports.__esModule = true;
var TextTrackMode = {
'disabled': 'disabled',
'hidden': 'hidden',
'showing': 'showing'
};
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind
*
* enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" };
*/
var TextTrackKind = {
'subtitles': 'subtitles',
'captions': 'captions',
'descriptions': 'descriptions',
'chapters': 'chapters',
'metadata': 'metadata'
};
exports.TextTrackMode = TextTrackMode;
exports.TextTrackKind = TextTrackKind;
},{}],111:[function(_dereq_,module,exports){
/**
* Utilities for capturing text track state and re-creating tracks
* based on a capture.
*
* @file text-track-list-converter.js
*/
/**
* Examine a single text track and return a JSON-compatible javascript
* object that represents the text track's state.
* @param track {TextTrackObject} the text track to query
* @return {Object} a serializable javascript representation of the
* @private
*/
'use strict';
exports.__esModule = true;
var trackToJson_ = function trackToJson_(track) {
return {
kind: track.kind,
label: track.label,
language: track.language,
id: track.id,
inBandMetadataTrackDispatchType: track.inBandMetadataTrackDispatchType,
mode: track.mode,
cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
return {
startTime: cue.startTime,
endTime: cue.endTime,
text: cue.text,
id: cue.id
};
}),
src: track.src
};
};
/**
* Examine a tech and return a JSON-compatible javascript array that
* represents the state of all text tracks currently configured. The
* return array is compatible with `jsonToTextTracks`.
* @param tech {tech} the tech object to query
* @return {Array} a serializable javascript representation of the
* @function textTracksToJson
*/
var textTracksToJson = function textTracksToJson(tech) {
var trackEls = tech.el().querySelectorAll('track');
var trackObjs = Array.prototype.map.call(trackEls, function (t) {
return t.track;
});
var tracks = Array.prototype.map.call(trackEls, function (trackEl) {
var json = trackToJson_(trackEl.track);
json.src = trackEl.src;
return json;
});
return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
return trackObjs.indexOf(track) === -1;
}).map(trackToJson_));
};
/**
* Creates a set of remote text tracks on a tech based on an array of
* javascript text track representations.
* @param json {Array} an array of text track representation objects,
* like those that would be produced by `textTracksToJson`
* @param tech {tech} the tech to create text tracks on
* @function jsonToTextTracks
*/
var jsonToTextTracks = function jsonToTextTracks(json, tech) {
json.forEach(function (track) {
var addedTrack = tech.addRemoteTextTrack(track).track;
if (!track.src && track.cues) {
track.cues.forEach(function (cue) {
return addedTrack.addCue(cue);
});
}
});
return tech.textTracks();
};
exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ };
module.exports = exports['default'];
},{}],112:[function(_dereq_,module,exports){
/**
* @file text-track-list.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _eventTarget = _dereq_('../event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist
*
* interface TextTrackList : EventTarget {
* readonly attribute unsigned long length;
* getter TextTrack (unsigned long index);
* TextTrack? getTrackById(DOMString id);
*
* attribute EventHandler onchange;
* attribute EventHandler onaddtrack;
* attribute EventHandler onremovetrack;
* };
*/
var TextTrackList = function TextTrackList(tracks) {
var list = this;
if (browser.IS_IE8) {
list = _globalDocument2['default'].createElement('custom');
for (var prop in TextTrackList.prototype) {
list[prop] = TextTrackList.prototype[prop];
}
}
tracks = tracks || [];
list.tracks_ = [];
Object.defineProperty(list, 'length', {
get: function get() {
return this.tracks_.length;
}
});
for (var i = 0; i < tracks.length; i++) {
list.addTrack_(tracks[i]);
}
if (browser.IS_IE8) {
return list;
}
};
TextTrackList.prototype = Object.create(_eventTarget2['default'].prototype);
TextTrackList.prototype.constructor = TextTrackList;
/*
* change - One or more tracks in the track list have been enabled or disabled.
* addtrack - A track has been added to the track list.
* removetrack - A track has been removed from the track list.
*/
TextTrackList.prototype.allowedEvents_ = {
'change': 'change',
'addtrack': 'addtrack',
'removetrack': 'removetrack'
};
// emulate attribute EventHandler support to allow for feature detection
for (var _event in TextTrackList.prototype.allowedEvents_) {
TextTrackList.prototype['on' + _event] = null;
}
TextTrackList.prototype.addTrack_ = function (track) {
var index = this.tracks_.length;
if (!('' + index in this)) {
Object.defineProperty(this, index, {
get: function get() {
return this.tracks_[index];
}
});
}
track.addEventListener('modechange', Fn.bind(this, function () {
this.trigger('change');
}));
this.tracks_.push(track);
this.trigger({
type: 'addtrack',
track: track
});
};
TextTrackList.prototype.removeTrack_ = function (rtrack) {
var result = null;
var track = undefined;
for (var i = 0, l = this.length; i < l; i++) {
track = this[i];
if (track === rtrack) {
this.tracks_.splice(i, 1);
break;
}
}
this.trigger({
type: 'removetrack',
track: track
});
};
TextTrackList.prototype.getTrackById = function (id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var track = this[i];
if (track.id === id) {
result = track;
break;
}
}
return result;
};
exports['default'] = TextTrackList;
module.exports = exports['default'];
},{"../event-target":90,"../utils/browser.js":115,"../utils/fn.js":120,"global/document":1}],113:[function(_dereq_,module,exports){
/**
* @file text-track-settings.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsEventsJs = _dereq_('../utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple');
var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* Manipulate settings of texttracks
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Component
* @class TextTrackSettings
*/
var TextTrackSettings = (function (_Component) {
_inherits(TextTrackSettings, _Component);
function TextTrackSettings(player, options) {
_classCallCheck(this, TextTrackSettings);
_Component.call(this, player, options);
this.hide();
// Grab `persistTextTrackSettings` from the player options if not passed in child options
if (options.persistTextTrackSettings === undefined) {
this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
}
Events.on(this.el().querySelector('.vjs-done-button'), 'click', Fn.bind(this, function () {
this.saveSettings();
this.hide();
}));
Events.on(this.el().querySelector('.vjs-default-button'), 'click', Fn.bind(this, function () {
this.el().querySelector('.vjs-fg-color > select').selectedIndex = 0;
this.el().querySelector('.vjs-bg-color > select').selectedIndex = 0;
this.el().querySelector('.window-color > select').selectedIndex = 0;
this.el().querySelector('.vjs-text-opacity > select').selectedIndex = 0;
this.el().querySelector('.vjs-bg-opacity > select').selectedIndex = 0;
this.el().querySelector('.vjs-window-opacity > select').selectedIndex = 0;
this.el().querySelector('.vjs-edge-style select').selectedIndex = 0;
this.el().querySelector('.vjs-font-family select').selectedIndex = 0;
this.el().querySelector('.vjs-font-percent select').selectedIndex = 2;
this.updateDisplay();
}));
Events.on(this.el().querySelector('.vjs-fg-color > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-bg-color > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.window-color > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-font-percent select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-edge-style select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-font-family select'), 'change', Fn.bind(this, this.updateDisplay));
if (this.options_.persistTextTrackSettings) {
this.restoreSettings();
}
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
TextTrackSettings.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-caption-settings vjs-modal-overlay',
innerHTML: captionOptionsMenuTemplate()
});
};
/**
* Get texttrack settings
* Settings are
* .vjs-edge-style
* .vjs-font-family
* .vjs-fg-color
* .vjs-text-opacity
* .vjs-bg-color
* .vjs-bg-opacity
* .window-color
* .vjs-window-opacity
*
* @return {Object}
* @method getValues
*/
TextTrackSettings.prototype.getValues = function getValues() {
var el = this.el();
var textEdge = getSelectedOptionValue(el.querySelector('.vjs-edge-style select'));
var fontFamily = getSelectedOptionValue(el.querySelector('.vjs-font-family select'));
var fgColor = getSelectedOptionValue(el.querySelector('.vjs-fg-color > select'));
var textOpacity = getSelectedOptionValue(el.querySelector('.vjs-text-opacity > select'));
var bgColor = getSelectedOptionValue(el.querySelector('.vjs-bg-color > select'));
var bgOpacity = getSelectedOptionValue(el.querySelector('.vjs-bg-opacity > select'));
var windowColor = getSelectedOptionValue(el.querySelector('.window-color > select'));
var windowOpacity = getSelectedOptionValue(el.querySelector('.vjs-window-opacity > select'));
var fontPercent = _globalWindow2['default']['parseFloat'](getSelectedOptionValue(el.querySelector('.vjs-font-percent > select')));
var result = {
'backgroundOpacity': bgOpacity,
'textOpacity': textOpacity,
'windowOpacity': windowOpacity,
'edgeStyle': textEdge,
'fontFamily': fontFamily,
'color': fgColor,
'backgroundColor': bgColor,
'windowColor': windowColor,
'fontPercent': fontPercent
};
for (var _name in result) {
if (result[_name] === '' || result[_name] === 'none' || _name === 'fontPercent' && result[_name] === 1.00) {
delete result[_name];
}
}
return result;
};
/**
* Set texttrack settings
* Settings are
* .vjs-edge-style
* .vjs-font-family
* .vjs-fg-color
* .vjs-text-opacity
* .vjs-bg-color
* .vjs-bg-opacity
* .window-color
* .vjs-window-opacity
*
* @param {Object} values Object with texttrack setting values
* @method setValues
*/
TextTrackSettings.prototype.setValues = function setValues(values) {
var el = this.el();
setSelectedOption(el.querySelector('.vjs-edge-style select'), values.edgeStyle);
setSelectedOption(el.querySelector('.vjs-font-family select'), values.fontFamily);
setSelectedOption(el.querySelector('.vjs-fg-color > select'), values.color);
setSelectedOption(el.querySelector('.vjs-text-opacity > select'), values.textOpacity);
setSelectedOption(el.querySelector('.vjs-bg-color > select'), values.backgroundColor);
setSelectedOption(el.querySelector('.vjs-bg-opacity > select'), values.backgroundOpacity);
setSelectedOption(el.querySelector('.window-color > select'), values.windowColor);
setSelectedOption(el.querySelector('.vjs-window-opacity > select'), values.windowOpacity);
var fontPercent = values.fontPercent;
if (fontPercent) {
fontPercent = fontPercent.toFixed(2);
}
setSelectedOption(el.querySelector('.vjs-font-percent > select'), fontPercent);
};
/**
* Restore texttrack settings
*
* @method restoreSettings
*/
TextTrackSettings.prototype.restoreSettings = function restoreSettings() {
var _safeParseTuple = _safeJsonParseTuple2['default'](_globalWindow2['default'].localStorage.getItem('vjs-text-track-settings'));
var err = _safeParseTuple[0];
var values = _safeParseTuple[1];
if (err) {
_utilsLogJs2['default'].error(err);
}
if (values) {
this.setValues(values);
}
};
/**
* Save texttrack settings to local storage
*
* @method saveSettings
*/
TextTrackSettings.prototype.saveSettings = function saveSettings() {
if (!this.options_.persistTextTrackSettings) {
return;
}
var values = this.getValues();
try {
if (Object.getOwnPropertyNames(values).length > 0) {
_globalWindow2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values));
} else {
_globalWindow2['default'].localStorage.removeItem('vjs-text-track-settings');
}
} catch (e) {}
};
/**
* Update display of texttrack settings
*
* @method updateDisplay
*/
TextTrackSettings.prototype.updateDisplay = function updateDisplay() {
var ttDisplay = this.player_.getChild('textTrackDisplay');
if (ttDisplay) {
ttDisplay.updateDisplay();
}
};
return TextTrackSettings;
})(_component2['default']);
_component2['default'].registerComponent('TextTrackSettings', TextTrackSettings);
function getSelectedOptionValue(target) {
var selectedOption = undefined;
// not all browsers support selectedOptions, so, fallback to options
if (target.selectedOptions) {
selectedOption = target.selectedOptions[0];
} else if (target.options) {
selectedOption = target.options[target.options.selectedIndex];
}
return selectedOption.value;
}
function setSelectedOption(target, value) {
if (!value) {
return;
}
var i = undefined;
for (i = 0; i < target.options.length; i++) {
var option = target.options[i];
if (option.value === value) {
break;
}
}
target.selectedIndex = i;
}
function captionOptionsMenuTemplate() {
var template = '<div class="vjs-tracksettings">\n <div class="vjs-tracksettings-colors">\n <div class="vjs-fg-color vjs-tracksetting">\n <label class="vjs-label">Foreground</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-text-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Opaque</option>\n </select>\n </span>\n </div> <!-- vjs-fg-color -->\n <div class="vjs-bg-color vjs-tracksetting">\n <label class="vjs-label">Background</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-bg-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-bg-color -->\n <div class="window-color vjs-tracksetting">\n <label class="vjs-label">Window</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-window-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-window-color -->\n </div> <!-- vjs-tracksettings -->\n <div class="vjs-tracksettings-font">\n <div class="vjs-font-percent vjs-tracksetting">\n <label class="vjs-label">Font Size</label>\n <select>\n <option value="0.50">50%</option>\n <option value="0.75">75%</option>\n <option value="1.00" selected>100%</option>\n <option value="1.25">125%</option>\n <option value="1.50">150%</option>\n <option value="1.75">175%</option>\n <option value="2.00">200%</option>\n <option value="3.00">300%</option>\n <option value="4.00">400%</option>\n </select>\n </div> <!-- vjs-font-percent -->\n <div class="vjs-edge-style vjs-tracksetting">\n <label class="vjs-label">Text Edge Style</label>\n <select>\n <option value="none">None</option>\n <option value="raised">Raised</option>\n <option value="depressed">Depressed</option>\n <option value="uniform">Uniform</option>\n <option value="dropshadow">Dropshadow</option>\n </select>\n </div> <!-- vjs-edge-style -->\n <div class="vjs-font-family vjs-tracksetting">\n <label class="vjs-label">Font Family</label>\n <select>\n <option value="">Default</option>\n <option value="monospaceSerif">Monospace Serif</option>\n <option value="proportionalSerif">Proportional Serif</option>\n <option value="monospaceSansSerif">Monospace Sans-Serif</option>\n <option value="proportionalSansSerif">Proportional Sans-Serif</option>\n <option value="casual">Casual</option>\n <option value="script">Script</option>\n <option value="small-caps">Small Caps</option>\n </select>\n </div> <!-- vjs-font-family -->\n </div>\n </div>\n <div class="vjs-tracksettings-controls">\n <button class="vjs-default-button">Defaults</button>\n <button class="vjs-done-button">Done</button>\n </div>';
return template;
}
exports['default'] = TextTrackSettings;
module.exports = exports['default'];
},{"../component":58,"../utils/events.js":119,"../utils/fn.js":120,"../utils/log.js":123,"global/window":2,"safe-json-parse/tuple":48}],114:[function(_dereq_,module,exports){
/**
* @file text-track.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _textTrackCueList = _dereq_('./text-track-cue-list');
var _textTrackCueList2 = _interopRequireDefault(_textTrackCueList);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsGuidJs = _dereq_('../utils/guid.js');
var Guid = _interopRequireWildcard(_utilsGuidJs);
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _textTrackEnums = _dereq_('./text-track-enums');
var TextTrackEnum = _interopRequireWildcard(_textTrackEnums);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _eventTarget = _dereq_('../event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _xhr = _dereq_('xhr');
var _xhr2 = _interopRequireDefault(_xhr);
/*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack
*
* interface TextTrack : EventTarget {
* readonly attribute TextTrackKind kind;
* readonly attribute DOMString label;
* readonly attribute DOMString language;
*
* readonly attribute DOMString id;
* readonly attribute DOMString inBandMetadataTrackDispatchType;
*
* attribute TextTrackMode mode;
*
* readonly attribute TextTrackCueList? cues;
* readonly attribute TextTrackCueList? activeCues;
*
* void addCue(TextTrackCue cue);
* void removeCue(TextTrackCue cue);
*
* attribute EventHandler oncuechange;
* };
*/
var TextTrack = function TextTrack() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (!options.tech) {
throw new Error('A tech was not provided.');
}
var tt = this;
if (browser.IS_IE8) {
tt = _globalDocument2['default'].createElement('custom');
for (var prop in TextTrack.prototype) {
tt[prop] = TextTrack.prototype[prop];
}
}
tt.tech_ = options.tech;
var mode = TextTrackEnum.TextTrackMode[options['mode']] || 'disabled';
var kind = TextTrackEnum.TextTrackKind[options['kind']] || 'subtitles';
var label = options['label'] || '';
var language = options['language'] || options['srclang'] || '';
var id = options['id'] || 'vjs_text_track_' + Guid.newGUID();
if (kind === 'metadata' || kind === 'chapters') {
mode = 'hidden';
}
tt.cues_ = [];
tt.activeCues_ = [];
var cues = new _textTrackCueList2['default'](tt.cues_);
var activeCues = new _textTrackCueList2['default'](tt.activeCues_);
var changed = false;
var timeupdateHandler = Fn.bind(tt, function () {
this['activeCues'];
if (changed) {
this['trigger']('cuechange');
changed = false;
}
});
if (mode !== 'disabled') {
tt.tech_.on('timeupdate', timeupdateHandler);
}
Object.defineProperty(tt, 'kind', {
get: function get() {
return kind;
},
set: Function.prototype
});
Object.defineProperty(tt, 'label', {
get: function get() {
return label;
},
set: Function.prototype
});
Object.defineProperty(tt, 'language', {
get: function get() {
return language;
},
set: Function.prototype
});
Object.defineProperty(tt, 'id', {
get: function get() {
return id;
},
set: Function.prototype
});
Object.defineProperty(tt, 'mode', {
get: function get() {
return mode;
},
set: function set(newMode) {
if (!TextTrackEnum.TextTrackMode[newMode]) {
return;
}
mode = newMode;
if (mode === 'showing') {
this.tech_.on('timeupdate', timeupdateHandler);
}
this.trigger('modechange');
}
});
Object.defineProperty(tt, 'cues', {
get: function get() {
if (!this.loaded_) {
return null;
}
return cues;
},
set: Function.prototype
});
Object.defineProperty(tt, 'activeCues', {
get: function get() {
if (!this.loaded_) {
return null;
}
if (this['cues'].length === 0) {
return activeCues; // nothing to do
}
var ct = this.tech_.currentTime();
var active = [];
for (var i = 0, l = this['cues'].length; i < l; i++) {
var cue = this['cues'][i];
if (cue['startTime'] <= ct && cue['endTime'] >= ct) {
active.push(cue);
} else if (cue['startTime'] === cue['endTime'] && cue['startTime'] <= ct && cue['startTime'] + 0.5 >= ct) {
active.push(cue);
}
}
changed = false;
if (active.length !== this.activeCues_.length) {
changed = true;
} else {
for (var i = 0; i < active.length; i++) {
if (indexOf.call(this.activeCues_, active[i]) === -1) {
changed = true;
}
}
}
this.activeCues_ = active;
activeCues.setCues_(this.activeCues_);
return activeCues;
},
set: Function.prototype
});
if (options.src) {
tt.src = options.src;
loadTrack(options.src, tt);
} else {
tt.loaded_ = true;
}
if (browser.IS_IE8) {
return tt;
}
};
TextTrack.prototype = Object.create(_eventTarget2['default'].prototype);
TextTrack.prototype.constructor = TextTrack;
/*
* cuechange - One or more cues in the track have become active or stopped being active.
*/
TextTrack.prototype.allowedEvents_ = {
'cuechange': 'cuechange'
};
TextTrack.prototype.addCue = function (cue) {
var tracks = this.tech_.textTracks();
if (tracks) {
for (var i = 0; i < tracks.length; i++) {
if (tracks[i] !== this) {
tracks[i].removeCue(cue);
}
}
}
this.cues_.push(cue);
this['cues'].setCues_(this.cues_);
};
TextTrack.prototype.removeCue = function (removeCue) {
var removed = false;
for (var i = 0, l = this.cues_.length; i < l; i++) {
var cue = this.cues_[i];
if (cue === removeCue) {
this.cues_.splice(i, 1);
removed = true;
}
}
if (removed) {
this.cues.setCues_(this.cues_);
}
};
/*
* Downloading stuff happens below this point
*/
var parseCues = function parseCues(srcContent, track) {
if (typeof _globalWindow2['default']['WebVTT'] !== 'function') {
//try again a bit later
return _globalWindow2['default'].setTimeout(function () {
parseCues(srcContent, track);
}, 25);
}
var parser = new _globalWindow2['default']['WebVTT']['Parser'](_globalWindow2['default'], _globalWindow2['default']['vttjs'], _globalWindow2['default']['WebVTT']['StringDecoder']());
parser['oncue'] = function (cue) {
track.addCue(cue);
};
parser['onparsingerror'] = function (error) {
_utilsLogJs2['default'].error(error);
};
parser['parse'](srcContent);
parser['flush']();
};
var loadTrack = function loadTrack(src, track) {
_xhr2['default']({ uri: src }, Fn.bind(this, function (err, response, responseBody) {
if (err) {
return _utilsLogJs2['default'].error(err, response);
}
track.loaded_ = true;
parseCues(responseBody, track);
}));
};
var indexOf = function indexOf(searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
exports['default'] = TextTrack;
module.exports = exports['default'];
},{"../event-target":90,"../utils/browser.js":115,"../utils/fn.js":120,"../utils/guid.js":122,"../utils/log.js":123,"./text-track-cue-list":108,"./text-track-enums":110,"global/document":1,"global/window":2,"xhr":50}],115:[function(_dereq_,module,exports){
/**
* @file browser.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var USER_AGENT = _globalWindow2['default'].navigator.userAgent;
var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT);
var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null;
/*
* Device is an iPhone
*
* @type {Boolean}
* @constant
* @private
*/
var IS_IPHONE = /iPhone/i.test(USER_AGENT);
exports.IS_IPHONE = IS_IPHONE;
var IS_IPAD = /iPad/i.test(USER_AGENT);
exports.IS_IPAD = IS_IPAD;
var IS_IPOD = /iPod/i.test(USER_AGENT);
exports.IS_IPOD = IS_IPOD;
var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
exports.IS_IOS = IS_IOS;
var IOS_VERSION = (function () {
var match = USER_AGENT.match(/OS (\d+)_/i);
if (match && match[1]) {
return match[1];
}
})();
exports.IOS_VERSION = IOS_VERSION;
var IS_ANDROID = /Android/i.test(USER_AGENT);
exports.IS_ANDROID = IS_ANDROID;
var 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 = 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;
}
})();
exports.ANDROID_VERSION = ANDROID_VERSION;
// Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser
var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3;
exports.IS_OLD_ANDROID = IS_OLD_ANDROID;
var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537;
exports.IS_NATIVE_ANDROID = IS_NATIVE_ANDROID;
var IS_FIREFOX = /Firefox/i.test(USER_AGENT);
exports.IS_FIREFOX = IS_FIREFOX;
var IS_CHROME = /Chrome/i.test(USER_AGENT);
exports.IS_CHROME = IS_CHROME;
var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT);
exports.IS_IE8 = IS_IE8;
var TOUCH_ENABLED = !!('ontouchstart' in _globalWindow2['default'] || _globalWindow2['default'].DocumentTouch && _globalDocument2['default'] instanceof _globalWindow2['default'].DocumentTouch);
exports.TOUCH_ENABLED = TOUCH_ENABLED;
var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in _globalDocument2['default'].createElement('video').style);
exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED;
},{"global/document":1,"global/window":2}],116:[function(_dereq_,module,exports){
/**
* @file buffer.js
*/
'use strict';
exports.__esModule = true;
exports.bufferedPercent = bufferedPercent;
var _timeRangesJs = _dereq_('./time-ranges.js');
/**
* Compute how much your video has been buffered
*
* @param {Object} Buffered object
* @param {Number} Total duration
* @return {Number} Percent buffered of the total duration
* @private
* @function bufferedPercent
*/
function bufferedPercent(buffered, duration) {
var bufferedDuration = 0,
start,
end;
if (!duration) {
return 0;
}
if (!buffered || !buffered.length) {
buffered = _timeRangesJs.createTimeRange(0, 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;
}
},{"./time-ranges.js":126}],117:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _logJs = _dereq_('./log.js');
var _logJs2 = _interopRequireDefault(_logJs);
/**
* Object containing the default behaviors for available handler methods.
*
* @private
* @type {Object}
*/
var defaultBehaviors = {
get: function get(obj, key) {
return obj[key];
},
set: function set(obj, key, value) {
obj[key] = value;
return true;
}
};
/**
* Expose private objects publicly using a Proxy to log deprecation warnings.
*
* Browsers that do not support Proxy objects will simply return the `target`
* object, so it can be directly exposed.
*
* @param {Object} target The target object.
* @param {Object} messages Messages to display from a Proxy. Only operations
* with an associated message will be proxied.
* @param {String} [messages.get]
* @param {String} [messages.set]
* @return {Object} A Proxy if supported or the `target` argument.
*/
exports['default'] = function (target) {
var messages = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (typeof Proxy === 'function') {
var _ret = (function () {
var handler = {};
// Build a handler object based on those keys that have both messages
// and default behaviors.
Object.keys(messages).forEach(function (key) {
if (defaultBehaviors.hasOwnProperty(key)) {
handler[key] = function () {
_logJs2['default'].warn(messages[key]);
return defaultBehaviors[key].apply(this, arguments);
};
}
});
return {
v: new Proxy(target, handler)
};
})();
if (typeof _ret === 'object') return _ret.v;
}
return target;
};
module.exports = exports['default'];
},{"./log.js":123}],118:[function(_dereq_,module,exports){
/**
* @file dom.js
*/
'use strict';
exports.__esModule = true;
exports.getEl = getEl;
exports.createEl = createEl;
exports.insertElFirst = insertElFirst;
exports.getElData = getElData;
exports.hasElData = hasElData;
exports.removeElData = removeElData;
exports.hasElClass = hasElClass;
exports.addElClass = addElClass;
exports.removeElClass = removeElClass;
exports.setElAttributes = setElAttributes;
exports.getElAttributes = getElAttributes;
exports.blockTextSelection = blockTextSelection;
exports.unblockTextSelection = unblockTextSelection;
exports.findElPosition = findElPosition;
exports.getPointerPosition = getPointerPosition;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _guidJs = _dereq_('./guid.js');
var Guid = _interopRequireWildcard(_guidJs);
var _logJs = _dereq_('./log.js');
var _logJs2 = _interopRequireDefault(_logJs);
var _tsml = _dereq_('tsml');
var _tsml2 = _interopRequireDefault(_tsml);
/**
* 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
* @function getEl
*/
function getEl(id) {
if (id.indexOf('#') === 0) {
id = id.slice(1);
}
return _globalDocument2['default'].getElementById(id);
}
/**
* 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}
* @function createEl
*/
function createEl() {
var tagName = arguments.length <= 0 || arguments[0] === undefined ? 'div' : arguments[0];
var properties = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var el = _globalDocument2['default'].createElement(tagName);
Object.getOwnPropertyNames(properties).forEach(function (propName) {
var val = properties[propName];
// See #2176
// We originally were accepting both properties and attributes in the
// same object, but that doesn't work so well.
if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') {
_logJs2['default'].warn(_tsml2['default']('Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ' + propName + ' to ' + val + '.'));
el.setAttribute(propName, val);
} else {
el[propName] = val;
}
});
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
var val = attributes[attrName];
el.setAttribute(attrName, attributes[attrName]);
});
return el;
}
/**
* Insert an element as the first child node of another
*
* @param {Element} child Element to insert
* @param {Element} parent Element to insert child into
* @private
* @function insertElFirst
*/
function insertElFirst(child, parent) {
if (parent.firstChild) {
parent.insertBefore(child, parent.firstChild);
} else {
parent.appendChild(child);
}
}
/**
* Element Data Store. Allows for binding data to an element without putting it directly on the element.
* Ex. Event listeners are stored here.
* (also from jsninja.com, slightly modified and updated for closure compiler)
*
* @type {Object}
* @private
*/
var elData = {};
/*
* Unique attribute name to store an element's guid in
*
* @type {String}
* @constant
* @private
*/
var elIdAttr = '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}
* @function getElData
*/
function getElData(el) {
var id = el[elIdAttr];
if (!id) {
id = el[elIdAttr] = Guid.newGUID();
}
if (!elData[id]) {
elData[id] = {};
}
return elData[id];
}
/**
* Returns whether or not an element has cached data
*
* @param {Element} el A dom element
* @return {Boolean}
* @private
* @function hasElData
*/
function hasElData(el) {
var id = el[elIdAttr];
if (!id) {
return false;
}
return !!Object.getOwnPropertyNames(elData[id]).length;
}
/**
* Delete data for the element from the cache and the guid attr from getElementById
*
* @param {Element} el Remove data for an element
* @private
* @function removeElData
*/
function removeElData(el) {
var id = el[elIdAttr];
if (!id) {
return;
}
// Remove all stored data
delete elData[id];
// Remove the elIdAttr property from the DOM node
try {
delete el[elIdAttr];
} catch (e) {
if (el.removeAttribute) {
el.removeAttribute(elIdAttr);
} else {
// IE doesn't appear to support removeAttribute on the document element
el[elIdAttr] = null;
}
}
}
/**
* Check if an element has a CSS class
*
* @param {Element} element Element to check
* @param {String} classToCheck Classname to check
* @function hasElClass
*/
function hasElClass(element, classToCheck) {
return (' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1;
}
/**
* Add a CSS class name to an element
*
* @param {Element} element Element to add class name to
* @param {String} classToAdd Classname to add
* @function addElClass
*/
function addElClass(element, classToAdd) {
if (!hasElClass(element, classToAdd)) {
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} classToRemove Classname to remove
* @function removeElClass
*/
function removeElClass(element, classToRemove) {
if (!hasElClass(element, classToRemove)) {
return;
}
var classNames = element.className.split(' ');
// no arr.indexOf in ie8, and we don't want to add a big shim
for (var i = classNames.length - 1; i >= 0; i--) {
if (classNames[i] === classToRemove) {
classNames.splice(i, 1);
}
}
element.className = classNames.join(' ');
}
/**
* Apply attributes to an HTML element.
*
* @param {Element} el Target element.
* @param {Object=} attributes Element attributes to be applied.
* @private
* @function setElAttributes
*/
function setElAttributes(el, attributes) {
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
var attrValue = attributes[attrName];
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
* Attributes 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
* @function getElAttributes
*/
function getElAttributes(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;
}
/**
* Attempt to block the ability to select text while dragging controls
*
* @return {Boolean}
* @method blockTextSelection
*/
function blockTextSelection() {
_globalDocument2['default'].body.focus();
_globalDocument2['default'].onselectstart = function () {
return false;
};
}
/**
* Turn off text selection blocking
*
* @return {Boolean}
* @method unblockTextSelection
*/
function unblockTextSelection() {
_globalDocument2['default'].onselectstart = function () {
return true;
};
}
/**
* Offset Left
* getBoundingClientRect technique from
* John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/
*
* @param {Element} el Element from which to get offset
* @return {Object=}
* @method findElPosition
*/
function findElPosition(el) {
var box = undefined;
if (el.getBoundingClientRect && el.parentNode) {
box = el.getBoundingClientRect();
}
if (!box) {
return {
left: 0,
top: 0
};
}
var docEl = _globalDocument2['default'].documentElement;
var body = _globalDocument2['default'].body;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var scrollLeft = _globalWindow2['default'].pageXOffset || body.scrollLeft;
var left = box.left + scrollLeft - clientLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var scrollTop = _globalWindow2['default'].pageYOffset || body.scrollTop;
var top = box.top + scrollTop - clientTop;
// Android sometimes returns slightly off decimal values, so need to round
return {
left: Math.round(left),
top: Math.round(top)
};
}
/**
* Get pointer position in element
* Returns an object with x and y coordinates.
* The base on the coordinates are the bottom left of the element.
*
* @param {Element} el Element on which to get the pointer position on
* @param {Event} event Event object
* @return {Object=} position This object will have x and y coordinates corresponding to the mouse position
* @metho getPointerPosition
*/
function getPointerPosition(el, event) {
var position = {};
var box = findElPosition(el);
var boxW = el.offsetWidth;
var boxH = el.offsetHeight;
var boxY = box.top;
var boxX = box.left;
var pageY = event.pageY;
var pageX = event.pageX;
if (event.changedTouches) {
pageX = event.changedTouches[0].pageX;
pageY = event.changedTouches[0].pageY;
}
position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH));
position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW));
return position;
}
},{"./guid.js":122,"./log.js":123,"global/document":1,"global/window":2,"tsml":49}],119:[function(_dereq_,module,exports){
/**
* @file events.js
*
* 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.
*/
'use strict';
exports.__esModule = true;
exports.on = on;
exports.off = off;
exports.trigger = trigger;
exports.one = one;
exports.fixEvent = fixEvent;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _domJs = _dereq_('./dom.js');
var Dom = _interopRequireWildcard(_domJs);
var _guidJs = _dereq_('./guid.js');
var Guid = _interopRequireWildcard(_guidJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* 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.
* @method on
*/
function on(elem, type, fn) {
if (Array.isArray(type)) {
return _handleMultipleEvents(on, elem, type, fn);
}
var data = Dom.getElData(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 = Guid.newGUID();
data.handlers[type].push(fn);
if (!data.dispatcher) {
data.disabled = false;
data.dispatcher = function (event, hash) {
if (data.disabled) return;
event = 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, hash);
}
}
}
};
}
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 include to remove listeners for an event type.
* @method off
*/
function off(elem, type, fn) {
// Don't want to add a cache object through getElData if not needed
if (!Dom.hasElData(elem)) return;
var data = Dom.getElData(elem);
// If no events exist, nothing to unbind
if (!data.handlers) {
return;
}
if (Array.isArray(type)) {
return _handleMultipleEvents(off, elem, type, fn);
}
// Utility function
var removeType = function removeType(t) {
data.handlers[t] = [];
_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);
}
}
}
_cleanUpEvents(elem, type);
}
/**
* 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
* @param {Object} [hash] data hash to pass along with the event
* @return {Boolean=} Returned only if default was prevented
* @method trigger
*/
function trigger(elem, event, hash) {
// 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 hasElData first.
var elemData = Dom.hasElData(elem) ? Dom.getElData(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 = fixEvent(event);
// If the passed element has a dispatcher, executes the established handlers.
if (elemData.dispatcher) {
elemData.dispatcher.call(elem, event, hash);
}
// 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 === true) {
trigger.call(null, parent, event, hash);
// If at the top of the DOM, triggers the default action unless disabled.
} else if (!parent && !event.defaultPrevented) {
var targetData = Dom.getElData(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;
}
/**
* Trigger a listener only once for an event
*
* @param {Element|Object} elem Element or object to
* @param {String|Array} type Name/type of event
* @param {Function} fn Event handler function
* @method one
*/
function one(elem, type, fn) {
if (Array.isArray(type)) {
return _handleMultipleEvents(one, elem, type, fn);
}
var func = function func() {
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 || Guid.newGUID();
on(elem, type, func);
}
/**
* Fix a native event to have standard property values
*
* @param {Object} event Event object to fix
* @return {Object}
* @private
* @method fixEvent
*/
function fixEvent(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 || _globalWindow2['default'].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
// and webkitMovementX/Y
if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') {
// 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 || _globalDocument2['default'];
}
// Handle which other element the event is related to
if (!event.relatedTarget) {
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;
old.returnValue = false;
event.defaultPrevented = true;
};
event.defaultPrevented = false;
// Stop the event from bubbling
event.stopPropagation = function () {
if (old.stopPropagation) {
old.stopPropagation();
}
event.cancelBubble = true;
old.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 = _globalDocument2['default'].documentElement,
body = _globalDocument2['default'].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;
}
/**
* 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
* @method _cleanUpEvents
*/
function _cleanUpEvents(elem, type) {
var data = Dom.getElData(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 (Object.getOwnPropertyNames(data.handlers).length <= 0) {
delete data.handlers;
delete data.dispatcher;
delete data.disabled;
}
// Finally remove the element data if there is no data left
if (Object.getOwnPropertyNames(data).length === 0) {
Dom.removeElData(elem);
}
}
/**
* 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
*/
function _handleMultipleEvents(fn, elem, types, callback) {
types.forEach(function (type) {
//Call the event method for each one of the types
fn(elem, type, callback);
});
}
},{"./dom.js":118,"./guid.js":122,"global/document":1,"global/window":2}],120:[function(_dereq_,module,exports){
/**
* @file fn.js
*/
'use strict';
exports.__esModule = true;
var _guidJs = _dereq_('./guid.js');
/**
* 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
* @method bind
*/
var bind = function bind(context, fn, uid) {
// Make sure the function has a unique ID
if (!fn.guid) {
fn.guid = _guidJs.newGUID();
}
// Create the new function that changes the context
var ret = function ret() {
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;
};
exports.bind = bind;
},{"./guid.js":122}],121:[function(_dereq_,module,exports){
/**
* @file format-time.js
*
* 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
* @function formatTime
*/
'use strict';
exports.__esModule = true;
function formatTime(seconds) {
var guide = arguments.length <= 1 || arguments[1] === undefined ? seconds : arguments[1];
return (function () {
var s = Math.floor(seconds % 60);
var m = Math.floor(seconds / 60 % 60);
var h = Math.floor(seconds / 3600);
var gm = Math.floor(guide / 60 % 60);
var 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;
})();
}
exports['default'] = formatTime;
module.exports = exports['default'];
},{}],122:[function(_dereq_,module,exports){
/**
* @file guid.js
*
* Unique ID for an element or function
* @type {Number}
* @private
*/
"use strict";
exports.__esModule = true;
exports.newGUID = newGUID;
var _guid = 1;
/**
* Get the next unique ID
*
* @return {String}
* @function newGUID
*/
function newGUID() {
return _guid++;
}
},{}],123:[function(_dereq_,module,exports){
/**
* @file log.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* Log plain debug messages
*/
var log = function log() {
_logType(null, arguments);
};
/**
* Keep a history of log messages
* @type {Array}
*/
log.history = [];
/**
* Log error messages
*/
log.error = function () {
_logType('error', arguments);
};
/**
* Log warning messages
*/
log.warn = function () {
_logType('warn', arguments);
};
/**
* Log messages to the console and history based on the type of message
*
* @param {String} type The type of message, or `null` for `log`
* @param {Object} args The args to be passed to the log
* @private
* @method _logType
*/
function _logType(type, args) {
// convert args to an array to get array functions
var argsArray = Array.prototype.slice.call(args);
// if there's no console then don't try to output messages
// they will still be stored in 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
var noop = function noop() {};
var console = _globalWindow2['default']['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
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(' '));
}
}
exports['default'] = log;
module.exports = exports['default'];
},{"global/window":2}],124:[function(_dereq_,module,exports){
/**
* @file merge-options.js
*/
'use strict';
exports.__esModule = true;
exports['default'] = mergeOptions;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge');
var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge);
function isPlain(obj) {
return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object;
}
/**
* Merge customizer. video.js simply overwrites non-simple objects
* (like arrays) instead of attempting to overlay them.
* @see https://lodash.com/docs#merge
*/
var customizer = function customizer(destination, source) {
// If we're not working with a plain object, copy the value as is
// If source is an array, for instance, it will replace destination
if (!isPlain(source)) {
return source;
}
// If the new value is a plain object but the first object value is not
// we need to create a new object for the first object to merge with.
// This makes it consistent with how merge() works by default
// and also protects from later changes the to first object affecting
// the second object's values.
if (!isPlain(destination)) {
return mergeOptions(source);
}
};
/**
* Merge one or more options objects, recursively merging **only**
* plain object properties. Previously `deepMerge`.
*
* @param {...Object} source One or more objects to merge
* @returns {Object} a new object that is the union of all
* provided objects
* @function mergeOptions
*/
function mergeOptions() {
// contruct the call dynamically to handle the variable number of
// objects to merge
var args = Array.prototype.slice.call(arguments);
// unshift an empty object into the front of the call as the target
// of the merge
args.unshift({});
// customize conflict resolution to match our historical merge behavior
args.push(customizer);
_lodashCompatObjectMerge2['default'].apply(null, args);
// return the mutated result object
return args[0];
}
module.exports = exports['default'];
},{"lodash-compat/object/merge":40}],125:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var createStyleElement = function createStyleElement(className) {
var style = _globalDocument2['default'].createElement('style');
style.className = className;
return style;
};
exports.createStyleElement = createStyleElement;
var setTextContent = function setTextContent(el, content) {
if (el.styleSheet) {
el.styleSheet.cssText = content;
} else {
el.textContent = content;
}
};
exports.setTextContent = setTextContent;
},{"global/document":1}],126:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
exports.createTimeRanges = createTimeRanges;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _logJs = _dereq_('./log.js');
var _logJs2 = _interopRequireDefault(_logJs);
/**
* @file time-ranges.js
*
* 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|Array)} Start of a single range or an array of ranges
* @param {Number} End of a single range
* @private
* @method createTimeRanges
*/
function createTimeRanges(start, end) {
if (Array.isArray(start)) {
return createTimeRangesObj(start);
} else if (start === undefined || end === undefined) {
return createTimeRangesObj();
}
return createTimeRangesObj([[start, end]]);
}
exports.createTimeRange = createTimeRanges;
function createTimeRangesObj(ranges) {
if (ranges === undefined || ranges.length === 0) {
return {
length: 0,
start: function start() {
throw new Error('This TimeRanges object is empty');
},
end: function end() {
throw new Error('This TimeRanges object is empty');
}
};
}
return {
length: ranges.length,
start: getRange.bind(null, 'start', 0, ranges),
end: getRange.bind(null, 'end', 1, ranges)
};
}
function getRange(fnName, valueIndex, ranges, rangeIndex) {
if (rangeIndex === undefined) {
_logJs2['default'].warn('DEPRECATED: Function \'' + fnName + '\' on \'TimeRanges\' called without an index argument.');
rangeIndex = 0;
}
rangeCheck(fnName, rangeIndex, ranges.length - 1);
return ranges[rangeIndex][valueIndex];
}
function rangeCheck(fnName, index, maxIndex) {
if (index < 0 || index > maxIndex) {
throw new Error('Failed to execute \'' + fnName + '\' on \'TimeRanges\': The index provided (' + index + ') is greater than or equal to the maximum bound (' + maxIndex + ').');
}
}
},{"./log.js":123}],127:[function(_dereq_,module,exports){
/**
* @file to-title-case.js
*
* Uppercase the first letter of a string
*
* @param {String} string String to be uppercased
* @return {String}
* @private
* @method toTitleCase
*/
"use strict";
exports.__esModule = true;
function toTitleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
exports["default"] = toTitleCase;
module.exports = exports["default"];
},{}],128:[function(_dereq_,module,exports){
/**
* @file url.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* Resolve and parse the elements of a URL
*
* @param {String} url The url to parse
* @return {Object} An object of url details
* @method parseUrl
*/
var parseUrl = function parseUrl(url) {
var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
// add the url to an anchor and let the browser parse the URL
var a = _globalDocument2['default'].createElement('a');
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
var addToBody = a.host === '' && a.protocol !== 'file:';
var div = undefined;
if (addToBody) {
div = _globalDocument2['default'].createElement('div');
div.innerHTML = '<a href="' + url + '"></a>';
a = div.firstChild;
// prevent the div from affecting layout
div.setAttribute('style', 'display:none; position:absolute;');
_globalDocument2['default'].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
var details = {};
for (var i = 0; i < props.length; i++) {
details[props[i]] = a[props[i]];
}
// IE9 adds the port to the host property unlike everyone else. If
// a port identifier is added for standard ports, strip it.
if (details.protocol === 'http:') {
details.host = details.host.replace(/:80$/, '');
}
if (details.protocol === 'https:') {
details.host = details.host.replace(/:443$/, '');
}
if (addToBody) {
_globalDocument2['default'].body.removeChild(div);
}
return details;
};
exports.parseUrl = parseUrl;
/**
* Get absolute 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
* @method getAbsoluteURL
*/
var getAbsoluteURL = function getAbsoluteURL(url) {
// Check if absolute URL
if (!url.match(/^https?:\/\//)) {
// Convert to absolute URL. Flash hosted off-site needs an absolute URL.
var div = _globalDocument2['default'].createElement('div');
div.innerHTML = '<a href="' + url + '">x</a>';
url = div.firstChild.href;
}
return url;
};
exports.getAbsoluteURL = getAbsoluteURL;
/**
* Returns the extension of the passed file name. It will return an empty string if you pass an invalid path
*
* @param {String} path The fileName path like '/path/to/file.mp4'
* @returns {String} The extension in lower case or an empty string if no extension could be found.
* @method getFileExtension
*/
var getFileExtension = function getFileExtension(path) {
if (typeof path === 'string') {
var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i;
var pathParts = splitPathRe.exec(path);
if (pathParts) {
return pathParts.pop().toLowerCase();
}
}
return '';
};
exports.getFileExtension = getFileExtension;
},{"global/document":1}],129:[function(_dereq_,module,exports){
/**
* @file video.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _setup = _dereq_('./setup');
var setup = _interopRequireWildcard(_setup);
var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js');
var stylesheet = _interopRequireWildcard(_utilsStylesheetJs);
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _eventTarget = _dereq_('./event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _player = _dereq_('./player');
var _player2 = _interopRequireDefault(_player);
var _pluginsJs = _dereq_('./plugins.js');
var _pluginsJs2 = _interopRequireDefault(_pluginsJs);
var _srcJsUtilsMergeOptionsJs = _dereq_('../../src/js/utils/merge-options.js');
var _srcJsUtilsMergeOptionsJs2 = _interopRequireDefault(_srcJsUtilsMergeOptionsJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _tracksTextTrackJs = _dereq_('./tracks/text-track.js');
var _tracksTextTrackJs2 = _interopRequireDefault(_tracksTextTrackJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js');
var _utilsFormatTimeJs = _dereq_('./utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
var _utilsLogJs = _dereq_('./utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsBrowserJs = _dereq_('./utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _utilsUrlJs = _dereq_('./utils/url.js');
var Url = _interopRequireWildcard(_utilsUrlJs);
var _extendJs = _dereq_('./extend.js');
var _extendJs2 = _interopRequireDefault(_extendJs);
var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge');
var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge);
var _utilsCreateDeprecationProxyJs = _dereq_('./utils/create-deprecation-proxy.js');
var _utilsCreateDeprecationProxyJs2 = _interopRequireDefault(_utilsCreateDeprecationProxyJs);
var _xhr = _dereq_('xhr');
var _xhr2 = _interopRequireDefault(_xhr);
// Include the built-in techs
var _techHtml5Js = _dereq_('./tech/html5.js');
var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js);
var _techFlashJs = _dereq_('./tech/flash.js');
var _techFlashJs2 = _interopRequireDefault(_techFlashJs);
// HTML5 Element Shim for IE8
if (typeof HTMLVideoElement === 'undefined') {
_globalDocument2['default'].createElement('video');
_globalDocument2['default'].createElement('audio');
_globalDocument2['default'].createElement('track');
}
/**
* Doubles as the main function for users to create a player instance and also
* the main library object.
* The `videojs` function can be used to initialize or retrieve a player.
* ```js
* var myPlayer = videojs('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 {Player} A player instance
* @mixes videojs
* @method videojs
*/
var videojs = function videojs(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 (videojs.getPlayers()[id]) {
// If options or ready funtion are passed, warn
if (options) {
_utilsLogJs2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.');
}
if (ready) {
videojs.getPlayers()[id].ready(ready);
}
return videojs.getPlayers()[id];
// Otherwise get element for ID
} else {
tag = Dom.getEl(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 _player2['default'](tag, options, ready);
};
// Add default styles
var style = _globalDocument2['default'].querySelector('.vjs-styles-defaults');
if (!style) {
style = stylesheet.createStyleElement('vjs-styles-defaults');
var head = _globalDocument2['default'].querySelector('head');
head.insertBefore(style, head.firstChild);
stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n ');
}
// 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)
setup.autoSetupTimeout(1, videojs);
/*
* Current software version (semver)
*
* @type {String}
*/
videojs.VERSION = '5.0.0-rc.98';
/**
* The global options object. These are the settings that take effect
* if no overrides are specified when the player is created.
*
* ```js
* videojs.options.autoplay = true
* // -> all players will autoplay by default
* ```
*
* @type {Object}
*/
videojs.options = _player2['default'].prototype.options_;
/**
* Get an object with the currently created players, keyed by player ID
*
* @return {Object} The created players
* @mixes videojs
* @method getPlayers
*/
videojs.getPlayers = function () {
return _player2['default'].players;
};
/**
* For backward compatibility, expose players object.
*
* @deprecated
* @memberOf videojs
* @property {Object|Proxy} players
*/
videojs.players = _utilsCreateDeprecationProxyJs2['default'](_player2['default'].players, {
get: 'Access to videojs.players is deprecated; use videojs.getPlayers instead',
set: 'Modification of videojs.players is deprecated'
});
/**
* Get a component class object by name
* ```js
* var VjsButton = videojs.getComponent('Button');
* // Create a new instance of the component
* var myButton = new VjsButton(myPlayer);
* ```
*
* @return {Component} Component identified by name
* @mixes videojs
* @method getComponent
*/
videojs.getComponent = _component2['default'].getComponent;
/**
* Register a component so it can referred to by name
* Used when adding to other
* components, either through addChild
* `component.addChild('myComponent')`
* or through default children options
* `{ children: ['myComponent'] }`.
* ```js
* // Get a component to subclass
* var VjsButton = videojs.getComponent('Button');
* // Subclass the component (see 'extend' doc for more info)
* var MySpecialButton = videojs.extend(VjsButton, {});
* // Register the new component
* VjsButton.registerComponent('MySepcialButton', MySepcialButton);
* // (optionally) add the new component as a default player child
* myPlayer.addChild('MySepcialButton');
* ```
* NOTE: You could also just initialize the component before adding.
* `component.addChild(new MyComponent());`
*
* @param {String} The class name of the component
* @param {Component} The component class
* @return {Component} The newly registered component
* @mixes videojs
* @method registerComponent
*/
videojs.registerComponent = _component2['default'].registerComponent;
/**
* A suite of browser and device tests
*
* @type {Object}
* @private
*/
videojs.browser = browser;
/**
* Whether or not the browser supports touch events. Included for backward
* compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED`
* instead going forward.
*
* @deprecated
* @type {Boolean}
*/
videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED;
/**
* Subclass an existing class
* Mimics ES6 subclassing with the `extend` keyword
* ```js
* // Create a basic javascript 'class'
* function MyClass(name){
* // Set a property at initialization
* this.myName = name;
* }
* // Create an instance method
* MyClass.prototype.sayMyName = function(){
* alert(this.myName);
* };
* // Subclass the exisitng class and change the name
* // when initializing
* var MySubClass = videojs.extend(MyClass, {
* constructor: function(name) {
* // Call the super class constructor for the subclass
* MyClass.call(this, name)
* }
* });
* // Create an instance of the new sub class
* var myInstance = new MySubClass('John');
* myInstance.sayMyName(); // -> should alert "John"
* ```
*
* @param {Function} The Class to subclass
* @param {Object} An object including instace methods for the new class
* Optionally including a `constructor` function
* @return {Function} The newly created subclass
* @mixes videojs
* @method extend
*/
videojs.extend = _extendJs2['default'];
/**
* Merge two options objects recursively
* Performs a deep merge like lodash.merge but **only merges plain objects**
* (not arrays, elements, anything else)
* Other values will be copied directly from the second object.
* ```js
* var defaultOptions = {
* foo: true,
* bar: {
* a: true,
* b: [1,2,3]
* }
* };
* var newOptions = {
* foo: false,
* bar: {
* b: [4,5,6]
* }
* };
* var result = videojs.mergeOptions(defaultOptions, newOptions);
* // result.foo = false;
* // result.bar.a = true;
* // result.bar.b = [4,5,6];
* ```
*
* @param {Object} The options object whose values will be overriden
* @param {Object} The options object with values to override the first
* @param {Object} Any number of additional options objects
*
* @return {Object} a new object with the merged values
* @mixes videojs
* @method mergeOptions
*/
videojs.mergeOptions = _srcJsUtilsMergeOptionsJs2['default'];
/**
* Change the context (this) of a function
*
* videojs.bind(newContext, function(){
* this === newContext
* });
*
* NOTE: as of v5.0 we require an ES5 shim, so you should use the native
* `function(){}.bind(newContext);` instead of this.
*
* @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}
*/
videojs.bind = Fn.bind;
/**
* Create a Video.js player plugin
* Plugins are only initialized when options for the plugin are included
* in the player options, or the plugin function on the player instance is
* called.
* **See the plugin guide in the docs for a more detailed example**
* ```js
* // Make a plugin that alerts when the player plays
* videojs.plugin('myPlugin', function(myPluginOptions) {
* myPluginOptions = myPluginOptions || {};
*
* var player = this;
* var alertText = myPluginOptions.text || 'Player is playing!'
*
* player.on('play', function(){
* alert(alertText);
* });
* });
* // USAGE EXAMPLES
* // EXAMPLE 1: New player with plugin options, call plugin immediately
* var player1 = videojs('idOne', {
* myPlugin: {
* text: 'Custom text!'
* }
* });
* // Click play
* // --> Should alert 'Custom text!'
* // EXAMPLE 3: New player, initialize plugin later
* var player3 = videojs('idThree');
* // Click play
* // --> NO ALERT
* // Click pause
* // Initialize plugin using the plugin function on the player instance
* player3.myPlugin({
* text: 'Plugin added later!'
* });
* // Click play
* // --> Should alert 'Plugin added later!'
* ```
*
* @param {String} The plugin name
* @param {Function} The plugin function that will be called with options
* @mixes videojs
* @method plugin
*/
videojs.plugin = _pluginsJs2['default'];
/**
* Adding languages so that they're available to all players.
* ```js
* videojs.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 language dictionary object
* @mixes videojs
* @method addLanguage
*/
videojs.addLanguage = function (code, data) {
var _merge;
code = ('' + code).toLowerCase();
return _lodashCompatObjectMerge2['default'](videojs.options.languages, (_merge = {}, _merge[code] = data, _merge))[code];
};
/**
* Log debug messages.
*
* @param {...Object} messages One or more messages to log
*/
videojs.log = _utilsLogJs2['default'];
/**
* Creates an emulated TimeRange object.
*
* @param {Number|Array} start Start time in seconds or an array of ranges
* @param {Number} end End time in seconds
* @return {Object} Fake TimeRange object
* @method createTimeRange
*/
videojs.createTimeRange = videojs.createTimeRanges = _utilsTimeRangesJs.createTimeRanges;
/**
* 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
* @method formatTime
*/
videojs.formatTime = _utilsFormatTimeJs2['default'];
/**
* Resolve and parse the elements of a URL
*
* @param {String} url The url to parse
* @return {Object} An object of url details
* @method parseUrl
*/
videojs.parseUrl = Url.parseUrl;
/**
* Event target class.
*
* @type {Function}
*/
videojs.EventTarget = _eventTarget2['default'];
/**
* 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.
* @method on
*/
videojs.on = Events.on;
/**
* Trigger a listener only once for an event
*
* @param {Element|Object} elem Element or object to
* @param {String|Array} type Name/type of event
* @param {Function} fn Event handler function
* @method one
*/
videojs.one = Events.one;
/**
* 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 include to remove listeners for an event type.
* @method off
*/
videojs.off = Events.off;
/**
* 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
* @param {Object} [hash] data hash to pass along with the event
* @return {Boolean=} Returned only if default was prevented
* @method trigger
*/
videojs.trigger = Events.trigger;
/**
* A cross-browser XMLHttpRequest wrapper. Here's a simple example:
*
* videojs.xhr({
* body: someJSONString,
* uri: "/foo",
* headers: {
* "Content-Type": "application/json"
* }
* }, function (err, resp, body) {
* // check resp.statusCode
* });
*
* Check out the [full
* documentation](https://github.com/Raynos/xhr/blob/v2.1.0/README.md)
* for more options.
*
* @param {Object} options settings for the request.
* @return {XMLHttpRequest|XDomainRequest} the request object.
* @see https://github.com/Raynos/xhr
*/
videojs.xhr = _xhr2['default'];
/**
* TextTrack class
*
* @type {Function}
*/
videojs.TextTrack = _tracksTextTrackJs2['default'];
// REMOVING: We probably should add this to the migration plugin
// // Expose but deprecate the window[componentName] method for accessing components
// Object.getOwnPropertyNames(Component.components).forEach(function(name){
// let component = Component.components[name];
//
// // A deprecation warning as the constuctor
// module.exports[name] = function(player, options, ready){
// log.warn('Using videojs.'+name+' to access the '+name+' component has been deprecated. Please use videojs.getComponent("componentName")');
//
// return new Component(player, options, ready);
// };
//
// // Allow the prototype and class methods to be accessible still this way
// // Though anything that attempts to override class methods will no longer work
// assign(module.exports[name], component);
// });
/*
* 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('videojs', [], 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;
}
exports['default'] = videojs;
module.exports = exports['default'];
},{"../../src/js/utils/merge-options.js":124,"./component":58,"./event-target":90,"./extend.js":91,"./player":98,"./plugins.js":99,"./setup":101,"./tech/flash.js":104,"./tech/html5.js":105,"./tracks/text-track.js":114,"./utils/browser.js":115,"./utils/create-deprecation-proxy.js":117,"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"./utils/format-time.js":121,"./utils/log.js":123,"./utils/stylesheet.js":125,"./utils/time-ranges.js":126,"./utils/url.js":128,"global/document":1,"lodash-compat/object/merge":40,"object.assign":43,"xhr":50}]},{},[129])(129)
});
//# sourceMappingURL=video.js.map
/* vtt.js - v0.12.1 (https://github.com/mozilla/vtt.js) built on 08-07-2015 */
(function(root) {
var vttjs = root.vttjs = {};
var cueShim = vttjs.VTTCue;
var regionShim = vttjs.VTTRegion;
var oldVTTCue = root.VTTCue;
var oldVTTRegion = root.VTTRegion;
vttjs.shim = function() {
vttjs.VTTCue = cueShim;
vttjs.VTTRegion = regionShim;
};
vttjs.restore = function() {
vttjs.VTTCue = oldVTTCue;
vttjs.VTTRegion = oldVTTRegion;
};
}(this));
/**
* Copyright 2013 vtt.js Contributors
*
* 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(root, vttjs) {
var autoKeyword = "auto";
var directionSetting = {
"": true,
"lr": true,
"rl": true
};
var alignSetting = {
"start": true,
"middle": true,
"end": true,
"left": true,
"right": true
};
function findDirectionSetting(value) {
if (typeof value !== "string") {
return false;
}
var dir = directionSetting[value.toLowerCase()];
return dir ? value.toLowerCase() : false;
}
function findAlignSetting(value) {
if (typeof value !== "string") {
return false;
}
var align = alignSetting[value.toLowerCase()];
return align ? value.toLowerCase() : false;
}
function extend(obj) {
var i = 1;
for (; i < arguments.length; i++) {
var cobj = arguments[i];
for (var p in cobj) {
obj[p] = cobj[p];
}
}
return obj;
}
function VTTCue(startTime, endTime, text) {
var cue = this;
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
var baseObj = {};
if (isIE8) {
cue = document.createElement('custom');
} else {
baseObj.enumerable = true;
}
/**
* Shim implementation specific properties. These properties are not in
* the spec.
*/
// Lets us know when the VTTCue's data has changed in such a way that we need
// to recompute its display state. This lets us compute its display state
// lazily.
cue.hasBeenReset = false;
/**
* VTTCue and TextTrackCue properties
* http://dev.w3.org/html5/webvtt/#vttcue-interface
*/
var _id = "";
var _pauseOnExit = false;
var _startTime = startTime;
var _endTime = endTime;
var _text = text;
var _region = null;
var _vertical = "";
var _snapToLines = true;
var _line = "auto";
var _lineAlign = "start";
var _position = 50;
var _positionAlign = "middle";
var _size = 50;
var _align = "middle";
Object.defineProperty(cue,
"id", extend({}, baseObj, {
get: function() {
return _id;
},
set: function(value) {
_id = "" + value;
}
}));
Object.defineProperty(cue,
"pauseOnExit", extend({}, baseObj, {
get: function() {
return _pauseOnExit;
},
set: function(value) {
_pauseOnExit = !!value;
}
}));
Object.defineProperty(cue,
"startTime", extend({}, baseObj, {
get: function() {
return _startTime;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("Start time must be set to a number.");
}
_startTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"endTime", extend({}, baseObj, {
get: function() {
return _endTime;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("End time must be set to a number.");
}
_endTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"text", extend({}, baseObj, {
get: function() {
return _text;
},
set: function(value) {
_text = "" + value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"region", extend({}, baseObj, {
get: function() {
return _region;
},
set: function(value) {
_region = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"vertical", extend({}, baseObj, {
get: function() {
return _vertical;
},
set: function(value) {
var setting = findDirectionSetting(value);
// Have to check for false because the setting an be an empty string.
if (setting === false) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_vertical = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"snapToLines", extend({}, baseObj, {
get: function() {
return _snapToLines;
},
set: function(value) {
_snapToLines = !!value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"line", extend({}, baseObj, {
get: function() {
return _line;
},
set: function(value) {
if (typeof value !== "number" && value !== autoKeyword) {
throw new SyntaxError("An invalid number or illegal string was specified.");
}
_line = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"lineAlign", extend({}, baseObj, {
get: function() {
return _lineAlign;
},
set: function(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_lineAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"position", extend({}, baseObj, {
get: function() {
return _position;
},
set: function(value) {
if (value < 0 || value > 100) {
throw new Error("Position must be between 0 and 100.");
}
_position = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"positionAlign", extend({}, baseObj, {
get: function() {
return _positionAlign;
},
set: function(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_positionAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"size", extend({}, baseObj, {
get: function() {
return _size;
},
set: function(value) {
if (value < 0 || value > 100) {
throw new Error("Size must be between 0 and 100.");
}
_size = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"align", extend({}, baseObj, {
get: function() {
return _align;
},
set: function(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_align = setting;
this.hasBeenReset = true;
}
}));
/**
* Other <track> spec defined properties
*/
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
cue.displayState = undefined;
if (isIE8) {
return cue;
}
}
/**
* VTTCue methods
*/
VTTCue.prototype.getCueAsHTML = function() {
// Assume WebVTT.convertCueToDOMTree is on the global.
return WebVTT.convertCueToDOMTree(window, this.text);
};
root.VTTCue = root.VTTCue || VTTCue;
vttjs.VTTCue = VTTCue;
}(this, (this.vttjs || {})));
/**
* Copyright 2013 vtt.js Contributors
*
* 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(root, vttjs) {
var scrollSetting = {
"": true,
"up": true
};
function findScrollSetting(value) {
if (typeof value !== "string") {
return false;
}
var scroll = scrollSetting[value.toLowerCase()];
return scroll ? value.toLowerCase() : false;
}
function isValidPercentValue(value) {
return typeof value === "number" && (value >= 0 && value <= 100);
}
// VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
function VTTRegion() {
var _width = 100;
var _lines = 3;
var _regionAnchorX = 0;
var _regionAnchorY = 100;
var _viewportAnchorX = 0;
var _viewportAnchorY = 100;
var _scroll = "";
Object.defineProperties(this, {
"width": {
enumerable: true,
get: function() {
return _width;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("Width must be between 0 and 100.");
}
_width = value;
}
},
"lines": {
enumerable: true,
get: function() {
return _lines;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("Lines must be set to a number.");
}
_lines = value;
}
},
"regionAnchorY": {
enumerable: true,
get: function() {
return _regionAnchorY;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("RegionAnchorX must be between 0 and 100.");
}
_regionAnchorY = value;
}
},
"regionAnchorX": {
enumerable: true,
get: function() {
return _regionAnchorX;
},
set: function(value) {
if(!isValidPercentValue(value)) {
throw new Error("RegionAnchorY must be between 0 and 100.");
}
_regionAnchorX = value;
}
},
"viewportAnchorY": {
enumerable: true,
get: function() {
return _viewportAnchorY;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("ViewportAnchorY must be between 0 and 100.");
}
_viewportAnchorY = value;
}
},
"viewportAnchorX": {
enumerable: true,
get: function() {
return _viewportAnchorX;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("ViewportAnchorX must be between 0 and 100.");
}
_viewportAnchorX = value;
}
},
"scroll": {
enumerable: true,
get: function() {
return _scroll;
},
set: function(value) {
var setting = findScrollSetting(value);
// Have to check for false as an empty string is a legal value.
if (setting === false) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_scroll = setting;
}
}
});
}
root.VTTRegion = root.VTTRegion || VTTRegion;
vttjs.VTTRegion = VTTRegion;
}(this, (this.vttjs || {})));
/**
* Copyright 2013 vtt.js Contributors
*
* 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.
*/
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
(function(global) {
var _objCreate = Object.create || (function() {
function F() {}
return function(o) {
if (arguments.length !== 1) {
throw new Error('Object.create shim only accepts one parameter.');
}
F.prototype = o;
return new F();
};
})();
// Creates a new ParserError object from an errorData object. The errorData
// object should have default code and message properties. The default message
// property can be overriden by passing in a message parameter.
// See ParsingError.Errors below for acceptable errors.
function ParsingError(errorData, message) {
this.name = "ParsingError";
this.code = errorData.code;
this.message = message || errorData.message;
}
ParsingError.prototype = _objCreate(Error.prototype);
ParsingError.prototype.constructor = ParsingError;
// ParsingError metadata for acceptable ParsingErrors.
ParsingError.Errors = {
BadSignature: {
code: 0,
message: "Malformed WebVTT signature."
},
BadTimeStamp: {
code: 1,
message: "Malformed time stamp."
}
};
// Try to parse input as a time stamp.
function parseTimeStamp(input) {
function computeSeconds(h, m, s, f) {
return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
}
var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
if (!m) {
return null;
}
if (m[3]) {
// Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
} else if (m[1] > 59) {
// Timestamp takes the form of [hours]:[minutes].[milliseconds]
// First position is hours as it's over 59.
return computeSeconds(m[1], m[2], 0, m[4]);
} else {
// Timestamp takes the form of [minutes]:[seconds].[milliseconds]
return computeSeconds(0, m[1], m[2], m[4]);
}
}
// A settings object holds key/value pairs and will ignore anything but the first
// assignment to a specific key.
function Settings() {
this.values = _objCreate(null);
}
Settings.prototype = {
// Only accept the first assignment to any key.
set: function(k, v) {
if (!this.get(k) && v !== "") {
this.values[k] = v;
}
},
// Return the value for a key, or a default value.
// If 'defaultKey' is passed then 'dflt' is assumed to be an object with
// a number of possible default values as properties where 'defaultKey' is
// the key of the property that will be chosen; otherwise it's assumed to be
// a single value.
get: function(k, dflt, defaultKey) {
if (defaultKey) {
return this.has(k) ? this.values[k] : dflt[defaultKey];
}
return this.has(k) ? this.values[k] : dflt;
},
// Check whether we have a value for a key.
has: function(k) {
return k in this.values;
},
// Accept a setting if its one of the given alternatives.
alt: function(k, v, a) {
for (var n = 0; n < a.length; ++n) {
if (v === a[n]) {
this.set(k, v);
break;
}
}
},
// Accept a setting if its a valid (signed) integer.
integer: function(k, v) {
if (/^-?\d+$/.test(v)) { // integer
this.set(k, parseInt(v, 10));
}
},
// Accept a setting if its a valid percentage.
percent: function(k, v) {
var m;
if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) {
v = parseFloat(v);
if (v >= 0 && v <= 100) {
this.set(k, v);
return true;
}
}
return false;
}
};
// Helper function to parse input into groups separated by 'groupDelim', and
// interprete each group as a key/value pair separated by 'keyValueDelim'.
function parseOptions(input, callback, keyValueDelim, groupDelim) {
var groups = groupDelim ? input.split(groupDelim) : [input];
for (var i in groups) {
if (typeof groups[i] !== "string") {
continue;
}
var kv = groups[i].split(keyValueDelim);
if (kv.length !== 2) {
continue;
}
var k = kv[0];
var v = kv[1];
callback(k, v);
}
}
function parseCue(input, cue, regionList) {
// Remember the original input if we need to throw an error.
var oInput = input;
// 4.1 WebVTT timestamp
function consumeTimeStamp() {
var ts = parseTimeStamp(input);
if (ts === null) {
throw new ParsingError(ParsingError.Errors.BadTimeStamp,
"Malformed timestamp: " + oInput);
}
// Remove time stamp from input.
input = input.replace(/^[^\sa-zA-Z-]+/, "");
return ts;
}
// 4.4.2 WebVTT cue settings
function consumeCueSettings(input, cue) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "region":
// Find the last region we parsed with the same region id.
for (var i = regionList.length - 1; i >= 0; i--) {
if (regionList[i].id === v) {
settings.set(k, regionList[i].region);
break;
}
}
break;
case "vertical":
settings.alt(k, v, ["rl", "lr"]);
break;
case "line":
var vals = v.split(","),
vals0 = vals[0];
settings.integer(k, vals0);
settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
settings.alt(k, vals0, ["auto"]);
if (vals.length === 2) {
settings.alt("lineAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "position":
vals = v.split(",");
settings.percent(k, vals[0]);
if (vals.length === 2) {
settings.alt("positionAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "size":
settings.percent(k, v);
break;
case "align":
settings.alt(k, v, ["start", "middle", "end", "left", "right"]);
break;
}
}, /:/, /\s/);
// Apply default values for any missing fields.
cue.region = settings.get("region", null);
cue.vertical = settings.get("vertical", "");
cue.line = settings.get("line", "auto");
cue.lineAlign = settings.get("lineAlign", "start");
cue.snapToLines = settings.get("snapToLines", true);
cue.size = settings.get("size", 100);
cue.align = settings.get("align", "middle");
cue.position = settings.get("position", {
start: 0,
left: 0,
middle: 50,
end: 100,
right: 100
}, cue.align);
cue.positionAlign = settings.get("positionAlign", {
start: "start",
left: "start",
middle: "middle",
end: "end",
right: "end"
}, cue.align);
}
function skipWhitespace() {
input = input.replace(/^\s+/, "");
}
// 4.1 WebVTT cue timings.
skipWhitespace();
cue.startTime = consumeTimeStamp(); // (1) collect cue start time
skipWhitespace();
if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->"
throw new ParsingError(ParsingError.Errors.BadTimeStamp,
"Malformed time stamp (time stamps must be separated by '-->'): " +
oInput);
}
input = input.substr(3);
skipWhitespace();
cue.endTime = consumeTimeStamp(); // (5) collect cue end time
// 4.1 WebVTT cue settings list.
skipWhitespace();
consumeCueSettings(input, cue);
}
var ESCAPE = {
"&": "&",
"<": "<",
">": ">",
"‎": "\u200e",
"‏": "\u200f",
" ": "\u00a0"
};
var TAG_NAME = {
c: "span",
i: "i",
b: "b",
u: "u",
ruby: "ruby",
rt: "rt",
v: "span",
lang: "span"
};
var TAG_ANNOTATION = {
v: "title",
lang: "lang"
};
var NEEDS_PARENT = {
rt: "ruby"
};
// Parse content into a document fragment.
function parseContent(window, input) {
function nextToken() {
// Check for end-of-string.
if (!input) {
return null;
}
// Consume 'n' characters from the input.
function consume(result) {
input = input.substr(result.length);
return result;
}
var m = input.match(/^([^<]*)(<[^>]+>?)?/);
// If there is some text before the next tag, return it, otherwise return
// the tag.
return consume(m[1] ? m[1] : m[2]);
}
// Unescape a string 's'.
function unescape1(e) {
return ESCAPE[e];
}
function unescape(s) {
while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {
s = s.replace(m[0], unescape1);
}
return s;
}
function shouldAdd(current, element) {
return !NEEDS_PARENT[element.localName] ||
NEEDS_PARENT[element.localName] === current.localName;
}
// Create an element for this tag.
function createElement(type, annotation) {
var tagName = TAG_NAME[type];
if (!tagName) {
return null;
}
var element = window.document.createElement(tagName);
element.localName = tagName;
var name = TAG_ANNOTATION[type];
if (name && annotation) {
element[name] = annotation.trim();
}
return element;
}
var rootDiv = window.document.createElement("div"),
current = rootDiv,
t,
tagStack = [];
while ((t = nextToken()) !== null) {
if (t[0] === '<') {
if (t[1] === "/") {
// If the closing tag matches, move back up to the parent node.
if (tagStack.length &&
tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
tagStack.pop();
current = current.parentNode;
}
// Otherwise just ignore the end tag.
continue;
}
var ts = parseTimeStamp(t.substr(1, t.length - 2));
var node;
if (ts) {
// Timestamps are lead nodes as well.
node = window.document.createProcessingInstruction("timestamp", ts);
current.appendChild(node);
continue;
}
var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
// If we can't parse the tag, skip to the next tag.
if (!m) {
continue;
}
// Try to construct an element, and ignore the tag if we couldn't.
node = createElement(m[1], m[3]);
if (!node) {
continue;
}
// Determine if the tag should be added based on the context of where it
// is placed in the cuetext.
if (!shouldAdd(current, node)) {
continue;
}
// Set the class list (as a list of classes, separated by space).
if (m[2]) {
node.className = m[2].substr(1).replace('.', ' ');
}
// Append the node to the current node, and enter the scope of the new
// node.
tagStack.push(m[1]);
current.appendChild(node);
current = node;
continue;
}
// Text nodes are leaf nodes.
current.appendChild(window.document.createTextNode(unescape(t)));
}
return rootDiv;
}
// This is a list of all the Unicode characters that have a strong
// right-to-left category. What this means is that these characters are
// written right-to-left for sure. It was generated by pulling all the strong
// right-to-left characters out of the Unicode data table. That table can
// found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1,
0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA,
0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3,
0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1,
0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F,
0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628,
0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631,
0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A,
0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643,
0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E,
0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678,
0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681,
0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A,
0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693,
0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C,
0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5,
0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE,
0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7,
0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0,
0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9,
0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2,
0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB,
0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704,
0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D,
0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718,
0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721,
0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A,
0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750,
0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759,
0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762,
0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B,
0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774,
0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D,
0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786,
0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F,
0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798,
0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1,
0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3,
0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC,
0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5,
0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE,
0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7,
0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802,
0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B,
0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814,
0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834,
0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D,
0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847,
0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850,
0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E,
0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9,
0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22,
0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C,
0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35,
0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41,
0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C,
0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55,
0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E,
0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67,
0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70,
0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79,
0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82,
0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B,
0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94,
0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D,
0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6,
0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF,
0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8,
0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1,
0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB,
0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4,
0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED,
0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6,
0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF,
0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08,
0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11,
0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A,
0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23,
0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C,
0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35,
0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E,
0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47,
0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50,
0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59,
0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62,
0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B,
0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74,
0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D,
0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86,
0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F,
0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98,
0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1,
0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA,
0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3,
0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC,
0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5,
0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE,
0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7,
0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0,
0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9,
0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2,
0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB,
0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04,
0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D,
0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16,
0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F,
0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28,
0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31,
0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A,
0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55,
0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E,
0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67,
0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70,
0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79,
0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82,
0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B,
0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96,
0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F,
0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8,
0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1,
0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA,
0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3,
0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4,
0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70,
0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A,
0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83,
0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C,
0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95,
0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E,
0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7,
0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0,
0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9,
0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2,
0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB,
0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4,
0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD,
0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6,
0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF,
0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8,
0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803,
0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E,
0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816,
0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E,
0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826,
0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E,
0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837,
0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844,
0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C,
0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854,
0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D,
0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905,
0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D,
0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915,
0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921,
0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929,
0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931,
0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939,
0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986,
0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E,
0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996,
0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E,
0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6,
0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE,
0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6,
0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13,
0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D,
0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25,
0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D,
0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41,
0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51,
0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60,
0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68,
0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70,
0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78,
0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00,
0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08,
0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10,
0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18,
0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20,
0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28,
0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30,
0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42,
0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A,
0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52,
0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C,
0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64,
0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C,
0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79,
0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01,
0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09,
0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11,
0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19,
0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21,
0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29,
0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31,
0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39,
0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41,
0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00,
0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09,
0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11,
0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19,
0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22,
0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E,
0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37,
0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E,
0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D,
0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A,
0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74,
0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E,
0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87,
0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90,
0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98,
0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6,
0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF,
0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7,
0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD];
function determineBidi(cueDiv) {
var nodeStack = [],
text = "",
charCode;
if (!cueDiv || !cueDiv.childNodes) {
return "ltr";
}
function pushNodes(nodeStack, node) {
for (var i = node.childNodes.length - 1; i >= 0; i--) {
nodeStack.push(node.childNodes[i]);
}
}
function nextTextNode(nodeStack) {
if (!nodeStack || !nodeStack.length) {
return null;
}
var node = nodeStack.pop(),
text = node.textContent || node.innerText;
if (text) {
// TODO: This should match all unicode type B characters (paragraph
// separator characters). See issue #115.
var m = text.match(/^.*(\n|\r)/);
if (m) {
nodeStack.length = 0;
return m[0];
}
return text;
}
if (node.tagName === "ruby") {
return nextTextNode(nodeStack);
}
if (node.childNodes) {
pushNodes(nodeStack, node);
return nextTextNode(nodeStack);
}
}
pushNodes(nodeStack, cueDiv);
while ((text = nextTextNode(nodeStack))) {
for (var i = 0; i < text.length; i++) {
charCode = text.charCodeAt(i);
for (var j = 0; j < strongRTLChars.length; j++) {
if (strongRTLChars[j] === charCode) {
return "rtl";
}
}
}
}
return "ltr";
}
function computeLinePos(cue) {
if (typeof cue.line === "number" &&
(cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) {
return cue.line;
}
if (!cue.track || !cue.track.textTrackList ||
!cue.track.textTrackList.mediaElement) {
return -1;
}
var track = cue.track,
trackList = track.textTrackList,
count = 0;
for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
if (trackList[i].mode === "showing") {
count++;
}
}
return ++count * -1;
}
function StyleBox() {
}
// Apply styles to a div. If there is no div passed then it defaults to the
// div on 'this'.
StyleBox.prototype.applyStyles = function(styles, div) {
div = div || this.div;
for (var prop in styles) {
if (styles.hasOwnProperty(prop)) {
div.style[prop] = styles[prop];
}
}
};
StyleBox.prototype.formatStyle = function(val, unit) {
return val === 0 ? 0 : val + unit;
};
// Constructs the computed display state of the cue (a div). Places the div
// into the overlay which should be a block level element (usually a div).
function CueStyleBox(window, cue, styleOptions) {
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
var color = "rgba(255, 255, 255, 1)";
var backgroundColor = "rgba(0, 0, 0, 0.8)";
if (isIE8) {
color = "rgb(255, 255, 255)";
backgroundColor = "rgb(0, 0, 0)";
}
StyleBox.call(this);
this.cue = cue;
// Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
// have inline positioning and will function as the cue background box.
this.cueDiv = parseContent(window, cue.text);
var styles = {
color: color,
backgroundColor: backgroundColor,
position: "relative",
left: 0,
right: 0,
top: 0,
bottom: 0,
display: "inline"
};
if (!isIE8) {
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl";
styles.unicodeBidi = "plaintext";
}
this.applyStyles(styles, this.cueDiv);
// Create an absolutely positioned div that will be used to position the cue
// div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
// mirrors of them except "middle" which is "center" in CSS.
this.div = window.document.createElement("div");
styles = {
textAlign: cue.align === "middle" ? "center" : cue.align,
font: styleOptions.font,
whiteSpace: "pre-line",
position: "absolute"
};
if (!isIE8) {
styles.direction = determineBidi(this.cueDiv);
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl".
stylesunicodeBidi = "plaintext";
}
this.applyStyles(styles);
this.div.appendChild(this.cueDiv);
// Calculate the distance from the reference edge of the viewport to the text
// position of the cue box. The reference edge will be resolved later when
// the box orientation styles are applied.
var textPos = 0;
switch (cue.positionAlign) {
case "start":
textPos = cue.position;
break;
case "middle":
textPos = cue.position - (cue.size / 2);
break;
case "end":
textPos = cue.position - cue.size;
break;
}
// Horizontal box orientation; textPos is the distance from the left edge of the
// area to the left edge of the box and cue.size is the distance extending to
// the right from there.
if (cue.vertical === "") {
this.applyStyles({
left: this.formatStyle(textPos, "%"),
width: this.formatStyle(cue.size, "%")
});
// Vertical box orientation; textPos is the distance from the top edge of the
// area to the top edge of the box and cue.size is the height extending
// downwards from there.
} else {
this.applyStyles({
top: this.formatStyle(textPos, "%"),
height: this.formatStyle(cue.size, "%")
});
}
this.move = function(box) {
this.applyStyles({
top: this.formatStyle(box.top, "px"),
bottom: this.formatStyle(box.bottom, "px"),
left: this.formatStyle(box.left, "px"),
right: this.formatStyle(box.right, "px"),
height: this.formatStyle(box.height, "px"),
width: this.formatStyle(box.width, "px")
});
};
}
CueStyleBox.prototype = _objCreate(StyleBox.prototype);
CueStyleBox.prototype.constructor = CueStyleBox;
// Represents the co-ordinates of an Element in a way that we can easily
// compute things with such as if it overlaps or intersects with another Element.
// Can initialize it with either a StyleBox or another BoxPosition.
function BoxPosition(obj) {
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
// Either a BoxPosition was passed in and we need to copy it, or a StyleBox
// was passed in and we need to copy the results of 'getBoundingClientRect'
// as the object returned is readonly. All co-ordinate values are in reference
// to the viewport origin (top left).
var lh, height, width, top;
if (obj.div) {
height = obj.div.offsetHeight;
width = obj.div.offsetWidth;
top = obj.div.offsetTop;
var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
rects.getClientRects && rects.getClientRects();
obj = obj.div.getBoundingClientRect();
// In certain cases the outter div will be slightly larger then the sum of
// the inner div's lines. This could be due to bold text, etc, on some platforms.
// In this case we should get the average line height and use that. This will
// result in the desired behaviour.
lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
: 0;
}
this.left = obj.left;
this.right = obj.right;
this.top = obj.top || top;
this.height = obj.height || height;
this.bottom = obj.bottom || (top + (obj.height || height));
this.width = obj.width || width;
this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
if (isIE8 && !this.lineHeight) {
this.lineHeight = 13;
}
}
// Move the box along a particular axis. Optionally pass in an amount to move
// the box. If no amount is passed then the default is the line height of the
// box.
BoxPosition.prototype.move = function(axis, toMove) {
toMove = toMove !== undefined ? toMove : this.lineHeight;
switch (axis) {
case "+x":
this.left += toMove;
this.right += toMove;
break;
case "-x":
this.left -= toMove;
this.right -= toMove;
break;
case "+y":
this.top += toMove;
this.bottom += toMove;
break;
case "-y":
this.top -= toMove;
this.bottom -= toMove;
break;
}
};
// Check if this box overlaps another box, b2.
BoxPosition.prototype.overlaps = function(b2) {
return this.left < b2.right &&
this.right > b2.left &&
this.top < b2.bottom &&
this.bottom > b2.top;
};
// Check if this box overlaps any other boxes in boxes.
BoxPosition.prototype.overlapsAny = function(boxes) {
for (var i = 0; i < boxes.length; i++) {
if (this.overlaps(boxes[i])) {
return true;
}
}
return false;
};
// Check if this box is within another box.
BoxPosition.prototype.within = function(container) {
return this.top >= container.top &&
this.bottom <= container.bottom &&
this.left >= container.left &&
this.right <= container.right;
};
// Check if this box is entirely within the container or it is overlapping
// on the edge opposite of the axis direction passed. For example, if "+x" is
// passed and the box is overlapping on the left edge of the container, then
// return true.
BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
switch (axis) {
case "+x":
return this.left < container.left;
case "-x":
return this.right > container.right;
case "+y":
return this.top < container.top;
case "-y":
return this.bottom > container.bottom;
}
};
// Find the percentage of the area that this box is overlapping with another
// box.
BoxPosition.prototype.intersectPercentage = function(b2) {
var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
intersectArea = x * y;
return intersectArea / (this.height * this.width);
};
// Convert the positions from this box to CSS compatible positions using
// the reference container's positions. This has to be done because this
// box's positions are in reference to the viewport origin, whereas, CSS
// values are in referecne to their respective edges.
BoxPosition.prototype.toCSSCompatValues = function(reference) {
return {
top: this.top - reference.top,
bottom: reference.bottom - this.bottom,
left: this.left - reference.left,
right: reference.right - this.right,
height: this.height,
width: this.width
};
};
// Get an object that represents the box's position without anything extra.
// Can pass a StyleBox, HTMLElement, or another BoxPositon.
BoxPosition.getSimpleBoxPosition = function(obj) {
var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
obj = obj.div ? obj.div.getBoundingClientRect() :
obj.tagName ? obj.getBoundingClientRect() : obj;
var ret = {
left: obj.left,
right: obj.right,
top: obj.top || top,
height: obj.height || height,
bottom: obj.bottom || (top + (obj.height || height)),
width: obj.width || width
};
return ret;
};
// Move a StyleBox to its specified, or next best, position. The containerBox
// is the box that contains the StyleBox, such as a div. boxPositions are
// a list of other boxes that the styleBox can't overlap with.
function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
// Find the best position for a cue box, b, on the video. The axis parameter
// is a list of axis, the order of which, it will move the box along. For example:
// Passing ["+x", "-x"] will move the box first along the x axis in the positive
// direction. If it doesn't find a good position for it there it will then move
// it along the x axis in the negative direction.
function findBestPosition(b, axis) {
var bestPosition,
specifiedPosition = new BoxPosition(b),
percentage = 1; // Highest possible so the first thing we get is better.
for (var i = 0; i < axis.length; i++) {
while (b.overlapsOppositeAxis(containerBox, axis[i]) ||
(b.within(containerBox) && b.overlapsAny(boxPositions))) {
b.move(axis[i]);
}
// We found a spot where we aren't overlapping anything. This is our
// best position.
if (b.within(containerBox)) {
return b;
}
var p = b.intersectPercentage(containerBox);
// If we're outside the container box less then we were on our last try
// then remember this position as the best position.
if (percentage > p) {
bestPosition = new BoxPosition(b);
percentage = p;
}
// Reset the box position to the specified position.
b = new BoxPosition(specifiedPosition);
}
return bestPosition || specifiedPosition;
}
var boxPosition = new BoxPosition(styleBox),
cue = styleBox.cue,
linePos = computeLinePos(cue),
axis = [];
// If we have a line number to align the cue to.
if (cue.snapToLines) {
var size;
switch (cue.vertical) {
case "":
axis = [ "+y", "-y" ];
size = "height";
break;
case "rl":
axis = [ "+x", "-x" ];
size = "width";
break;
case "lr":
axis = [ "-x", "+x" ];
size = "width";
break;
}
var step = boxPosition.lineHeight,
position = step * Math.round(linePos),
maxPosition = containerBox[size] + step,
initialAxis = axis[0];
// If the specified intial position is greater then the max position then
// clamp the box to the amount of steps it would take for the box to
// reach the max position.
if (Math.abs(position) > maxPosition) {
position = position < 0 ? -1 : 1;
position *= Math.ceil(maxPosition / step) * step;
}
// If computed line position returns negative then line numbers are
// relative to the bottom of the video instead of the top. Therefore, we
// need to increase our initial position by the length or width of the
// video, depending on the writing direction, and reverse our axis directions.
if (linePos < 0) {
position += cue.vertical === "" ? containerBox.height : containerBox.width;
axis = axis.reverse();
}
// Move the box to the specified position. This may not be its best
// position.
boxPosition.move(initialAxis, position);
} else {
// If we have a percentage line value for the cue.
var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;
switch (cue.lineAlign) {
case "middle":
linePos -= (calculatedPercentage / 2);
break;
case "end":
linePos -= calculatedPercentage;
break;
}
// Apply initial line position to the cue box.
switch (cue.vertical) {
case "":
styleBox.applyStyles({
top: styleBox.formatStyle(linePos, "%")
});
break;
case "rl":
styleBox.applyStyles({
left: styleBox.formatStyle(linePos, "%")
});
break;
case "lr":
styleBox.applyStyles({
right: styleBox.formatStyle(linePos, "%")
});
break;
}
axis = [ "+y", "-x", "+x", "-y" ];
// Get the box position again after we've applied the specified positioning
// to it.
boxPosition = new BoxPosition(styleBox);
}
var bestPosition = findBestPosition(boxPosition, axis);
styleBox.move(bestPosition.toCSSCompatValues(containerBox));
}
function WebVTT() {
// Nothing
}
// Helper to allow strings to be decoded instead of the default binary utf8 data.
WebVTT.StringDecoder = function() {
return {
decode: function(data) {
if (!data) {
return "";
}
if (typeof data !== "string") {
throw new Error("Error - expected string data.");
}
return decodeURIComponent(encodeURIComponent(data));
}
};
};
WebVTT.convertCueToDOMTree = function(window, cuetext) {
if (!window || !cuetext) {
return null;
}
return parseContent(window, cuetext);
};
var FONT_SIZE_PERCENT = 0.05;
var FONT_STYLE = "sans-serif";
var CUE_BACKGROUND_PADDING = "1.5%";
// Runs the processing model over the cues and regions passed to it.
// @param overlay A block level element (usually a div) that the computed cues
// and regions will be placed into.
WebVTT.processCues = function(window, cues, overlay) {
if (!window || !cues || !overlay) {
return null;
}
// Remove all previous children.
while (overlay.firstChild) {
overlay.removeChild(overlay.firstChild);
}
var paddedOverlay = window.document.createElement("div");
paddedOverlay.style.position = "absolute";
paddedOverlay.style.left = "0";
paddedOverlay.style.right = "0";
paddedOverlay.style.top = "0";
paddedOverlay.style.bottom = "0";
paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
overlay.appendChild(paddedOverlay);
// Determine if we need to compute the display states of the cues. This could
// be the case if a cue's state has been changed since the last computation or
// if it has not been computed yet.
function shouldCompute(cues) {
for (var i = 0; i < cues.length; i++) {
if (cues[i].hasBeenReset || !cues[i].displayState) {
return true;
}
}
return false;
}
// We don't need to recompute the cues' display states. Just reuse them.
if (!shouldCompute(cues)) {
for (var i = 0; i < cues.length; i++) {
paddedOverlay.appendChild(cues[i].displayState);
}
return;
}
var boxPositions = [],
containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
var styleOptions = {
font: fontSize + "px " + FONT_STYLE
};
(function() {
var styleBox, cue;
for (var i = 0; i < cues.length; i++) {
cue = cues[i];
// Compute the intial position and styles of the cue div.
styleBox = new CueStyleBox(window, cue, styleOptions);
paddedOverlay.appendChild(styleBox.div);
// Move the cue div to it's correct line position.
moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
// Remember the computed div so that we don't have to recompute it later
// if we don't have too.
cue.displayState = styleBox.div;
boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
}
})();
};
WebVTT.Parser = function(window, vttjs, decoder) {
if (!decoder) {
decoder = vttjs;
vttjs = {};
}
if (!vttjs) {
vttjs = {};
}
this.window = window;
this.vttjs = vttjs;
this.state = "INITIAL";
this.buffer = "";
this.decoder = decoder || new TextDecoder("utf8");
this.regionList = [];
};
WebVTT.Parser.prototype = {
// If the error is a ParsingError then report it to the consumer if
// possible. If it's not a ParsingError then throw it like normal.
reportOrThrowError: function(e) {
if (e instanceof ParsingError) {
this.onparsingerror && this.onparsingerror(e);
} else {
throw e;
}
},
parse: function (data) {
var self = this;
// If there is no data then we won't decode it, but will just try to parse
// whatever is in buffer already. This may occur in circumstances, for
// example when flush() is called.
if (data) {
// Try to decode the data that we received.
self.buffer += self.decoder.decode(data, {stream: true});
}
function collectNextLine() {
var buffer = self.buffer;
var pos = 0;
while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
++pos;
}
var line = buffer.substr(0, pos);
// Advance the buffer early in case we fail below.
if (buffer[pos] === '\r') {
++pos;
}
if (buffer[pos] === '\n') {
++pos;
}
self.buffer = buffer.substr(pos);
return line;
}
// 3.4 WebVTT region and WebVTT region settings syntax
function parseRegion(input) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "id":
settings.set(k, v);
break;
case "width":
settings.percent(k, v);
break;
case "lines":
settings.integer(k, v);
break;
case "regionanchor":
case "viewportanchor":
var xy = v.split(',');
if (xy.length !== 2) {
break;
}
// We have to make sure both x and y parse, so use a temporary
// settings object here.
var anchor = new Settings();
anchor.percent("x", xy[0]);
anchor.percent("y", xy[1]);
if (!anchor.has("x") || !anchor.has("y")) {
break;
}
settings.set(k + "X", anchor.get("x"));
settings.set(k + "Y", anchor.get("y"));
break;
case "scroll":
settings.alt(k, v, ["up"]);
break;
}
}, /=/, /\s/);
// Create the region, using default values for any values that were not
// specified.
if (settings.has("id")) {
var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
region.width = settings.get("width", 100);
region.lines = settings.get("lines", 3);
region.regionAnchorX = settings.get("regionanchorX", 0);
region.regionAnchorY = settings.get("regionanchorY", 100);
region.viewportAnchorX = settings.get("viewportanchorX", 0);
region.viewportAnchorY = settings.get("viewportanchorY", 100);
region.scroll = settings.get("scroll", "");
// Register the region.
self.onregion && self.onregion(region);
// Remember the VTTRegion for later in case we parse any VTTCues that
// reference it.
self.regionList.push({
id: settings.get("id"),
region: region
});
}
}
// 3.2 WebVTT metadata header syntax
function parseHeader(input) {
parseOptions(input, function (k, v) {
switch (k) {
case "Region":
// 3.3 WebVTT region metadata header syntax
parseRegion(v);
break;
}
}, /:/);
}
// 5.1 WebVTT file parsing.
try {
var line;
if (self.state === "INITIAL") {
// We can't start parsing until we have the first line.
if (!/\r\n|\n/.test(self.buffer)) {
return this;
}
line = collectNextLine();
var m = line.match(/^WEBVTT([ \t].*)?$/);
if (!m || !m[0]) {
throw new ParsingError(ParsingError.Errors.BadSignature);
}
self.state = "HEADER";
}
var alreadyCollectedLine = false;
while (self.buffer) {
// We can't parse a line until we have the full line.
if (!/\r\n|\n/.test(self.buffer)) {
return this;
}
if (!alreadyCollectedLine) {
line = collectNextLine();
} else {
alreadyCollectedLine = false;
}
switch (self.state) {
case "HEADER":
// 13-18 - Allow a header (metadata) under the WEBVTT line.
if (/:/.test(line)) {
parseHeader(line);
} else if (!line) {
// An empty line terminates the header and starts the body (cues).
self.state = "ID";
}
continue;
case "NOTE":
// Ignore NOTE blocks.
if (!line) {
self.state = "ID";
}
continue;
case "ID":
// Check for the start of NOTE blocks.
if (/^NOTE($|[ \t])/.test(line)) {
self.state = "NOTE";
break;
}
// 19-29 - Allow any number of line terminators, then initialize new cue values.
if (!line) {
continue;
}
self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
self.state = "CUE";
// 30-39 - Check if self line contains an optional identifier or timing data.
if (line.indexOf("-->") === -1) {
self.cue.id = line;
continue;
}
// Process line as start of a cue.
/*falls through*/
case "CUE":
// 40 - Collect cue timings and settings.
try {
parseCue(line, self.cue, self.regionList);
} catch (e) {
self.reportOrThrowError(e);
// In case of an error ignore rest of the cue.
self.cue = null;
self.state = "BADCUE";
continue;
}
self.state = "CUETEXT";
continue;
case "CUETEXT":
var hasSubstring = line.indexOf("-->") !== -1;
// 34 - If we have an empty line then report the cue.
// 35 - If we have the special substring '-->' then report the cue,
// but do not collect the line as we need to process the current
// one as a new cue.
if (!line || hasSubstring && (alreadyCollectedLine = true)) {
// We are done parsing self cue.
self.oncue && self.oncue(self.cue);
self.cue = null;
self.state = "ID";
continue;
}
if (self.cue.text) {
self.cue.text += "\n";
}
self.cue.text += line;
continue;
case "BADCUE": // BADCUE
// 54-62 - Collect and discard the remaining cue.
if (!line) {
self.state = "ID";
}
continue;
}
}
} catch (e) {
self.reportOrThrowError(e);
// If we are currently parsing a cue, report what we have.
if (self.state === "CUETEXT" && self.cue && self.oncue) {
self.oncue(self.cue);
}
self.cue = null;
// Enter BADWEBVTT state if header was not parsed correctly otherwise
// another exception occurred so enter BADCUE state.
self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
}
return this;
},
flush: function () {
var self = this;
try {
// Finish decoding the stream.
self.buffer += self.decoder.decode();
// Synthesize the end of the current cue or region.
if (self.cue || self.state === "HEADER") {
self.buffer += "\n\n";
self.parse();
}
// If we've flushed, parsed, and we're still on the INITIAL state then
// that means we don't have enough of the stream to parse the first
// line.
if (self.state === "INITIAL") {
throw new ParsingError(ParsingError.Errors.BadSignature);
}
} catch(e) {
self.reportOrThrowError(e);
}
self.onflush && self.onflush();
return this;
}
};
global.WebVTT = WebVTT;
}(this, (this.vttjs || {})));
|
app/scripts/components/DocsManagement/__tests__/Updater-test.js | andela-ekupara/DcManFrontEnd | import React from 'react';
import expect from 'expect';
import sinon from 'sinon';
import {mount,shallow} from 'enzyme';
import * as DocActions from '../../../actions/DocumentActions';
import DocStore from '../../../stores/DocumentStore';
import Updater from '../Updater.jsx';
describe('Document Update Component Tests', function() {
describe('Component Rendering Tests', function() {
var component;
beforeEach(() => {
let data = {
title: 'Test',
content: 'Doc to be updated',
accessLevel: 'private'
}
component = shallow(<Updater doc={data} />);
});
it('renders the component correctly', function() {
expect(component.hasClass('row')).toBe(true);
expect(component.find('.input-field').length).toEqual(2);
expect(component.find('textarea').length).toEqual(1);
component.unmount();
});
it('initializes with the correct state', function() {
expect(component.state().doc.accessLevel).toBe('private');
expect(component.state().doc.content).toBe('Doc to be updated');
expect(component.state().doc.title).toBe('Test');
component.unmount();
});
});
describe('Component LifeCycle Tests', function() {
var component;
beforeEach(() => {
let data = {
title: 'Test',
content: 'Doc to be updated',
accessLevel: 'private'
};
window.Materialize.toast = sinon.spy();
component = mount(<Updater doc={data} />);
});
it('Calls componentWillMount', function() {
sinon.spy(Updater.prototype, 'componentWillMount');
let data = {
title: 'Test',
content: 'Doc to be updated',
accessLevel: 'private'
};
sinon.spy(DocStore, 'addChangeListener');
component = mount(<Updater doc={data} />);
expect(Updater.prototype.componentWillMount.called).toBe(true);
expect(DocStore.addChangeListener.called).toBe(true);
Updater.prototype.componentWillMount.restore();
DocStore.addChangeListener.restore();
component.unmount();
});
it('Calls componentWillUnmount', function() {
sinon.spy(Updater.prototype, 'componentWillUnmount');
sinon.spy(DocStore, 'removeChangeListener');
component.unmount();
expect(Updater.prototype.componentWillUnmount.called).toBe(true);
expect(DocStore.removeChangeListener.called).toBe(true);
Updater.prototype.componentWillUnmount.restore();
DocStore.removeChangeListener.restore();
});
});
describe('Component Method Tests', function() {
window.Materialize = {};
var component;
beforeEach(() => {
let data = {
title: 'Test',
content: 'Doc to be updated',
accessLevel: 'private'
}
window.Materialize.toast = sinon.spy();
component = mount(<Updater doc={data} />);
});
afterEach(function() {
component.unmount();
});
it('handleDocUpdate no error', function() {
sinon.stub(DocActions, 'getUserDocs').returns({});
let instance = component.instance();
let data = {
doc: {
title: 'Test title',
content: 'edwin',
accessLevel: 'private'
},
message: 'Update success '
};
DocStore.setDocUpdateResult(data);
sinon.spy(instance, 'handleDocUpdate');
sinon.spy(DocStore, 'getDocUpdateResult');
sinon.spy(localStorage, 'getItem');
instance.handleDocUpdate();
expect(DocStore.getDocUpdateResult.called).toBe(true);
expect(window.Materialize.toast.withArgs(data.message).called).toBe(true);
expect(localStorage.getItem.withArgs('token').called).toBe(true);
instance.handleDocUpdate.restore();
DocStore.getDocUpdateResult.restore();
DocActions.getUserDocs.restore();
localStorage.getItem.restore();
});
it('handleDocUpdate error handling', function() {
sinon.stub(DocActions, 'getUserDocs').returns({});
let instance = component.instance();
let data = {
error: {
message: 'update error'
}
};
DocStore.setDocUpdateResult(data);
sinon.spy(instance, 'handleDocUpdate');
sinon.spy(DocStore, 'getDocUpdateResult');
instance.handleDocUpdate();
expect(DocStore.getDocUpdateResult.called).toBe(true);
expect(window.Materialize.toast.withArgs(data.error.message).called).toBe(true);
instance.handleDocUpdate.restore();
DocStore.getDocUpdateResult.restore();
DocActions.getUserDocs.restore();
});
it('should call handleSubmit with update data', function() {
sinon.stub(DocActions, 'updateDoc').returns({});
let instance = component.instance();
component.setState({
doc: {
title: 'Update Test',
content: 'This is a test doc',
accessLevel: 'public'
}
});
// simulate the Update event
let updateEvent = {
preventDefault: function() {}
};
sinon.spy(instance, 'handleSubmit');
sinon.spy(updateEvent, 'preventDefault');
component.find('form').simulate('submit', updateEvent);
expect(updateEvent.preventDefault.called).toBe(true);
expect(DocActions.updateDoc.called).toBe(true);
DocActions.updateDoc.restore();
});
it('should correctly update the state', function() {
let fieldChangeEvent = {
target: {
name: 'title',
value: 'Test Document'
},
preventDefault: function() {}
};
const instance = component.instance();
sinon.spy(instance, 'handleFieldChange');
instance.handleFieldChange(fieldChangeEvent);
expect(component.state().doc[fieldChangeEvent.target.name]).toBe(fieldChangeEvent.target.value);
instance.handleFieldChange.restore();
});
});
});
|
introToDynamicHTML/bower_components/backbone/backbone.js | sidathgithub/screencasts | // Backbone.js 1.1.2
// (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://backbonejs.org
(function(root, factory) {
// Set up Backbone appropriately for the environment. Start with AMD.
if (typeof define === 'function' && define.amd) {
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global Backbone.
root.Backbone = factory(root, exports, _, $);
});
// Next for Node.js or CommonJS. jQuery may not be needed as a module.
} else if (typeof exports !== 'undefined') {
var _ = require('underscore');
factory(root, exports, _);
// Finally, as a browser global.
} else {
root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
}
}(this, function(root, Backbone, _, $) {
// Initial Setup
// -------------
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
// Create local references to array methods we'll want to use later.
var array = [];
var push = array.push;
var slice = array.slice;
var splice = array.splice;
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '1.1.2';
// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
// the `$` variable.
Backbone.$ = $;
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
// will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
// set a `X-Http-Method-Override` header.
Backbone.emulateHTTP = false;
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
// `application/json` requests ... will encode the body as
// `application/x-www-form-urlencoded` instead and will send the model in a
// form param named `model`.
Backbone.emulateJSON = false;
// Backbone.Events
// ---------------
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback
// functions to an event; `trigger`-ing an event fires all callbacks in
// succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = Backbone.Events = {
// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},
// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, it will be removed.
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = void 0;
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events = this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo) return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object') callback = this;
if (obj) (listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
}
return this;
}
};
// Regular expression used to split event strings.
var eventSplitter = /\s+/;
// Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
// Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
// Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
}
};
var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
_.each(listenMethods, function(implementation, method) {
Events[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object') callback = this;
obj[implementation](name, callback, this);
return this;
};
});
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Allow the `Backbone` object to serve as a global event bus, for folks who
// want global "pubsub" in a convenient place.
_.extend(Backbone, Events);
// Backbone.Model
// --------------
// Backbone **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.
// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.
var Model = Backbone.Model = function(attributes, options) {
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// The value returned during the last failed validation.
validationError: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.clone(this.attributes);
},
// Proxy `Backbone.sync` by default -- but override this if you need
// custom syncing semantics for *this* particular model.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Get the value of an attribute.
get: function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape: function(attr) {
return _.escape(this.get(attr));
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function(attr) {
return this.get(attr) != null;
},
// Set a hash of model attributes on the object, firing `"change"`. This is
// the core primitive operation of a model, updating the data and notifying
// anyone who needs to know about the change in state. The heart of the beast.
set: function(key, val, options) {
var attr, attrs, unset, changes, silent, changing, prev, current;
if (key == null) return this;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Run validation.
if (!this._validate(attrs, options)) return false;
// Extract attributes and options.
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = _.clone(this.attributes);
this.changed = {};
}
current = this.attributes, prev = this._previousAttributes;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// For each `set` attribute, update or delete the current value.
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(current[attr], val)) changes.push(attr);
if (!_.isEqual(prev[attr], val)) {
this.changed[attr] = val;
} else {
delete this.changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
}
// Trigger all relevant attribute changes.
if (!silent) {
if (changes.length) this._pending = options;
for (var i = 0, l = changes.length; i < l; i++) {
this.trigger('change:' + changes[i], this, current[changes[i]], options);
}
}
// You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
options = this._pending;
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
// Remove an attribute from the model, firing `"change"`. `unset` is a noop
// if the attribute doesn't exist.
unset: function(attr, options) {
return this.set(attr, void 0, _.extend({}, options, {unset: true}));
},
// Clear all attributes on the model, firing `"change"`.
clear: function(options) {
var attrs = {};
for (var key in this.attributes) attrs[key] = void 0;
return this.set(attrs, _.extend({}, options, {unset: true}));
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function(attr) {
if (attr == null) return !_.isEmpty(this.changed);
return _.has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
var val, changed = false;
var old = this._changing ? this._previousAttributes : this.attributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (attr == null || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overridden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
if (!model.set(model.parse(resp, options), options)) return false;
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function(key, val, options) {
var attrs, method, xhr, attributes = this.attributes;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options = _.extend({validate: true}, options);
// If we're not waiting and attributes exist, save acts as
// `set(attr).save(null, opts)` with validation. Otherwise, check if
// the model will be valid when the attributes, if any, are set.
if (attrs && !options.wait) {
if (!this.set(attrs, options)) return false;
} else {
if (!this._validate(attrs, options)) return false;
}
// Set temporary attributes if `{wait: true}`.
if (attrs && options.wait) {
this.attributes = _.extend({}, attributes, attrs);
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
// Ensure attributes are restored during synchronous saves.
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
if (method === 'patch') options.attrs = attrs;
xhr = this.sync(method, this, options);
// Restore attributes.
if (attrs && options.wait) this.attributes = attributes;
return xhr;
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var destroy = function() {
model.trigger('destroy', model, model.collection, options);
};
options.success = function(resp) {
if (options.wait || model.isNew()) destroy();
if (success) success(model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
};
if (this.isNew()) {
options.success();
return false;
}
wrapError(this, options);
var xhr = this.sync('delete', this, options);
if (!options.wait) destroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function() {
var base =
_.result(this, 'urlRoot') ||
_.result(this.collection, 'url') ||
urlError();
if (this.isNew()) return base;
return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function(resp, options) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function() {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return !this.has(this.idAttribute);
},
// Check if the model is currently in a valid state.
isValid: function(options) {
return this._validate({}, _.extend(options || {}, { validate: true }));
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function(attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
return false;
}
});
// Underscore methods that we want to implement on the Model.
var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
// Mix in each Underscore method as a proxy to `Model#attributes`.
_.each(modelMethods, function(method) {
Model.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.attributes);
return _[method].apply(_, args);
};
});
// Backbone.Collection
// -------------------
// If models tend to represent a single row of data, a Backbone Collection is
// more analagous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.
// Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.model) this.model = options.model;
if (options.comparator !== void 0) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, _.extend({silent: true}, options));
};
// Default options for `Collection#set`.
var setOptions = {add: true, remove: true, merge: true};
var addOptions = {add: true, remove: false};
// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function(options) {
return this.map(function(model){ return model.toJSON(options); });
},
// Proxy `Backbone.sync` by default.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Add a model, or list of models to the set.
add: function(models, options) {
return this.set(models, _.extend({merge: false}, options, addOptions));
},
// Remove a model, or a list of models from the set.
remove: function(models, options) {
var singular = !_.isArray(models);
models = singular ? [models] : _.clone(models);
options || (options = {});
var i, l, index, model;
for (i = 0, l = models.length; i < l; i++) {
model = models[i] = this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byId[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model, options);
}
return singular ? models[0] : models;
},
// Update a collection by `set`-ing a new list of models, adding new ones,
// removing models that are no longer present, and merging models that
// already exist in the collection, as necessary. Similar to **Model#set**,
// the core operation for updating the data contained by the collection.
set: function(models, options) {
options = _.defaults({}, options, setOptions);
if (options.parse) models = this.parse(models, options);
var singular = !_.isArray(models);
models = singular ? (models ? [models] : []) : _.clone(models);
var i, l, id, model, attrs, existing, sort;
var at = options.at;
var targetModel = this.model;
var sortable = this.comparator && (at == null) && options.sort !== false;
var sortAttr = _.isString(this.comparator) ? this.comparator : null;
var toAdd = [], toRemove = [], modelMap = {};
var add = options.add, merge = options.merge, remove = options.remove;
var order = !sortable && add && remove ? [] : false;
// Turn bare objects into model references, and prevent invalid models
// from being added.
for (i = 0, l = models.length; i < l; i++) {
attrs = models[i] || {};
if (attrs instanceof Model) {
id = model = attrs;
} else {
id = attrs[targetModel.prototype.idAttribute || 'id'];
}
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
if (existing = this.get(id)) {
if (remove) modelMap[existing.cid] = true;
if (merge) {
attrs = attrs === model ? model.attributes : attrs;
if (options.parse) attrs = existing.parse(attrs, options);
existing.set(attrs, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
}
models[i] = existing;
// If this is a new, valid model, push it to the `toAdd` list.
} else if (add) {
model = models[i] = this._prepareModel(attrs, options);
if (!model) continue;
toAdd.push(model);
this._addReference(model, options);
}
// Do not add multiple models with the same `id`.
model = existing || model;
if (order && (model.isNew() || !modelMap[model.id])) order.push(model);
modelMap[model.id] = true;
}
// Remove nonexistent models if appropriate.
if (remove) {
for (i = 0, l = this.length; i < l; ++i) {
if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
}
if (toRemove.length) this.remove(toRemove, options);
}
// See if sorting is needed, update `length` and splice in new models.
if (toAdd.length || (order && order.length)) {
if (sortable) sort = true;
this.length += toAdd.length;
if (at != null) {
for (i = 0, l = toAdd.length; i < l; i++) {
this.models.splice(at + i, 0, toAdd[i]);
}
} else {
if (order) this.models.length = 0;
var orderedModels = order || toAdd;
for (i = 0, l = orderedModels.length; i < l; i++) {
this.models.push(orderedModels[i]);
}
}
}
// Silently sort the collection if appropriate.
if (sort) this.sort({silent: true});
// Unless silenced, it's time to fire all appropriate add/sort events.
if (!options.silent) {
for (i = 0, l = toAdd.length; i < l; i++) {
(model = toAdd[i]).trigger('add', model, this, options);
}
if (sort || (order && order.length)) this.trigger('sort', this, options);
}
// Return the added (or merged) model (or models).
return singular ? models[0] : models;
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function(models, options) {
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i], options);
}
options.previousModels = this.models;
this._reset();
models = this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return models;
},
// Add a model to the end of the collection.
push: function(model, options) {
return this.add(model, _.extend({at: this.length}, options));
},
// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
// Add a model to the beginning of the collection.
unshift: function(model, options) {
return this.add(model, _.extend({at: 0}, options));
},
// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
// Slice out a sub-array of models from the collection.
slice: function() {
return slice.apply(this.models, arguments);
},
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of
// `filter`.
where: function(attrs, first) {
if (_.isEmpty(attrs)) return first ? void 0 : [];
return this[first ? 'find' : 'filter'](function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere: function(attrs) {
return this.where(attrs, true);
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function(options) {
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
options || (options = {});
// Run sort based on type of `comparator`.
if (_.isString(this.comparator) || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(_.bind(this.comparator, this));
}
if (!options.silent) this.trigger('sort', this, options);
return this;
},
// Pluck an attribute from each model in the collection.
pluck: function(attr) {
return _.invoke(this.models, 'get', attr);
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `reset: true` is passed, the response
// data will be passed through the `reset` method instead of `set`.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var success = options.success;
var collection = this;
options.success = function(resp) {
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success(collection, resp, options);
collection.trigger('sync', collection, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function(model, options) {
options = options ? _.clone(options) : {};
if (!(model = this._prepareModel(model, options))) return false;
if (!options.wait) this.add(model, options);
var collection = this;
var success = options.success;
options.success = function(model, resp) {
if (options.wait) collection.add(model, options);
if (success) success(model, resp, options);
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function(resp, options) {
return resp;
},
// Create a new collection with an identical list of models as this one.
clone: function() {
return new this.constructor(this.models);
},
// Private method to reset all internal state. Called when the collection
// is first initialized or reset.
_reset: function() {
this.length = 0;
this.models = [];
this._byId = {};
},
// Prepare a hash of attributes (or other model) to be added to this
// collection.
_prepareModel: function(attrs, options) {
if (attrs instanceof Model) return attrs;
options = options ? _.clone(options) : {};
options.collection = this;
var model = new this.model(attrs, options);
if (!model.validationError) return model;
this.trigger('invalid', this, model.validationError, options);
return false;
},
// Internal method to create a model's ties to a collection.
_addReference: function(model, options) {
this._byId[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
if (!model.collection) model.collection = this;
model.on('all', this._onModelEvent, this);
},
// Internal method to sever a model's ties to a collection.
_removeReference: function(model, options) {
if (this === model.collection) delete model.collection;
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function(event, model, collection, options) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(model, options);
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
if (model.id != null) this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
// 90% of the core usefulness of Backbone Collections is actually implemented
// right here:
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
'lastIndexOf', 'isEmpty', 'chain', 'sample'];
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Collection.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.models);
return _[method].apply(_, args);
};
});
// Underscore methods that take a property name as an argument.
var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
// Use attributes instead of properties.
_.each(attributeMethods, function(method) {
Collection.prototype[method] = function(value, context) {
var iterator = _.isFunction(value) ? value : function(model) {
return model.get(value);
};
return _[method](this.models, iterator, context);
};
});
// Backbone.View
// -------------
// Backbone Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
options || (options = {});
_.extend(this, _.pick(options, viewOptions));
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, Events, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be preferred to global lookups where possible.
$: function(selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function() {
return this;
},
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save',
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
});
// Backbone.sync
// -------------
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
// as `POST`, with a `_method` parameter containing the true HTTP method,
// as well as all requests with the body as `application/x-www-form-urlencoded`
// instead of `application/json` with the model in a param named `model`.
// Useful when interfacing with server-side languages like **PHP** that make
// it difficult to read the body of `PUT` requests.
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default options, unless specified.
_.defaults(options || (options = {}), {
emulateHTTP: Backbone.emulateHTTP,
emulateJSON: Backbone.emulateJSON
});
// Default JSON-request options.
var params = {type: type, dataType: 'json'};
// Ensure that we have a URL.
if (!options.url) {
params.url = _.result(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (options.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
params.type = 'POST';
if (options.emulateJSON) params.data._method = type;
var beforeSend = options.beforeSend;
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
if (beforeSend) return beforeSend.apply(this, arguments);
};
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !options.emulateJSON) {
params.processData = false;
}
// If we're sending a `PATCH` request, and we're in an old Internet Explorer
// that still has ActiveX enabled by default, override jQuery to use that
// for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
if (params.type === 'PATCH' && noXhrPatch) {
params.xhr = function() {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
// Make the request, allowing the user to override any Ajax options.
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
model.trigger('request', model, xhr, options);
return xhr;
};
var noXhrPatch =
typeof window !== 'undefined' && !!window.ActiveXObject &&
!(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
};
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
// Override this if you'd like to use a different library.
Backbone.ajax = function() {
return Backbone.$.ajax.apply(Backbone.$, arguments);
};
// Backbone.Router
// ---------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
router.execute(callback, args);
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});
return this;
},
// Execute a route handler with the provided parameters. This is an
// excellent place to do pre-route setup or post-route cleanup.
execute: function(callback, args) {
if (callback) callback.apply(this, args);
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
return this;
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) return;
this.routes = _.result(this, 'routes');
var route, routes = _.keys(this.routes);
while ((route = routes.pop()) != null) {
this.route(route, this.routes[route]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^/?]+)';
})
.replace(splatParam, '([^?]*?)');
return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted decoded parameters. Empty or unmatched parameters will be
// treated as `null` to normalize cross-browser behavior.
_extractParameters: function(route, fragment) {
var params = route.exec(fragment).slice(1);
return _.map(params, function(param, i) {
// Don't decode the search params.
if (i === params.length - 1) return param || null;
return param ? decodeURIComponent(param) : null;
});
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.
var History = Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
// Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};
// Cached regex for stripping a leading hash/slash and trailing space.
var routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
var rootStripper = /^\/+|\/+$/g;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Cached regex for removing a trailing slash.
var trailingSlash = /\/$/;
// Cached regex for stripping urls of hash.
var pathStripper = /#.*$/;
// Has the history handling already been started?
History.started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, Events, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Are we at the app root?
atRoot: function() {
return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root;
},
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = decodeURI(this.location.pathname + this.location.search);
var root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({root: '/'}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
// Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
if (oldIE && this._wantsHashChange) {
var frame = Backbone.$('<iframe src="javascript:0" tabindex="-1">');
this.iframe = frame.hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
Backbone.$(window).on('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
Backbone.$(window).on('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = this.location;
// Transition from hashChange to pushState or vice versa if both are
// requested.
if (this._wantsHashChange && this._wantsPushState) {
// If we've started off with a route from a `pushState`-enabled
// browser, but we're currently in a browser that doesn't support it...
if (!this._hasPushState && !this.atRoot()) {
this.fragment = this.getFragment(null, true);
this.location.replace(this.root + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._hasPushState && this.atRoot() && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
this.history.replaceState({}, document.title, this.root + this.fragment);
}
}
if (!this.options.silent) return this.loadUrl();
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function(e) {
var current = this.getFragment();
if (current === this.fragment && this.iframe) {
current = this.getFragment(this.getHash(this.iframe));
}
if (current === this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl();
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragment) {
fragment = this.fragment = this.getFragment(fragment);
return _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {trigger: !!options};
var url = this.root + (fragment = this.getFragment(fragment || ''));
// Strip the hash for matching.
fragment = fragment.replace(pathStripper, '');
if (this.fragment === fragment) return;
this.fragment = fragment;
// Don't include a trailing slash on the root.
if (fragment === '' && url !== '/') url = url.slice(0, -1);
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
// Opening and closing the iframe tricks IE7 and earlier to push a
// history entry on hash-tag change. When replace is true, we don't
// want this.
if(!options.replace) this.iframe.document.open().close();
this._updateHash(this.iframe.location, fragment, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return this.location.assign(url);
}
if (options.trigger) return this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
// Some browsers require that `hash` contains a leading #.
location.hash = '#' + fragment;
}
}
});
// Create the default Backbone.history.
Backbone.history = new History;
// Helpers
// -------
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// Set up inheritance for the model, collection, router, view and history.
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
// Wrap an optional error callback with a fallback error event.
var wrapError = function(model, options) {
var error = options.error;
options.error = function(resp) {
if (error) error(model, resp, options);
model.trigger('error', model, resp, options);
};
};
return Backbone;
}));
|
ajax/libs/yui/3.4.0/yui/yui-debug.js | wackyapples/cdnjs | /**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and
* the core utilities for the library.
* @module yui
* @submodule yui-base
*/
if (typeof YUI != 'undefined') {
YUI._YUI = YUI;
}
/**
The YUI global namespace object. If YUI is already defined, the
existing YUI object will not be overwritten so that defined
namespaces are preserved. It is the constructor for the object
the end user interacts with. As indicated below, each instance
has full custom event support, but only if the event system
is available. This is a self-instantiable factory function. You
can invoke it directly like this:
YUI().use('*', function(Y) {
// ready
});
But it also works like this:
var Y = YUI();
@class YUI
@constructor
@global
@uses EventTarget
@param o* {Object} 0..n optional configuration objects. these values
are store in Y.config. See <a href="config.html">Config</a> for the list of supported
properties.
*/
/*global YUI*/
/*global YUI_config*/
var YUI = function() {
var i = 0,
Y = this,
args = arguments,
l = args.length,
instanceOf = function(o, type) {
return (o && o.hasOwnProperty && (o instanceof type));
},
gconf = (typeof YUI_config !== 'undefined') && YUI_config;
if (!(instanceOf(Y, YUI))) {
Y = new YUI();
} else {
// set up the core environment
Y._init();
/**
YUI.GlobalConfig is a master configuration that might span
multiple contexts in a non-browser environment. It is applied
first to all instances in all contexts.
@property YUI.GlobalConfig
@type {Object}
@global
@example
YUI.GlobalConfig = {
filter: 'debug'
};
YUI().use('node', function(Y) {
//debug files used here
});
YUI({
filter: 'min'
}).use('node', function(Y) {
//min files used here
});
*/
if (YUI.GlobalConfig) {
Y.applyConfig(YUI.GlobalConfig);
}
/**
YUI_config is a page-level config. It is applied to all
instances created on the page. This is applied after
YUI.GlobalConfig, and before the instance level configuration
objects.
@global
@property YUI_config
@type {Object}
@example
//Single global var to include before YUI seed file
YUI_config = {
filter: 'debug'
};
YUI().use('node', function(Y) {
//debug files used here
});
YUI({
filter: 'min'
}).use('node', function(Y) {
//min files used here
});
*/
if (gconf) {
Y.applyConfig(gconf);
}
// bind the specified additional modules for this instance
if (!l) {
Y._setup();
}
}
if (l) {
// Each instance can accept one or more configuration objects.
// These are applied after YUI.GlobalConfig and YUI_Config,
// overriding values set in those config files if there is a '
// matching property.
for (; i < l; i++) {
Y.applyConfig(args[i]);
}
Y._setup();
}
Y.instanceOf = instanceOf;
return Y;
};
(function() {
var proto, prop,
VERSION = '@VERSION@',
PERIOD = '.',
BASE = 'http://yui.yahooapis.com/',
DOC_LABEL = 'yui3-js-enabled',
NOOP = function() {},
SLICE = Array.prototype.slice,
APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo
'io.xdrResponse': 1, // can call. this should
'SWF.eventHandler': 1 }, // be done at build time
hasWin = (typeof window != 'undefined'),
win = (hasWin) ? window : null,
doc = (hasWin) ? win.document : null,
docEl = doc && doc.documentElement,
docClass = docEl && docEl.className,
instances = {},
time = new Date().getTime(),
add = function(el, type, fn, capture) {
if (el && el.addEventListener) {
el.addEventListener(type, fn, capture);
} else if (el && el.attachEvent) {
el.attachEvent('on' + type, fn);
}
},
remove = function(el, type, fn, capture) {
if (el && el.removeEventListener) {
// this can throw an uncaught exception in FF
try {
el.removeEventListener(type, fn, capture);
} catch (ex) {}
} else if (el && el.detachEvent) {
el.detachEvent('on' + type, fn);
}
},
handleLoad = function() {
YUI.Env.windowLoaded = true;
YUI.Env.DOMReady = true;
if (hasWin) {
remove(window, 'load', handleLoad);
}
},
getLoader = function(Y, o) {
var loader = Y.Env._loader;
if (loader) {
//loader._config(Y.config);
loader.ignoreRegistered = false;
loader.onEnd = null;
loader.data = null;
loader.required = [];
loader.loadType = null;
} else {
loader = new Y.Loader(Y.config);
Y.Env._loader = loader;
}
return loader;
},
clobber = function(r, s) {
for (var i in s) {
if (s.hasOwnProperty(i)) {
r[i] = s[i];
}
}
},
ALREADY_DONE = { success: true };
// Stamp the documentElement (HTML) with a class of "yui-loaded" to
// enable styles that need to key off of JS being enabled.
if (docEl && docClass.indexOf(DOC_LABEL) == -1) {
if (docClass) {
docClass += ' ';
}
docClass += DOC_LABEL;
docEl.className = docClass;
}
if (VERSION.indexOf('@') > -1) {
VERSION = '3.3.0'; // dev time hack for cdn test
}
proto = {
/**
* Applies a new configuration object to the YUI instance config.
* This will merge new group/module definitions, and will also
* update the loader cache if necessary. Updating Y.config directly
* will not update the cache.
* @method applyConfig
* @param {Object} o the configuration object.
* @since 3.2.0
*/
applyConfig: function(o) {
o = o || NOOP;
var attr,
name,
// detail,
config = this.config,
mods = config.modules,
groups = config.groups,
rls = config.rls,
loader = this.Env._loader;
for (name in o) {
if (o.hasOwnProperty(name)) {
attr = o[name];
if (mods && name == 'modules') {
clobber(mods, attr);
} else if (groups && name == 'groups') {
clobber(groups, attr);
} else if (rls && name == 'rls') {
clobber(rls, attr);
} else if (name == 'win') {
config[name] = attr.contentWindow || attr;
config.doc = config[name].document;
} else if (name == '_yuid') {
// preserve the guid
} else {
config[name] = attr;
}
}
}
if (loader) {
loader._config(o);
}
},
/**
* Old way to apply a config to the instance (calls `applyConfig` under the hood)
* @private
* @method _config
* @param {Object} o The config to apply
*/
_config: function(o) {
this.applyConfig(o);
},
/**
* Initialize this YUI instance
* @private
* @method _init
*/
_init: function() {
var filter,
Y = this,
G_ENV = YUI.Env,
Env = Y.Env,
prop;
/**
* The version number of the YUI instance.
* @property version
* @type string
*/
Y.version = VERSION;
if (!Env) {
Y.Env = {
mods: {}, // flat module map
versions: {}, // version module map
base: BASE,
cdn: BASE + VERSION + '/build/',
// bootstrapped: false,
_idx: 0,
_used: {},
_attached: {},
_missed: [],
_yidx: 0,
_uidx: 0,
_guidp: 'y',
_loaded: {},
// serviced: {},
// Regex in English:
// I'll start at the \b(simpleyui).
// 1. Look in the test string for "simpleyui" or "yui" or
// "yui-base" or "yui-rls" or "yui-foobar" that comes after a word break. That is, it
// can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string.
// 2. After #1 must come a forward slash followed by the string matched in #1, so
// "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants".
// 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min",
// so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt".
// 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js"
// 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string,
// then capture the junk between the LAST "&" and the string in 1-4. So
// "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-rls/yui-rls.js"
// will capture "3.3.0/build/"
//
// Regex Exploded:
// (?:\? Find a ?
// (?:[^&]*&) followed by 0..n characters followed by an &
// * in fact, find as many sets of characters followed by a & as you can
// ([^&]*) capture the stuff after the last & in \1
// )? but it's ok if all this ?junk&more_junk stuff isn't even there
// \b(simpleyui| after a word break find either the string "simpleyui" or
// yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters
// ) and store the simpleyui or yui-* string in \2
// \/\2 then comes a / followed by the simpleyui or yui-* string in \2
// (?:-(min|debug))? optionally followed by "-min" or "-debug"
// .js and ending in ".js"
_BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/,
parseBasePath: function(src, pattern) {
var match = src.match(pattern),
path, filter;
if (match) {
path = RegExp.leftContext || src.slice(0, src.indexOf(match[0]));
// this is to set up the path to the loader. The file
// filter for loader should match the yui include.
filter = match[3];
// extract correct path for mixed combo urls
// http://yuilibrary.com/projects/yui3/ticket/2528423
if (match[1]) {
path += '?' + match[1];
}
path = {
filter: filter,
path: path
}
}
return path;
},
getBase: G_ENV && G_ENV.getBase ||
function(pattern) {
var nodes = (doc && doc.getElementsByTagName('script')) || [],
path = Env.cdn, parsed,
i, len, src;
for (i = 0, len = nodes.length; i < len; ++i) {
src = nodes[i].src;
if (src) {
parsed = Y.Env.parseBasePath(src, pattern);
if (parsed) {
filter = parsed.filter;
path = parsed.path;
break;
}
}
}
// use CDN default
return path;
}
};
Env = Y.Env;
Env._loaded[VERSION] = {};
if (G_ENV && Y !== YUI) {
Env._yidx = ++G_ENV._yidx;
Env._guidp = ('yui_' + VERSION + '_' +
Env._yidx + '_' + time).replace(/\./g, '_');
} else if (YUI._YUI) {
G_ENV = YUI._YUI.Env;
Env._yidx += G_ENV._yidx;
Env._uidx += G_ENV._uidx;
for (prop in G_ENV) {
if (!(prop in Env)) {
Env[prop] = G_ENV[prop];
}
}
delete YUI._YUI;
}
Y.id = Y.stamp(Y);
instances[Y.id] = Y;
}
Y.constructor = YUI;
// configuration defaults
Y.config = Y.config || {
win: win,
doc: doc,
debug: true,
useBrowserConsole: true,
throwFail: true,
bootstrap: true,
cacheUse: true,
fetchCSS: true,
use_rls: false,
rls_timeout: 2000
};
if (YUI.Env.rls_disabled) {
Y.config.use_rls = false;
}
Y.config.lang = Y.config.lang || 'en-US';
Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE);
if (!filter || (!('mindebug').indexOf(filter))) {
filter = 'min';
}
filter = (filter) ? '-' + filter : filter;
Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js';
},
/**
* Finishes the instance setup. Attaches whatever modules were defined
* when the yui modules was registered.
* @method _setup
* @private
*/
_setup: function(o) {
var i, Y = this,
core = [],
mods = YUI.Env.mods,
extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3'];
for (i = 0; i < extras.length; i++) {
if (mods[extras[i]]) {
core.push(extras[i]);
}
}
Y._attach(['yui-base']);
Y._attach(core);
// Y.log(Y.id + ' initialized', 'info', 'yui');
},
/**
* Executes a method on a YUI instance with
* the specified id if the specified method is whitelisted.
* @method applyTo
* @param id {String} the YUI instance id.
* @param method {String} the name of the method to exectute.
* Ex: 'Object.keys'.
* @param args {Array} the arguments to apply to the method.
* @return {Object} the return value from the applied method or null.
*/
applyTo: function(id, method, args) {
if (!(method in APPLY_TO_AUTH)) {
this.log(method + ': applyTo not allowed', 'warn', 'yui');
return null;
}
var instance = instances[id], nest, m, i;
if (instance) {
nest = method.split('.');
m = instance;
for (i = 0; i < nest.length; i = i + 1) {
m = m[nest[i]];
if (!m) {
this.log('applyTo not found: ' + method, 'warn', 'yui');
}
}
return m.apply(instance, args);
}
return null;
},
/**
Registers a module with the YUI global. The easiest way to create a
first-class YUI module is to use the YUI component build tool.
http://yuilibrary.com/projects/builder
The build system will produce the `YUI.add` wrapper for you module, along
with any configuration info required for the module.
@method add
@param name {String} module name.
@param fn {Function} entry point into the module that is used to bind module to the YUI instance.
@param {YUI} fn.Y The YUI instance this module is executed in.
@param {String} fn.name The name of the module
@param version {String} version string.
@param details {Object} optional config data:
@param details.requires {Array} features that must be present before this module can be attached.
@param details.optional {Array} optional features that should be present if loadOptional
is defined. Note: modules are not often loaded this way in YUI 3,
but this field is still useful to inform the user that certain
features in the component will require additional dependencies.
@param details.use {Array} features that are included within this module which need to
be attached automatically when this module is attached. This
supports the YUI 3 rollup system -- a module with submodules
defined will need to have the submodules listed in the 'use'
config. The YUI component build tool does this for you.
@return {YUI} the YUI instance.
@example
YUI.add('davglass', function(Y, name) {
Y.davglass = function() {
alert('Dav was here!');
};
}, '3.4.0', { requires: ['yui-base', 'harley-davidson', 'mt-dew'] });
*/
add: function(name, fn, version, details) {
details = details || {};
var env = YUI.Env,
mod = {
name: name,
fn: fn,
version: version,
details: details
},
loader,
i, versions = env.versions;
env.mods[name] = mod;
versions[version] = versions[version] || {};
versions[version][name] = mod;
for (i in instances) {
if (instances.hasOwnProperty(i)) {
loader = instances[i].Env._loader;
if (loader) {
if (!loader.moduleInfo[name]) {
loader.addModule(details, name);
}
}
}
}
return this;
},
/**
* Executes the function associated with each required
* module, binding the module to the YUI instance.
* @method _attach
* @private
*/
_attach: function(r, moot) {
var i, name, mod, details, req, use, after,
mods = YUI.Env.mods,
aliases = YUI.Env.aliases,
Y = this, j,
done = Y.Env._attached,
len = r.length, loader;
//console.info('attaching: ' + r, 'info', 'yui');
for (i = 0; i < len; i++) {
if (!done[r[i]]) {
name = r[i];
mod = mods[name];
if (aliases && aliases[name]) {
Y._attach(aliases[name]);
continue;
}
if (!mod) {
loader = Y.Env._loader;
if (loader && loader.moduleInfo[name]) {
mod = loader.moduleInfo[name];
if (mod.use) {
moot = true;
}
}
// Y.log('no js def for: ' + name, 'info', 'yui');
//if (!loader || !loader.moduleInfo[name]) {
//if ((!loader || !loader.moduleInfo[name]) && !moot) {
if (!moot) {
if (name.indexOf('skin-') === -1) {
Y.Env._missed.push(name);
Y.message('NOT loaded: ' + name, 'warn', 'yui');
}
}
} else {
done[name] = true;
//Don't like this, but in case a mod was asked for once, then we fetch it
//We need to remove it from the missed list
for (j = 0; j < Y.Env._missed.length; j++) {
if (Y.Env._missed[j] === name) {
Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui');
Y.Env._missed.splice(j, 1);
}
}
details = mod.details;
req = details.requires;
use = details.use;
after = details.after;
if (req) {
for (j = 0; j < req.length; j++) {
if (!done[req[j]]) {
if (!Y._attach(req)) {
return false;
}
break;
}
}
}
if (after) {
for (j = 0; j < after.length; j++) {
if (!done[after[j]]) {
if (!Y._attach(after, true)) {
return false;
}
break;
}
}
}
if (mod.fn) {
try {
mod.fn(Y, name);
} catch (e) {
Y.error('Attach error: ' + name, e, name);
return false;
}
}
if (use) {
for (j = 0; j < use.length; j++) {
if (!done[use[j]]) {
if (!Y._attach(use)) {
return false;
}
break;
}
}
}
}
}
}
return true;
},
/**
* Attaches one or more modules to the YUI instance. When this
* is executed, the requirements are analyzed, and one of
* several things can happen:
*
* * All requirements are available on the page -- The modules
* are attached to the instance. If supplied, the use callback
* is executed synchronously.
*
* * Modules are missing, the Get utility is not available OR
* the 'bootstrap' config is false -- A warning is issued about
* the missing modules and all available modules are attached.
*
* * Modules are missing, the Loader is not available but the Get
* utility is and boostrap is not false -- The loader is bootstrapped
* before doing the following....
*
* * Modules are missing and the Loader is available -- The loader
* expands the dependency tree and fetches missing modules. When
* the loader is finshed the callback supplied to use is executed
* asynchronously.
*
* @method use
* @param modules* {String} 1-n modules to bind (uses arguments array).
* @param *callback {Function} callback function executed when
* the instance has the required functionality. If included, it
* must be the last parameter.
*
* @example
* // loads and attaches dd and its dependencies
* YUI().use('dd', function(Y) {});
*
* // loads and attaches dd and node as well as all of their dependencies (since 3.4.0)
* YUI().use(['dd', 'node'], function(Y) {});
*
* // attaches all modules that are available on the page
* YUI().use('*', function(Y) {});
*
* // intrinsic YUI gallery support (since 3.1.0)
* YUI().use('gallery-yql', function(Y) {});
*
* // intrinsic YUI 2in3 support (since 3.1.0)
* YUI().use('yui2-datatable', function(Y) {});
*
* @return {YUI} the YUI instance.
*/
use: function() {
var args = SLICE.call(arguments, 0),
callback = args[args.length - 1],
Y = this,
i = 0,
name,
Env = Y.Env,
provisioned = true;
// The last argument supplied to use can be a load complete callback
if (Y.Lang.isFunction(callback)) {
args.pop();
} else {
callback = null;
}
if (Y.Lang.isArray(args[0])) {
args = args[0];
}
if (Y.config.cacheUse) {
while ((name = args[i++])) {
if (!Env._attached[name]) {
provisioned = false;
break;
}
}
if (provisioned) {
if (args.length) {
Y.log('already provisioned: ' + args, 'info', 'yui');
}
Y._notify(callback, ALREADY_DONE, args);
return Y;
}
}
if (Y.config.cacheUse) {
while ((name = args[i++])) {
if (!Env._attached[name]) {
provisioned = false;
break;
}
}
if (provisioned) {
if (args.length) {
Y.log('already provisioned: ' + args, 'info', 'yui');
}
Y._notify(callback, ALREADY_DONE, args);
return Y;
}
}
if (Y._loading) {
Y._useQueue = Y._useQueue || new Y.Queue();
Y._useQueue.add([args, callback]);
} else {
Y._use(args, function(Y, response) {
Y._notify(callback, response, args);
});
}
return Y;
},
/**
* Notify handler from Loader for attachment/load errors
* @method _notify
* @param callback {Function} The callback to pass to the `Y.config.loadErrorFn`
* @param response {Object} The response returned from Loader
* @param args {Array} The aruments passed from Loader
* @private
*/
_notify: function(callback, response, args) {
if (!response.success && this.config.loadErrorFn) {
this.config.loadErrorFn.call(this, this, callback, response, args);
} else if (callback) {
try {
callback(this, response);
} catch (e) {
this.error('use callback error', e, args);
}
}
},
/**
* This private method is called from the `use` method queue. To ensure that only one set of loading
* logic is performed at a time.
* @method _use
* @private
* @param args* {String} 1-n modules to bind (uses arguments array).
* @param *callback {Function} callback function executed when
* the instance has the required functionality. If included, it
* must be the last parameter.
*/
_use: function(args, callback) {
if (!this.Array) {
this._attach(['yui-base']);
}
var len, loader, handleBoot, handleRLS,
Y = this,
G_ENV = YUI.Env,
mods = G_ENV.mods,
Env = Y.Env,
used = Env._used,
queue = G_ENV._loaderQueue,
firstArg = args[0],
YArray = Y.Array,
config = Y.config,
boot = config.bootstrap,
missing = [],
r = [],
ret = true,
fetchCSS = config.fetchCSS,
process = function(names, skip) {
if (!names.length) {
return;
}
YArray.each(names, function(name) {
// add this module to full list of things to attach
if (!skip) {
r.push(name);
}
// only attach a module once
if (used[name]) {
return;
}
var m = mods[name], req, use;
if (m) {
used[name] = true;
req = m.details.requires;
use = m.details.use;
} else {
// CSS files don't register themselves, see if it has
// been loaded
if (!G_ENV._loaded[VERSION][name]) {
missing.push(name);
} else {
used[name] = true; // probably css
}
}
// make sure requirements are attached
if (req && req.length) {
process(req);
}
// make sure we grab the submodule dependencies too
if (use && use.length) {
process(use, 1);
}
});
},
handleLoader = function(fromLoader) {
var response = fromLoader || {
success: true,
msg: 'not dynamic'
},
redo, origMissing,
ret = true,
data = response.data;
Y._loading = false;
if (data) {
origMissing = missing;
missing = [];
r = [];
process(data);
redo = missing.length;
if (redo) {
if (missing.sort().join() ==
origMissing.sort().join()) {
redo = false;
}
}
}
if (redo && data) {
Y._loading = false;
Y._use(args, function() {
Y.log('Nested use callback: ' + data, 'info', 'yui');
if (Y._attach(data)) {
Y._notify(callback, response, data);
}
});
} else {
if (data) {
// Y.log('attaching from loader: ' + data, 'info', 'yui');
ret = Y._attach(data);
}
if (ret) {
Y._notify(callback, response, args);
}
}
if (Y._useQueue && Y._useQueue.size() && !Y._loading) {
Y._use.apply(Y, Y._useQueue.next());
}
};
// Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui');
// YUI().use('*'); // bind everything available
if (firstArg === '*') {
ret = Y._attach(Y.Object.keys(mods));
if (ret) {
handleLoader();
}
return Y;
}
// Y.log('before loader requirements: ' + args, 'info', 'yui');
// use loader to expand dependencies and sort the
// requirements if it is available.
if (boot && Y.Loader && args.length) {
loader = getLoader(Y);
loader.require(args);
loader.ignoreRegistered = true;
loader.calculate(null, (fetchCSS) ? null : 'js');
args = loader.sorted;
}
// process each requirement and any additional requirements
// the module metadata specifies
process(args);
len = missing.length;
if (len) {
missing = Y.Object.keys(YArray.hash(missing));
len = missing.length;
Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui');
}
// dynamic load
if (boot && len && Y.Loader) {
// Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui');
Y.log('Using Loader', 'info', 'yui');
Y._loading = true;
loader = getLoader(Y);
loader.onEnd = handleLoader;
loader.context = Y;
loader.data = args;
loader.ignoreRegistered = false;
loader.require(args);
loader.insert(null, (fetchCSS) ? null : 'js');
// loader.partial(missing, (fetchCSS) ? null : 'js');
} else if (len && Y.config.use_rls && !YUI.Env.rls_enabled) {
G_ENV._rls_queue = G_ENV._rls_queue || new Y.Queue();
// server side loader service
handleRLS = function(instance, argz) {
var rls_end = function(o) {
handleLoader(o);
instance.rls_advance();
},
rls_url = instance._rls(argz);
if (rls_url) {
Y.log('Fetching RLS url', 'info', 'rls');
instance.rls_oncomplete(function(o) {
rls_end(o);
});
instance.Get.script(rls_url, {
data: argz,
timeout: instance.config.rls_timeout,
onFailure: instance.rls_handleFailure,
onTimeout: instance.rls_handleTimeout
});
} else {
rls_end({
success: true,
data: argz
});
}
};
G_ENV._rls_queue.add(function() {
Y.log('executing queued rls request', 'info', 'rls');
G_ENV._rls_in_progress = true;
Y.rls_callback = callback;
Y.rls_locals(Y, args, handleRLS);
});
if (!G_ENV._rls_in_progress && G_ENV._rls_queue.size()) {
G_ENV._rls_queue.next()();
}
} else if (boot && len && Y.Get && !Env.bootstrapped) {
Y._loading = true;
handleBoot = function() {
Y._loading = false;
queue.running = false;
Env.bootstrapped = true;
G_ENV._bootstrapping = false;
if (Y._attach(['loader'])) {
Y._use(args, callback);
}
};
if (G_ENV._bootstrapping) {
Y.log('Waiting for loader', 'info', 'yui');
queue.add(handleBoot);
} else {
G_ENV._bootstrapping = true;
Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui');
Y.Get.script(config.base + config.loaderPath, {
onEnd: handleBoot
});
}
} else {
Y.log('Attaching available dependencies: ' + args, 'info', 'yui');
ret = Y._attach(args);
if (ret) {
handleLoader();
}
}
return Y;
},
/**
Adds a namespace object onto the YUI global if called statically:
// creates YUI.your.namespace.here as nested objects
YUI.namespace("your.namespace.here");
If called as an instance method on the YUI instance, it creates the
namespace on the instance:
// creates Y.property.package
Y.namespace("property.package");
Dots in the input string cause `namespace` to create nested objects for
each token. If any part of the requested namespace already exists, the
current object will be left in place. This allows multiple calls to
`namespace` to preserve existing namespaced properties.
If the first token in the namespace string is "YAHOO", the token is
discarded.
Be careful when naming packages. Reserved words may work in some browsers
and not others. For instance, the following will fail in some browsers:
Y.namespace("really.long.nested.namespace");
This fails because `long` is a future reserved word in ECMAScript
@method namespace
@param {String[]} namespace* 1-n namespaces to create.
@return {Object} A reference to the last namespace object created.
**/
namespace: function() {
var a = arguments, o = this, i = 0, j, d, arg;
for (; i < a.length; i++) {
// d = ('' + a[i]).split('.');
arg = a[i];
if (arg.indexOf(PERIOD)) {
d = arg.split(PERIOD);
for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
} else {
o[arg] = o[arg] || {};
}
}
return o;
},
// this is replaced if the log module is included
log: NOOP,
message: NOOP,
// this is replaced if the dump module is included
dump: function (o) { return ''+o; },
/**
* Report an error. The reporting mechanism is controled by
* the `throwFail` configuration attribute. If throwFail is
* not specified, the message is written to the Logger, otherwise
* a JS error is thrown
* @method error
* @param msg {String} the error message.
* @param e {Error|String} Optional JS error that was caught, or an error string.
* @param data Optional additional info
* and `throwFail` is specified, this error will be re-thrown.
* @return {YUI} this YUI instance.
*/
error: function(msg, e, data) {
var Y = this, ret;
if (Y.config.errorFn) {
ret = Y.config.errorFn.apply(Y, arguments);
}
if (Y.config.throwFail && !ret) {
throw (e || new Error(msg));
} else {
Y.message(msg, 'error'); // don't scrub this one
}
return Y;
},
/**
* Generate an id that is unique among all YUI instances
* @method guid
* @param pre {String} optional guid prefix.
* @return {String} the guid.
*/
guid: function(pre) {
var id = this.Env._guidp + '_' + (++this.Env._uidx);
return (pre) ? (pre + id) : id;
},
/**
* Returns a `guid` associated with an object. If the object
* does not have one, a new one is created unless `readOnly`
* is specified.
* @method stamp
* @param o {Object} The object to stamp.
* @param readOnly {Boolean} if `true`, a valid guid will only
* be returned if the object has one assigned to it.
* @return {String} The object's guid or null.
*/
stamp: function(o, readOnly) {
var uid;
if (!o) {
return o;
}
// IE generates its own unique ID for dom nodes
// The uniqueID property of a document node returns a new ID
if (o.uniqueID && o.nodeType && o.nodeType !== 9) {
uid = o.uniqueID;
} else {
uid = (typeof o === 'string') ? o : o._yuid;
}
if (!uid) {
uid = this.guid();
if (!readOnly) {
try {
o._yuid = uid;
} catch (e) {
uid = null;
}
}
}
return uid;
},
/**
* Destroys the YUI instance
* @method destroy
* @since 3.3.0
*/
destroy: function() {
var Y = this;
if (Y.Event) {
Y.Event._unload();
}
delete instances[Y.id];
delete Y.Env;
delete Y.config;
}
/**
* instanceof check for objects that works around
* memory leak in IE when the item tested is
* window/document
* @method instanceOf
* @since 3.3.0
*/
};
YUI.prototype = proto;
// inheritance utilities are not available yet
for (prop in proto) {
if (proto.hasOwnProperty(prop)) {
YUI[prop] = proto[prop];
}
}
// set up the environment
YUI._init();
if (hasWin) {
// add a window load event at load time so we can capture
// the case where it fires before dynamic loading is
// complete.
add(window, 'load', handleLoad);
} else {
handleLoad();
}
YUI.Env.add = add;
YUI.Env.remove = remove;
/*global exports*/
// Support the CommonJS method for exporting our single global
if (typeof exports == 'object') {
exports.YUI = YUI;
}
}());
/**
* The config object contains all of the configuration options for
* the `YUI` instance. This object is supplied by the implementer
* when instantiating a `YUI` instance. Some properties have default
* values if they are not supplied by the implementer. This should
* not be updated directly because some values are cached. Use
* `applyConfig()` to update the config object on a YUI instance that
* has already been configured.
*
* @class config
* @static
*/
/**
* Allows the YUI seed file to fetch the loader component and library
* metadata to dynamically load additional dependencies.
*
* @property bootstrap
* @type boolean
* @default true
*/
/**
* Log to the browser console if debug is on and the browser has a
* supported console.
*
* @property useBrowserConsole
* @type boolean
* @default true
*/
/**
* A hash of log sources that should be logged. If specified, only
* log messages from these sources will be logged.
*
* @property logInclude
* @type object
*/
/**
* A hash of log sources that should be not be logged. If specified,
* all sources are logged if not on this list.
*
* @property logExclude
* @type object
*/
/**
* Set to true if the yui seed file was dynamically loaded in
* order to bootstrap components relying on the window load event
* and the `domready` custom event.
*
* @property injected
* @type boolean
* @default false
*/
/**
* If `throwFail` is set, `Y.error` will generate or re-throw a JS Error.
* Otherwise the failure is logged.
*
* @property throwFail
* @type boolean
* @default true
*/
/**
* The window/frame that this instance should operate in.
*
* @property win
* @type Window
* @default the window hosting YUI
*/
/**
* The document associated with the 'win' configuration.
*
* @property doc
* @type Document
* @default the document hosting YUI
*/
/**
* A list of modules that defines the YUI core (overrides the default).
*
* @property core
* @type string[]
*/
/**
* A list of languages in order of preference. This list is matched against
* the list of available languages in modules that the YUI instance uses to
* determine the best possible localization of language sensitive modules.
* Languages are represented using BCP 47 language tags, such as "en-GB" for
* English as used in the United Kingdom, or "zh-Hans-CN" for simplified
* Chinese as used in China. The list can be provided as a comma-separated
* list or as an array.
*
* @property lang
* @type string|string[]
*/
/**
* The default date format
* @property dateFormat
* @type string
* @deprecated use configuration in `DataType.Date.format()` instead.
*/
/**
* The default locale
* @property locale
* @type string
* @deprecated use `config.lang` instead.
*/
/**
* The default interval when polling in milliseconds.
* @property pollInterval
* @type int
* @default 20
*/
/**
* The number of dynamic nodes to insert by default before
* automatically removing them. This applies to script nodes
* because removing the node will not make the evaluated script
* unavailable. Dynamic CSS is not auto purged, because removing
* a linked style sheet will also remove the style definitions.
* @property purgethreshold
* @type int
* @default 20
*/
/**
* The default interval when polling in milliseconds.
* @property windowResizeDelay
* @type int
* @default 40
*/
/**
* Base directory for dynamic loading
* @property base
* @type string
*/
/*
* The secure base dir (not implemented)
* For dynamic loading.
* @property secureBase
* @type string
*/
/**
* The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?`
* For dynamic loading.
* @property comboBase
* @type string
*/
/**
* The root path to prepend to module path for the combo service.
* Ex: 3.0.0b1/build/
* For dynamic loading.
* @property root
* @type string
*/
/**
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the Logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).</dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
*
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
*
* For dynamic loading.
*
* @property filter
* @type string|object
*/
/**
* The `skin` config let's you configure application level skin
* customizations. It contains the following attributes which
* can be specified to override the defaults:
*
* // The default skin, which is automatically applied if not
* // overriden by a component-specific skin definition.
* // Change this in to apply a different skin globally
* defaultSkin: 'sam',
*
* // This is combined with the loader base property to get
* // the default root directory for a skin.
* base: 'assets/skins/',
*
* // Any component-specific overrides can be specified here,
* // making it possible to load different skins for different
* // components. It is possible to load more than one skin
* // for a given component as well.
* overrides: {
* slider: ['capsule', 'round']
* }
*
* For dynamic loading.
*
* @property skin
*/
/**
* Hash of per-component filter specification. If specified for a given
* component, this overrides the filter config.
*
* For dynamic loading.
*
* @property filters
*/
/**
* Use the YUI combo service to reduce the number of http connections
* required to load your dependencies. Turning this off will
* disable combo handling for YUI and all module groups configured
* with a combo service.
*
* For dynamic loading.
*
* @property combine
* @type boolean
* @default true if 'base' is not supplied, false if it is.
*/
/**
* A list of modules that should never be dynamically loaded
*
* @property ignore
* @type string[]
*/
/**
* A list of modules that should always be loaded when required, even if already
* present on the page.
*
* @property force
* @type string[]
*/
/**
* Node or id for a node that should be used as the insertion point for new
* nodes. For dynamic loading.
*
* @property insertBefore
* @type string
*/
/**
* Object literal containing attributes to add to dynamically loaded script
* nodes.
* @property jsAttributes
* @type string
*/
/**
* Object literal containing attributes to add to dynamically loaded link
* nodes.
* @property cssAttributes
* @type string
*/
/**
* Number of milliseconds before a timeout occurs when dynamically
* loading nodes. If not set, there is no timeout.
* @property timeout
* @type int
*/
/**
* Callback for the 'CSSComplete' event. When dynamically loading YUI
* components with CSS, this property fires when the CSS is finished
* loading but script loading is still ongoing. This provides an
* opportunity to enhance the presentation of a loading page a little
* bit before the entire loading process is done.
*
* @property onCSS
* @type function
*/
/**
* A hash of module definitions to add to the list of YUI components.
* These components can then be dynamically loaded side by side with
* YUI via the `use()` method. This is a hash, the key is the module
* name, and the value is an object literal specifying the metdata
* for the module. See `Loader.addModule` for the supported module
* metadata fields. Also see groups, which provides a way to
* configure the base and combo spec for a set of modules.
*
* modules: {
* mymod1: {
* requires: ['node'],
* fullpath: 'http://myserver.mydomain.com/mymod1/mymod1.js'
* },
* mymod2: {
* requires: ['mymod1'],
* fullpath: 'http://myserver.mydomain.com/mymod2/mymod2.js'
* }
* }
*
* @property modules
* @type object
*/
/**
* A hash of module group definitions. It for each group you
* can specify a list of modules and the base path and
* combo spec to use when dynamically loading the modules.
*
* groups: {
* yui2: {
* // specify whether or not this group has a combo service
* combine: true,
*
* // the base path for non-combo paths
* base: 'http://yui.yahooapis.com/2.8.0r4/build/',
*
* // the path to the combo service
* comboBase: 'http://yui.yahooapis.com/combo?',
*
* // a fragment to prepend to the path attribute when
* // when building combo urls
* root: '2.8.0r4/build/',
*
* // the module definitions
* modules: {
* yui2_yde: {
* path: "yahoo-dom-event/yahoo-dom-event.js"
* },
* yui2_anim: {
* path: "animation/animation.js",
* requires: ['yui2_yde']
* }
* }
* }
* }
*
* @property groups
* @type object
*/
/**
* The loader 'path' attribute to the loader itself. This is combined
* with the 'base' attribute to dynamically load the loader component
* when boostrapping with the get utility alone.
*
* @property loaderPath
* @type string
* @default loader/loader-min.js
*/
/**
* Specifies whether or not YUI().use(...) will attempt to load CSS
* resources at all. Any truthy value will cause CSS dependencies
* to load when fetching script. The special value 'force' will
* cause CSS dependencies to be loaded even if no script is needed.
*
* @property fetchCSS
* @type boolean|string
* @default true
*/
/**
* The default gallery version to build gallery module urls
* @property gallery
* @type string
* @since 3.1.0
*/
/**
* The default YUI 2 version to build yui2 module urls. This is for
* intrinsic YUI 2 support via the 2in3 project. Also see the '2in3'
* config for pulling different revisions of the wrapped YUI 2
* modules.
* @since 3.1.0
* @property yui2
* @type string
* @default 2.8.1
*/
/**
* The 2in3 project is a deployment of the various versions of YUI 2
* deployed as first-class YUI 3 modules. Eventually, the wrapper
* for the modules will change (but the underlying YUI 2 code will
* be the same), and you can select a particular version of
* the wrapper modules via this config.
* @since 3.1.0
* @property 2in3
* @type string
* @default 1
*/
/**
* Alternative console log function for use in environments without
* a supported native console. The function is executed in the
* YUI instance context.
* @since 3.1.0
* @property logFn
* @type Function
*/
/**
* A callback to execute when Y.error is called. It receives the
* error message and an javascript error object if Y.error was
* executed because a javascript error was caught. The function
* is executed in the YUI instance context.
*
* @since 3.2.0
* @property errorFn
* @type Function
*/
/**
* A callback to execute when the loader fails to load one or
* more resource. This could be because of a script load
* failure. It can also fail if a javascript module fails
* to register itself, but only when the 'requireRegistration'
* is true. If this function is defined, the use() callback will
* only be called when the loader succeeds, otherwise it always
* executes unless there was a javascript error when attaching
* a module.
*
* @since 3.3.0
* @property loadErrorFn
* @type Function
*/
/**
* When set to true, the YUI loader will expect that all modules
* it is responsible for loading will be first-class YUI modules
* that register themselves with the YUI global. If this is
* set to true, loader will fail if the module registration fails
* to happen after the script is loaded.
*
* @since 3.3.0
* @property requireRegistration
* @type boolean
* @default false
*/
/**
* Cache serviced use() requests.
* @since 3.3.0
* @property cacheUse
* @type boolean
* @default true
* @deprecated no longer used
*/
/**
* The parameter defaults for the remote loader service. **Requires the rls seed file.** The properties that are supported:
*
* * `m`: comma separated list of module requirements. This
* must be the param name even for custom implemetations.
* * `v`: the version of YUI to load. Defaults to the version
* of YUI that is being used.
* * `gv`: the version of the gallery to load (see the gallery config)
* * `env`: comma separated list of modules already on the page.
* this must be the param name even for custom implemetations.
* * `lang`: the languages supported on the page (see the lang config)
* * `'2in3v'`: the version of the 2in3 wrapper to use (see the 2in3 config).
* * `'2v'`: the version of yui2 to use in the yui 2in3 wrappers
* * `filt`: a filter def to apply to the urls (see the filter config).
* * `filts`: a list of custom filters to apply per module
* * `tests`: this is a map of conditional module test function id keys
* with the values of 1 if the test passes, 0 if not. This must be
* the name of the querystring param in custom templates.
*
* @since 3.2.0
* @property rls
* @type {Object}
*/
/**
* The base path to the remote loader service. **Requires the rls seed file.**
*
* @since 3.2.0
* @property rls_base
* @type {String}
*/
/**
* The template to use for building the querystring portion
* of the remote loader service url. The default is determined
* by the rls config -- each property that has a value will be
* represented. **Requires the rls seed file.**
*
* @since 3.2.0
* @property rls_tmpl
* @type {String}
* @example
* m={m}&v={v}&env={env}&lang={lang}&filt={filt}&tests={tests}
*
*/
/**
* Configure the instance to use a remote loader service instead of
* the client loader. **Requires the rls seed file.**
*
* @since 3.2.0
* @property use_rls
* @type {Boolean}
*/
YUI.add('yui-base', function(Y) {
/*
* YUI stub
* @module yui
* @submodule yui-base
*/
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Provides core language utilites and extensions used throughout YUI.
*
* @class Lang
* @static
*/
var L = Y.Lang || (Y.Lang = {}),
STRING_PROTO = String.prototype,
TOSTRING = Object.prototype.toString,
TYPES = {
'undefined' : 'undefined',
'number' : 'number',
'boolean' : 'boolean',
'string' : 'string',
'[object Function]': 'function',
'[object RegExp]' : 'regexp',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object Error]' : 'error'
},
SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g,
TRIMREGEX = /^\s+|\s+$/g,
// If either MooTools or Prototype is on the page, then there's a chance that we
// can't trust "native" language features to actually be native. When this is
// the case, we take the safe route and fall back to our own non-native
// implementation.
win = Y.config.win,
unsafeNatives = win && !!(win.MooTools || win.Prototype);
/**
* Determines whether or not the provided item is an array.
*
* Returns `false` for array-like collections such as the function `arguments`
* collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to
* test for an array-like collection.
*
* @method isArray
* @param o The object to test.
* @return {boolean} true if o is an array.
* @static
*/
L.isArray = (!unsafeNatives && Array.isArray) || function (o) {
return L.type(o) === 'array';
};
/**
* Determines whether or not the provided item is a boolean.
* @method isBoolean
* @static
* @param o The object to test.
* @return {boolean} true if o is a boolean.
*/
L.isBoolean = function(o) {
return typeof o === 'boolean';
};
/**
* <p>
* Determines whether or not the provided item is a function.
* Note: Internet Explorer thinks certain functions are objects:
* </p>
*
* <pre>
* var obj = document.createElement("object");
* Y.Lang.isFunction(obj.getAttribute) // reports false in IE
*
* var input = document.createElement("input"); // append to body
* Y.Lang.isFunction(input.focus) // reports false in IE
* </pre>
*
* <p>
* You will have to implement additional tests if these functions
* matter to you.
* </p>
*
* @method isFunction
* @static
* @param o The object to test.
* @return {boolean} true if o is a function.
*/
L.isFunction = function(o) {
return L.type(o) === 'function';
};
/**
* Determines whether or not the supplied item is a date instance.
* @method isDate
* @static
* @param o The object to test.
* @return {boolean} true if o is a date.
*/
L.isDate = function(o) {
return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o);
};
/**
* Determines whether or not the provided item is null.
* @method isNull
* @static
* @param o The object to test.
* @return {boolean} true if o is null.
*/
L.isNull = function(o) {
return o === null;
};
/**
* Determines whether or not the provided item is a legal number.
* @method isNumber
* @static
* @param o The object to test.
* @return {boolean} true if o is a number.
*/
L.isNumber = function(o) {
return typeof o === 'number' && isFinite(o);
};
/**
* Determines whether or not the provided item is of type object
* or function. Note that arrays are also objects, so
* <code>Y.Lang.isObject([]) === true</code>.
* @method isObject
* @static
* @param o The object to test.
* @param failfn {boolean} fail if the input is a function.
* @return {boolean} true if o is an object.
* @see isPlainObject
*/
L.isObject = function(o, failfn) {
var t = typeof o;
return (o && (t === 'object' ||
(!failfn && (t === 'function' || L.isFunction(o))))) || false;
};
/**
* Determines whether or not the provided item is a string.
* @method isString
* @static
* @param o The object to test.
* @return {boolean} true if o is a string.
*/
L.isString = function(o) {
return typeof o === 'string';
};
/**
* Determines whether or not the provided item is undefined.
* @method isUndefined
* @static
* @param o The object to test.
* @return {boolean} true if o is undefined.
*/
L.isUndefined = function(o) {
return typeof o === 'undefined';
};
/**
* Returns a string without any leading or trailing whitespace. If
* the input is not a string, the input will be returned untouched.
* @method trim
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trim = STRING_PROTO.trim ? function(s) {
return s && s.trim ? s.trim() : s;
} : function (s) {
try {
return s.replace(TRIMREGEX, '');
} catch (e) {
return s;
}
};
/**
* Returns a string without any leading whitespace.
* @method trimLeft
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimLeft = STRING_PROTO.trimLeft ? function (s) {
return s.trimLeft();
} : function (s) {
return s.replace(/^\s+/, '');
};
/**
* Returns a string without any trailing whitespace.
* @method trimRight
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimRight = STRING_PROTO.trimRight ? function (s) {
return s.trimRight();
} : function (s) {
return s.replace(/\s+$/, '');
};
/**
* A convenience method for detecting a legitimate non-null value.
* Returns false for null/undefined/NaN, true for other values,
* including 0/false/''
* @method isValue
* @static
* @param o The item to test.
* @return {boolean} true if it is not null/undefined/NaN || false.
*/
L.isValue = function(o) {
var t = L.type(o);
switch (t) {
case 'number':
return isFinite(o);
case 'null': // fallthru
case 'undefined':
return false;
default:
return !!t;
}
};
/**
* <p>
* Returns a string representing the type of the item passed in.
* </p>
*
* <p>
* Known issues:
* </p>
*
* <ul>
* <li>
* <code>typeof HTMLElementCollection</code> returns function in Safari, but
* <code>Y.type()</code> reports object, which could be a good thing --
* but it actually caused the logic in <code>Y.Lang.isObject</code> to fail.
* </li>
* </ul>
*
* @method type
* @param o the item to test.
* @return {string} the detected type.
* @static
*/
L.type = function(o) {
return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};
/**
* Lightweight version of <code>Y.substitute</code>. Uses the same template
* structure as <code>Y.substitute</code>, but doesn't support recursion,
* auto-object coersion, or formats.
* @method sub
* @param {string} s String to be modified.
* @param {object} o Object containing replacement values.
* @return {string} the substitute result.
* @static
* @since 3.2.0
*/
L.sub = function(s, o) {
return s.replace ? s.replace(SUBREGEX, function (match, key) {
return L.isUndefined(o[key]) ? match : o[key];
}) : s;
};
/**
* Returns the current time in milliseconds.
*
* @method now
* @return {Number} Current time in milliseconds.
* @static
* @since 3.3.0
*/
L.now = Date.now || function () {
return new Date().getTime();
};
/**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and the
* core utilities for the library.
*
* @module yui
* @submodule yui-base
*/
var Lang = Y.Lang,
Native = Array.prototype,
hasOwn = Object.prototype.hasOwnProperty;
/**
Provides utility methods for working with arrays. Additional array helpers can
be found in the `collection` and `array-extras` modules.
`Y.Array(thing)` returns a native array created from _thing_. Depending on
_thing_'s type, one of the following will happen:
* Arrays are returned unmodified unless a non-zero _startIndex_ is
specified.
* Array-like collections (see `Array.test()`) are converted to arrays.
* For everything else, a new array is created with _thing_ as the sole
item.
Note: elements that are also collections, such as `<form>` and `<select>`
elements, are not automatically converted to arrays. To force a conversion,
pass `true` as the value of the _force_ parameter.
@class Array
@constructor
@param {Any} thing The thing to arrayify.
@param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like
collection, a subset of items starting at the specified index will be
returned.
@param {Boolean} [force=false] If `true`, _thing_ will be treated as an
array-like collection no matter what.
@return {Array} A native array created from _thing_, according to the rules
described above.
**/
function YArray(thing, startIndex, force) {
var len, result;
startIndex || (startIndex = 0);
if (force || YArray.test(thing)) {
// IE throws when trying to slice HTMLElement collections.
try {
return Native.slice.call(thing, startIndex);
} catch (ex) {
result = [];
for (len = thing.length; startIndex < len; ++startIndex) {
result.push(thing[startIndex]);
}
return result;
}
}
return [thing];
}
Y.Array = YArray;
/**
Evaluates _obj_ to determine if it's an array, an array-like collection, or
something else. This is useful when working with the function `arguments`
collection and `HTMLElement` collections.
Note: This implementation doesn't consider elements that are also
collections, such as `<form>` and `<select>`, to be array-like.
@method test
@param {Object} obj Object to test.
@return {Number} A number indicating the results of the test:
* 0: Neither an array nor an array-like collection.
* 1: Real array.
* 2: Array-like collection.
@static
**/
YArray.test = function (obj) {
var result = 0;
if (Lang.isArray(obj)) {
result = 1;
} else if (Lang.isObject(obj)) {
try {
// indexed, but no tagName (element) or alert (window),
// or functions without apply/call (Safari
// HTMLElementCollection bug).
if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) {
result = 2;
}
} catch (ex) {}
}
return result;
};
/**
Dedupes an array of strings, returning an array that's guaranteed to contain
only one copy of a given string.
This method differs from `Array.unique()` in that it's optimized for use only
with strings, whereas `unique` may be used with other types (but is slower).
Using `dedupe()` with non-string values may result in unexpected behavior.
@method dedupe
@param {String[]} array Array of strings to dedupe.
@return {Array} Deduped copy of _array_.
@static
@since 3.4.0
**/
YArray.dedupe = function (array) {
var hash = {},
results = [],
i, item, len;
for (i = 0, len = array.length; i < len; ++i) {
item = array[i];
if (!hasOwn.call(hash, item)) {
hash[item] = 1;
results.push(item);
}
}
return results;
};
/**
Executes the supplied function on each item in the array. This method wraps
the native ES5 `Array.forEach()` method if available.
@method each
@param {Array} array Array to iterate.
@param {Function} fn Function to execute on each item in the array. The function
will receive the following arguments:
@param {Any} fn.item Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {YUI} The YUI instance.
@static
**/
YArray.each = YArray.forEach = Native.forEach ? function (array, fn, thisObj) {
Native.forEach.call(array || [], fn, thisObj || Y);
return Y;
} : function (array, fn, thisObj) {
for (var i = 0, len = (array && array.length) || 0; i < len; ++i) {
if (i in array) {
fn.call(thisObj || Y, array[i], i, array);
}
}
return Y;
};
/**
Alias for `each()`.
@method forEach
@static
**/
/**
Returns an object using the first array as keys and the second as values. If
the second array is not provided, or if it doesn't contain the same number of
values as the first array, then `true` will be used in place of the missing
values.
@example
Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']);
// => {a: 'foo', b: 'bar', c: true}
@method hash
@param {String[]} keys Array of strings to use as keys.
@param {Array} [values] Array to use as values.
@return {Object} Hash using the first array as keys and the second as values.
@static
**/
YArray.hash = function (keys, values) {
var hash = {},
vlen = (values && values.length) || 0,
i, len;
for (i = 0, len = keys.length; i < len; ++i) {
if (i in keys) {
hash[keys[i]] = vlen > i && i in values ? values[i] : true;
}
}
return hash;
};
/**
Returns the index of the first item in the array that's equal (using a strict
equality check) to the specified _value_, or `-1` if the value isn't found.
This method wraps the native ES5 `Array.indexOf()` method if available.
@method indexOf
@param {Array} array Array to search.
@param {Any} value Value to search for.
@return {Number} Index of the item strictly equal to _value_, or `-1` if not
found.
@static
**/
YArray.indexOf = Native.indexOf ? function (array, value) {
// TODO: support fromIndex
return Native.indexOf.call(array, value);
} : function (array, value) {
for (var i = 0, len = array.length; i < len; ++i) {
if (array[i] === value) {
return i;
}
}
return -1;
};
/**
Numeric sort convenience function.
The native `Array.prototype.sort()` function converts values to strings and
sorts them in lexicographic order, which is unsuitable for sorting numeric
values. Provide `Array.numericSort` as a custom sort function when you want
to sort values in numeric order.
@example
[42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort);
// => [4, 8, 15, 16, 23, 42]
@method numericSort
@param {Number} a First value to compare.
@param {Number} b Second value to compare.
@return {Number} Difference between _a_ and _b_.
@static
**/
YArray.numericSort = function (a, b) {
return a - b;
};
/**
Executes the supplied function on each item in the array. Returning a truthy
value from the function will stop the processing of remaining items.
@method some
@param {Array} array Array to iterate over.
@param {Function} fn Function to execute on each item. The function will receive
the following arguments:
@param {Any} fn.value Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated over.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {Boolean} `true` if the function returns a truthy value on any of the
items in the array; `false` otherwise.
@static
**/
YArray.some = Native.some ? function (array, fn, thisObj) {
return Native.some.call(array, fn, thisObj);
} : function (array, fn, thisObj) {
for (var i = 0, len = array.length; i < len; ++i) {
if (i in array && fn.call(thisObj, array[i], i, array)) {
return true;
}
}
return false;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* A simple FIFO queue. Items are added to the Queue with add(1..n items) and
* removed using next().
*
* @class Queue
* @constructor
* @param {MIXED} item* 0..n items to seed the queue.
*/
function Queue() {
this._init();
this.add.apply(this, arguments);
}
Queue.prototype = {
/**
* Initialize the queue
*
* @method _init
* @protected
*/
_init: function() {
/**
* The collection of enqueued items
*
* @property _q
* @type Array
* @protected
*/
this._q = [];
},
/**
* Get the next item in the queue. FIFO support
*
* @method next
* @return {MIXED} the next item in the queue.
*/
next: function() {
return this._q.shift();
},
/**
* Get the last in the queue. LIFO support.
*
* @method last
* @return {MIXED} the last item in the queue.
*/
last: function() {
return this._q.pop();
},
/**
* Add 0..n items to the end of the queue.
*
* @method add
* @param {MIXED} item* 0..n items.
* @return {object} this queue.
*/
add: function() {
this._q.push.apply(this._q, arguments);
return this;
},
/**
* Returns the current number of queued items.
*
* @method size
* @return {Number} The size.
*/
size: function() {
return this._q.length;
}
};
Y.Queue = Queue;
YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue();
/**
The YUI module contains the components required for building the YUI seed file.
This includes the script loading mechanism, a simple queue, and the core
utilities for the library.
@module yui
@submodule yui-base
**/
var CACHED_DELIMITER = '__',
hasOwn = Object.prototype.hasOwnProperty,
isObject = Y.Lang.isObject;
/**
Returns a wrapper for a function which caches the return value of that function,
keyed off of the combined string representation of the argument values provided
when the wrapper is called.
Calling this function again with the same arguments will return the cached value
rather than executing the wrapped function.
Note that since the cache is keyed off of the string representation of arguments
passed to the wrapper function, arguments that aren't strings and don't provide
a meaningful `toString()` method may result in unexpected caching behavior. For
example, the objects `{}` and `{foo: 'bar'}` would both be converted to the
string `[object Object]` when used as a cache key.
@method cached
@param {Function} source The function to memoize.
@param {Object} [cache={}] Object in which to store cached values. You may seed
this object with pre-existing cached values if desired.
@param {any} [refetch] If supplied, this value is compared with the cached value
using a `==` comparison. If the values are equal, the wrapped function is
executed again even though a cached value exists.
@return {Function} Wrapped function.
@for YUI
**/
Y.cached = function (source, cache, refetch) {
cache || (cache = {});
return function (arg) {
var key = arguments.length > 1 ?
Array.prototype.join.call(arguments, CACHED_DELIMITER) :
arg.toString();
if (!(key in cache) || (refetch && cache[key] == refetch)) {
cache[key] = source.apply(source, arguments);
}
return cache[key];
};
};
/**
Returns a new object containing all of the properties of all the supplied
objects. The properties from later objects will overwrite those in earlier
objects.
Passing in a single object will create a shallow copy of it. For a deep copy,
use `clone()`.
@method merge
@param {Object} objects* One or more objects to merge.
@return {Object} A new merged object.
**/
Y.merge = function () {
var args = arguments,
i = 0,
len = args.length,
result = {};
for (; i < len; ++i) {
Y.mix(result, args[i], true);
}
return result;
};
/**
Mixes _supplier_'s properties into _receiver_. Properties will not be
overwritten or merged unless the _overwrite_ or _merge_ parameters are `true`,
respectively.
In the default mode (0), only properties the supplier owns are copied (prototype
properties are not copied). The following copying modes are available:
* `0`: _Default_. Object to object.
* `1`: Prototype to prototype.
* `2`: Prototype to prototype and object to object.
* `3`: Prototype to object.
* `4`: Object to prototype.
@method mix
@param {Function|Object} receiver The object or function to receive the mixed
properties.
@param {Function|Object} supplier The object or function supplying the
properties to be mixed.
@param {Boolean} [overwrite=false] If `true`, properties that already exist
on the receiver will be overwritten with properties from the supplier.
@param {String[]} [whitelist] An array of property names to copy. If
specified, only the whitelisted properties will be copied, and all others
will be ignored.
@param {Int} [mode=0] Mix mode to use. See above for available modes.
@param {Boolean} [merge=false] If `true`, objects and arrays that already
exist on the receiver will have the corresponding object/array from the
supplier merged into them, rather than being skipped or overwritten. When
both _overwrite_ and _merge_ are `true`, _merge_ takes precedence.
@return {Function|Object|YUI} The receiver, or the YUI instance if the
specified receiver is falsy.
**/
Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) {
var alwaysOverwrite, exists, from, i, key, len, to;
// If no supplier is given, we return the receiver. If no receiver is given,
// we return Y. Returning Y doesn't make much sense to me, but it's
// grandfathered in for backcompat reasons.
if (!receiver || !supplier) {
return receiver || Y;
}
if (mode) {
// In mode 2 (prototype to prototype and object to object), we recurse
// once to do the proto to proto mix. The object to object mix will be
// handled later on.
if (mode === 2) {
Y.mix(receiver.prototype, supplier.prototype, overwrite,
whitelist, 0, merge);
}
// Depending on which mode is specified, we may be copying from or to
// the prototypes of the supplier and receiver.
from = mode === 1 || mode === 3 ? supplier.prototype : supplier;
to = mode === 1 || mode === 4 ? receiver.prototype : receiver;
// If either the supplier or receiver doesn't actually have a
// prototype property, then we could end up with an undefined `from`
// or `to`. If that happens, we abort and return the receiver.
if (!from || !to) {
return receiver;
}
} else {
from = supplier;
to = receiver;
}
// If `overwrite` is truthy and `merge` is falsy, then we can skip a call
// to `hasOwnProperty` on each iteration and save some time.
alwaysOverwrite = overwrite && !merge;
if (whitelist) {
for (i = 0, len = whitelist.length; i < len; ++i) {
key = whitelist[i];
// We call `Object.prototype.hasOwnProperty` instead of calling
// `hasOwnProperty` on the object itself, since the object's
// `hasOwnProperty` method may have been overridden or removed.
// Also, some native objects don't implement a `hasOwnProperty`
// method.
if (!hasOwn.call(from, key)) {
continue;
}
exists = alwaysOverwrite ? false : hasOwn.call(to, key);
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
// If we're in merge mode, and the key is present on both
// objects, and the value on both objects is either an object or
// an array (but not a function), then we recurse to merge the
// `from` value into the `to` value instead of overwriting it.
//
// Note: It's intentional that the whitelist isn't passed to the
// recursive call here. This is legacy behavior that lots of
// code still depends on.
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
// We're not in merge mode, so we'll only copy the `from` value
// to the `to` value if we're in overwrite mode or if the
// current key doesn't exist on the `to` object.
to[key] = from[key];
}
}
} else {
for (key in from) {
// The code duplication here is for runtime performance reasons.
// Combining whitelist and non-whitelist operations into a single
// loop or breaking the shared logic out into a function both result
// in worse performance, and Y.mix is critical enough that the byte
// tradeoff is worth it.
if (!hasOwn.call(from, key)) {
continue;
}
exists = alwaysOverwrite ? false : hasOwn.call(to, key);
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
to[key] = from[key];
}
}
// If this is an IE browser with the JScript enumeration bug, force
// enumeration of the buggy properties by making a recursive call with
// the buggy properties as the whitelist.
if (Y.Object._hasEnumBug) {
Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge);
}
}
return receiver;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Adds utilities to the YUI instance for working with objects.
*
* @class Object
*/
var hasOwn = Object.prototype.hasOwnProperty,
// If either MooTools or Prototype is on the page, then there's a chance that we
// can't trust "native" language features to actually be native. When this is
// the case, we take the safe route and fall back to our own non-native
// implementations.
win = Y.config.win,
unsafeNatives = win && !!(win.MooTools || win.Prototype),
UNDEFINED, // <-- Note the comma. We're still declaring vars.
/**
* Returns a new object that uses _obj_ as its prototype. This method wraps the
* native ES5 `Object.create()` method if available, but doesn't currently
* pass through `Object.create()`'s second argument (properties) in order to
* ensure compatibility with older browsers.
*
* @method ()
* @param {Object} obj Prototype object.
* @return {Object} New object using _obj_ as its prototype.
* @static
*/
O = Y.Object = (!unsafeNatives && Object.create) ? function (obj) {
// We currently wrap the native Object.create instead of simply aliasing it
// to ensure consistency with our fallback shim, which currently doesn't
// support Object.create()'s second argument (properties). Once we have a
// safe fallback for the properties arg, we can stop wrapping
// Object.create().
return Object.create(obj);
} : (function () {
// Reusable constructor function for the Object.create() shim.
function F() {}
// The actual shim.
return function (obj) {
F.prototype = obj;
return new F();
};
}()),
/**
* Property names that IE doesn't enumerate in for..in loops, even when they
* should be enumerable. When `_hasEnumBug` is `true`, it's necessary to
* manually enumerate these properties.
*
* @property _forceEnum
* @type String[]
* @protected
* @static
*/
forceEnum = O._forceEnum = [
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'toLocaleString',
'valueOf'
],
/**
* `true` if this browser has the JScript enumeration bug that prevents
* enumeration of the properties named in the `_forceEnum` array, `false`
* otherwise.
*
* See:
* - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug>
* - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation>
*
* @property _hasEnumBug
* @type {Boolean}
* @protected
* @static
*/
hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'),
/**
* Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or
* exists only on _obj_'s prototype. This is essentially a safer version of
* `obj.hasOwnProperty()`.
*
* @method owns
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
owns = O.owns = function (obj, key) {
return !!obj && hasOwn.call(obj, key);
}; // <-- End of var declarations.
/**
* Alias for `owns()`.
*
* @method hasKey
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
O.hasKey = owns;
/**
* Returns an array containing the object's enumerable keys. Does not include
* prototype keys or non-enumerable keys.
*
* Note that keys are returned in enumeration order (that is, in the same order
* that they would be enumerated by a `for-in` loop), which may not be the same
* as the order in which they were defined.
*
* This method is an alias for the native ES5 `Object.keys()` method if
* available.
*
* @example
*
* Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'});
* // => ['a', 'b', 'c']
*
* @method keys
* @param {Object} obj An object.
* @return {String[]} Array of keys.
* @static
*/
O.keys = (!unsafeNatives && Object.keys) || function (obj) {
if (!Y.Lang.isObject(obj)) {
throw new TypeError('Object.keys called on a non-object');
}
var keys = [],
i, key, len;
for (key in obj) {
if (owns(obj, key)) {
keys.push(key);
}
}
if (hasEnumBug) {
for (i = 0, len = forceEnum.length; i < len; ++i) {
key = forceEnum[i];
if (owns(obj, key)) {
keys.push(key);
}
}
}
return keys;
};
/**
* Returns an array containing the values of the object's enumerable keys.
*
* Note that values are returned in enumeration order (that is, in the same
* order that they would be enumerated by a `for-in` loop), which may not be the
* same as the order in which they were defined.
*
* @example
*
* Y.Object.values({a: 'foo', b: 'bar', c: 'baz'});
* // => ['foo', 'bar', 'baz']
*
* @method values
* @param {Object} obj An object.
* @return {Array} Array of values.
* @static
*/
O.values = function (obj) {
var keys = O.keys(obj),
i = 0,
len = keys.length,
values = [];
for (; i < len; ++i) {
values.push(obj[keys[i]]);
}
return values;
};
/**
* Returns the number of enumerable keys owned by an object.
*
* @method size
* @param {Object} obj An object.
* @return {Number} The object's size.
* @static
*/
O.size = function (obj) {
return O.keys(obj).length;
};
/**
* Returns `true` if the object owns an enumerable property with the specified
* value.
*
* @method hasValue
* @param {Object} obj An object.
* @param {any} value The value to search for.
* @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise.
* @static
*/
O.hasValue = function (obj, value) {
return Y.Array.indexOf(O.values(obj), value) > -1;
};
/**
* Executes a function on each enumerable property in _obj_. The function
* receives the value, the key, and the object itself as parameters (in that
* order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method each
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {YUI} the YUI instance.
* @chainable
* @static
*/
O.each = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
fn.call(thisObj || Y, obj[key], key, obj);
}
}
return Y;
};
/**
* Executes a function on each enumerable property in _obj_, but halts if the
* function returns a truthy value. The function receives the value, the key,
* and the object itself as paramters (in that order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method some
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {Boolean} `true` if any execution of _fn_ returns a truthy value,
* `false` otherwise.
* @static
*/
O.some = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
if (fn.call(thisObj || Y, obj[key], key, obj)) {
return true;
}
}
}
return false;
};
/**
* Retrieves the sub value at the provided path,
* from the value object provided.
*
* @method getValue
* @static
* @param o The object from which to extract the property value.
* @param path {Array} A path array, specifying the object traversal path
* from which to obtain the sub value.
* @return {Any} The value stored in the path, undefined if not found,
* undefined if the source is not an object. Returns the source object
* if an empty path is provided.
*/
O.getValue = function(o, path) {
if (!Y.Lang.isObject(o)) {
return UNDEFINED;
}
var i,
p = Y.Array(path),
l = p.length;
for (i = 0; o !== UNDEFINED && i < l; i++) {
o = o[p[i]];
}
return o;
};
/**
* Sets the sub-attribute value at the provided path on the
* value object. Returns the modified value object, or
* undefined if the path is invalid.
*
* @method setValue
* @static
* @param o The object on which to set the sub value.
* @param path {Array} A path array, specifying the object traversal path
* at which to set the sub value.
* @param val {Any} The new value for the sub-attribute.
* @return {Object} The modified object, with the new sub value set, or
* undefined, if the path was invalid.
*/
O.setValue = function(o, path, val) {
var i,
p = Y.Array(path),
leafIdx = p.length - 1,
ref = o;
if (leafIdx >= 0) {
for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) {
ref = ref[p[i]];
}
if (ref !== UNDEFINED) {
ref[p[i]] = val;
} else {
return UNDEFINED;
}
}
return o;
};
/**
* Returns `true` if the object has no enumerable properties of its own.
*
* @method isEmpty
* @param {Object} obj An object.
* @return {Boolean} `true` if the object is empty.
* @static
* @since 3.2.0
*/
O.isEmpty = function (obj) {
return !O.keys(obj).length;
};
/**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and the
* core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* YUI user agent detection.
* Do not fork for a browser if it can be avoided. Use feature detection when
* you can. Use the user agent as a last resort. For all fields listed
* as @type float, UA stores a version number for the browser engine,
* 0 otherwise. This value may or may not map to the version number of
* the browser using the engine. The value is presented as a float so
* that it can easily be used for boolean evaluation as well as for
* looking for a particular range of versions. Because of this,
* some of the granularity of the version info may be lost. The fields that
* are @type string default to null. The API docs list the values that
* these fields can have.
* @class UA
* @static
*/
/**
* Static method for parsing the UA string. Defaults to assigning it's value to Y.UA
* @static
* @method Env.parseUA
* @param {String} subUA Parse this UA string instead of navigator.userAgent
* @returns {Object} The Y.UA object
*/
YUI.Env.parseUA = function(subUA) {
var numberify = function(s) {
var c = 0;
return parseFloat(s.replace(/\./g, function() {
return (c++ == 1) ? '' : '.';
}));
},
win = Y.config.win,
nav = win && win.navigator,
o = {
/**
* Internet Explorer version number or 0. Example: 6
* @property ie
* @type float
* @static
*/
ie: 0,
/**
* Opera version number or 0. Example: 9.2
* @property opera
* @type float
* @static
*/
opera: 0,
/**
* Gecko engine revision number. Will evaluate to 1 if Gecko
* is detected but the revision could not be found. Other browsers
* will be 0. Example: 1.8
* <pre>
* Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7
* Firefox 1.5.0.9: 1.8.0.9 <-- 1.8
* Firefox 2.0.0.3: 1.8.1.3 <-- 1.81
* Firefox 3.0 <-- 1.9
* Firefox 3.5 <-- 1.91
* </pre>
* @property gecko
* @type float
* @static
*/
gecko: 0,
/**
* AppleWebKit version. KHTML browsers that are not WebKit browsers
* will evaluate to 1, other browsers 0. Example: 418.9
* <pre>
* Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the
* latest available for Mac OSX 10.3.
* Safari 2.0.2: 416 <-- hasOwnProperty introduced
* Safari 2.0.4: 418 <-- preventDefault fixed
* Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run
* different versions of webkit
* Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been
* updated, but not updated
* to the latest patch.
* Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native
* SVG and many major issues fixed).
* Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic
* update from 2.x via the 10.4.11 OS patch.
* Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event.
* yahoo.com user agent hack removed.
* </pre>
* http://en.wikipedia.org/wiki/Safari_version_history
* @property webkit
* @type float
* @static
*/
webkit: 0,
/**
* Safari will be detected as webkit, but this property will also
* be populated with the Safari version number
* @property safari
* @type float
* @static
*/
safari: 0,
/**
* Chrome will be detected as webkit, but this property will also
* be populated with the Chrome version number
* @property chrome
* @type float
* @static
*/
chrome: 0,
/**
* The mobile property will be set to a string containing any relevant
* user agent information when a modern mobile browser is detected.
* Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series
* devices with the WebKit-based browser, and Opera Mini.
* @property mobile
* @type string
* @default null
* @static
*/
mobile: null,
/**
* Adobe AIR version number or 0. Only populated if webkit is detected.
* Example: 1.0
* @property air
* @type float
*/
air: 0,
/**
* Detects Apple iPad's OS version
* @property ipad
* @type float
* @static
*/
ipad: 0,
/**
* Detects Apple iPhone's OS version
* @property iphone
* @type float
* @static
*/
iphone: 0,
/**
* Detects Apples iPod's OS version
* @property ipod
* @type float
* @static
*/
ipod: 0,
/**
* General truthy check for iPad, iPhone or iPod
* @property ios
* @type float
* @default null
* @static
*/
ios: null,
/**
* Detects Googles Android OS version
* @property android
* @type float
* @static
*/
android: 0,
/**
* Detects Palms WebOS version
* @property webos
* @type float
* @static
*/
webos: 0,
/**
* Google Caja version number or 0.
* @property caja
* @type float
*/
caja: nav && nav.cajaVersion,
/**
* Set to true if the page appears to be in SSL
* @property secure
* @type boolean
* @static
*/
secure: false,
/**
* The operating system. Currently only detecting windows or macintosh
* @property os
* @type string
* @default null
* @static
*/
os: null
},
ua = subUA || nav && nav.userAgent,
loc = win && win.location,
href = loc && loc.href,
m;
o.secure = href && (href.toLowerCase().indexOf('https') === 0);
if (ua) {
if ((/windows|win32/i).test(ua)) {
o.os = 'windows';
} else if ((/macintosh/i).test(ua)) {
o.os = 'macintosh';
} else if ((/rhino/i).test(ua)) {
o.os = 'rhino';
}
// Modern KHTML browsers should qualify as Safari X-Grade
if ((/KHTML/).test(ua)) {
o.webkit = 1;
}
// Modern WebKit browsers are at least X-Grade
m = ua.match(/AppleWebKit\/([^\s]*)/);
if (m && m[1]) {
o.webkit = numberify(m[1]);
o.safari = o.webkit;
// Mobile browser check
if (/ Mobile\//.test(ua)) {
o.mobile = 'Apple'; // iPhone or iPod Touch
m = ua.match(/OS ([^\s]*)/);
if (m && m[1]) {
m = numberify(m[1].replace('_', '.'));
}
o.ios = m;
o.ipad = o.ipod = o.iphone = 0;
m = ua.match(/iPad|iPod|iPhone/);
if (m && m[0]) {
o[m[0].toLowerCase()] = o.ios;
}
} else {
m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/);
if (m) {
// Nokia N-series, webOS, ex: NokiaN95
o.mobile = m[0];
}
if (/webOS/.test(ua)) {
o.mobile = 'WebOS';
m = ua.match(/webOS\/([^\s]*);/);
if (m && m[1]) {
o.webos = numberify(m[1]);
}
}
if (/ Android/.test(ua)) {
if (/Mobile/.test(ua)) {
o.mobile = 'Android';
}
m = ua.match(/Android ([^\s]*);/);
if (m && m[1]) {
o.android = numberify(m[1]);
}
}
}
m = ua.match(/Chrome\/([^\s]*)/);
if (m && m[1]) {
o.chrome = numberify(m[1]); // Chrome
o.safari = 0; //Reset safari back to 0
} else {
m = ua.match(/AdobeAIR\/([^\s]*)/);
if (m) {
o.air = m[0]; // Adobe AIR 1.0 or better
}
}
}
if (!o.webkit) { // not webkit
// @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
m = ua.match(/Opera[\s\/]([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]);
m = ua.match(/Version\/([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]); // opera 10+
}
m = ua.match(/Opera Mini[^;]*/);
if (m) {
o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
}
} else { // not opera or webkit
m = ua.match(/MSIE\s([^;]*)/);
if (m && m[1]) {
o.ie = numberify(m[1]);
} else { // not opera, webkit, or ie
m = ua.match(/Gecko\/([^\s]*)/);
if (m) {
o.gecko = 1; // Gecko detected, look for revision
m = ua.match(/rv:([^\s\)]*)/);
if (m && m[1]) {
o.gecko = numberify(m[1]);
}
}
}
}
}
}
YUI.Env.UA = o;
return o;
};
Y.UA = YUI.Env.UA || YUI.Env.parseUA();
YUI.Env.aliases = {
"anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"],
"app": ["controller","model","model-list","view"],
"attribute": ["attribute-base","attribute-complex"],
"autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"],
"base": ["base-base","base-pluginhost","base-build"],
"cache": ["cache-base","cache-offline","cache-plugin"],
"collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"],
"dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"],
"datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"],
"datatable": ["datatable-base","datatable-datasource","datatable-sort","datatable-scroll"],
"datatype": ["datatype-number","datatype-date","datatype-xml"],
"datatype-date": ["datatype-date-parse","datatype-date-format"],
"datatype-number": ["datatype-number-parse","datatype-number-format"],
"datatype-xml": ["datatype-xml-parse","datatype-xml-format"],
"dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"],
"dom": ["dom-base","dom-screen","dom-style","selector-native","selector"],
"editor": ["frame","selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"],
"event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside"],
"event-custom": ["event-custom-base","event-custom-complex"],
"event-gestures": ["event-flick","event-move"],
"highlight": ["highlight-base","highlight-accentfold"],
"history": ["history-base","history-hash","history-hash-ie","history-html5"],
"io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"],
"json": ["json-parse","json-stringify"],
"loader": ["loader-base","loader-rollup","loader-yui3"],
"node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"],
"pluginhost": ["pluginhost-base","pluginhost-config"],
"querystring": ["querystring-parse","querystring-stringify"],
"recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"],
"resize": ["resize-base","resize-proxy","resize-constrain"],
"slider": ["slider-base","slider-value-range","clickable-rail","range-slider"],
"text": ["text-accentfold","text-wordbreak"],
"widget": ["widget-base","widget-htmlparser","widget-uievents","widget-skin"]
};
}, '@VERSION@' );
YUI.add('get', function(Y) {
/**
* Provides a mechanism to fetch remote resources and
* insert them into a document.
* @module yui
* @submodule get
*/
/**
* Fetches and inserts one or more script or link nodes into the document
* @class Get
* @static
*/
var ua = Y.UA,
L = Y.Lang,
TYPE_JS = 'text/javascript',
TYPE_CSS = 'text/css',
STYLESHEET = 'stylesheet',
SCRIPT = 'script',
AUTOPURGE = 'autopurge',
UTF8 = 'utf-8',
LINK = 'link',
ASYNC = 'async',
ALL = true,
// FireFox does not support the onload event for link nodes, so
// there is no way to make the css requests synchronous. This means
// that the css rules in multiple files could be applied out of order
// in this browser if a later request returns before an earlier one.
// Safari too.
ONLOAD_SUPPORTED = {
script: ALL,
css: !(ua.webkit || ua.gecko)
},
/**
* hash of queues to manage multiple requests
* @property queues
* @private
*/
queues = {},
/**
* queue index used to generate transaction ids
* @property qidx
* @type int
* @private
*/
qidx = 0,
/**
* interal property used to prevent multiple simultaneous purge
* processes
* @property purging
* @type boolean
* @private
*/
purging,
/**
* Clear timeout state
*
* @method _clearTimeout
* @param {Object} q Queue data
* @private
*/
_clearTimeout = function(q) {
var timer = q.timer;
if (timer) {
clearTimeout(timer);
q.timer = null;
}
},
/**
* Generates an HTML element, this is not appended to a document
* @method _node
* @param {string} type the type of element.
* @param {Object} attr the fixed set of attribute for the type.
* @param {Object} custAttrs optional Any custom attributes provided by the user.
* @param {Window} win optional window to create the element in.
* @return {HTMLElement} the generated node.
* @private
*/
_node = function(type, attr, custAttrs, win) {
var w = win || Y.config.win,
d = w.document,
n = d.createElement(type),
i;
if (custAttrs) {
Y.mix(attr, custAttrs);
}
for (i in attr) {
if (attr[i] && attr.hasOwnProperty(i)) {
n.setAttribute(i, attr[i]);
}
}
return n;
},
/**
* Generates a link node
* @method _linkNode
* @param {string} url the url for the css file.
* @param {Window} win optional window to create the node in.
* @param {object} attributes optional attributes collection to apply to the
* new node.
* @return {HTMLElement} the generated node.
* @private
*/
_linkNode = function(url, win, attributes) {
return _node(LINK, {
id: Y.guid(),
type: TYPE_CSS,
rel: STYLESHEET,
href: url
}, attributes, win);
},
/**
* Generates a script node
* @method _scriptNode
* @param {string} url the url for the script file.
* @param {Window} win optional window to create the node in.
* @param {object} attributes optional attributes collection to apply to the
* new node.
* @return {HTMLElement} the generated node.
* @private
*/
_scriptNode = function(url, win, attributes) {
return _node(SCRIPT, {
id: Y.guid(),
type: TYPE_JS,
src: url
}, attributes, win);
},
/**
* Returns the data payload for callback functions.
* @method _returnData
* @param {object} q the queue.
* @param {string} msg the result message.
* @param {string} result the status message from the request.
* @return {object} the state data from the request.
* @private
*/
_returnData = function(q, msg, result) {
return {
tId: q.tId,
win: q.win,
data: q.data,
nodes: q.nodes,
msg: msg,
statusText: result,
purge: function() {
_purge(this.tId);
}
};
},
/**
* The transaction is finished
* @method _end
* @param {string} id the id of the request.
* @param {string} msg the result message.
* @param {string} result the status message from the request.
* @private
*/
_end = function(id, msg, result) {
var q = queues[id],
onEnd = q && q.onEnd;
q.finished = true;
if (onEnd) {
onEnd.call(q.context, _returnData(q, msg, result));
}
},
/**
* The request failed, execute fail handler with whatever
* was accomplished. There isn't a failure case at the
* moment unless you count aborted transactions
* @method _fail
* @param {string} id the id of the request
* @private
*/
_fail = function(id, msg) {
Y.log('get failure: ' + msg, 'warn', 'get');
var q = queues[id],
onFailure = q.onFailure;
_clearTimeout(q);
if (onFailure) {
onFailure.call(q.context, _returnData(q, msg));
}
_end(id, msg, 'failure');
},
/**
* Abort the transaction
*
* @method _abort
* @param {Object} id
* @private
*/
_abort = function(id) {
_fail(id, 'transaction ' + id + ' was aborted');
},
/**
* The request is complete, so executing the requester's callback
* @method _complete
* @param {string} id the id of the request.
* @private
*/
_complete = function(id) {
Y.log("Finishing transaction " + id, "info", "get");
var q = queues[id],
onSuccess = q.onSuccess;
_clearTimeout(q);
if (q.aborted) {
_abort(id);
} else {
if (onSuccess) {
onSuccess.call(q.context, _returnData(q));
}
// 3.3.0 had undefined msg for this path.
_end(id, undefined, 'OK');
}
},
/**
* Get node reference, from string
*
* @method _getNodeRef
* @param {String|HTMLElement} nId The node id to find. If an HTMLElement is passed in, it will be returned.
* @param {String} tId Queue id, used to determine document for queue
* @private
*/
_getNodeRef = function(nId, tId) {
var q = queues[tId],
n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId;
if (!n) {
_fail(tId, 'target node not found: ' + nId);
}
return n;
},
/**
* Removes the nodes for the specified queue
* @method _purge
* @param {string} tId the transaction id.
* @private
*/
_purge = function(tId) {
var nodes, doc, parent, sibling, node, attr, insertBefore,
i, l,
q = queues[tId];
if (q) {
nodes = q.nodes;
l = nodes.length;
// TODO: Why is node.parentNode undefined? Which forces us to do this...
/*
doc = q.win.document;
parent = doc.getElementsByTagName('head')[0];
insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0];
if (insertBefore) {
sibling = _getNodeRef(insertBefore, tId);
if (sibling) {
parent = sibling.parentNode;
}
}
*/
for (i = 0; i < l; i++) {
node = nodes[i];
parent = node.parentNode;
if (node.clearAttributes) {
node.clearAttributes();
} else {
// This destroys parentNode ref, so we hold onto it above first.
for (attr in node) {
if (node.hasOwnProperty(attr)) {
delete node[attr];
}
}
}
parent.removeChild(node);
}
}
q.nodes = [];
},
/**
* Progress callback
*
* @method _progress
* @param {string} id The id of the request.
* @param {string} The url which just completed.
* @private
*/
_progress = function(id, url) {
var q = queues[id],
onProgress = q.onProgress,
o;
if (onProgress) {
o = _returnData(q);
o.url = url;
onProgress.call(q.context, o);
}
},
/**
* Timeout detected
* @method _timeout
* @param {string} id the id of the request.
* @private
*/
_timeout = function(id) {
Y.log('Timeout ' + id, 'info', 'get');
var q = queues[id],
onTimeout = q.onTimeout;
if (onTimeout) {
onTimeout.call(q.context, _returnData(q));
}
_end(id, 'timeout', 'timeout');
},
/**
* onload callback
* @method _loaded
* @param {string} id the id of the request.
* @return {string} the result.
* @private
*/
_loaded = function(id, url) {
var q = queues[id],
sync = (q && !q.async);
if (!q) {
return;
}
if (sync) {
_clearTimeout(q);
}
_progress(id, url);
// TODO: Cleaning up flow to have a consistent end point
// !q.finished check is for the async case,
// where scripts may still be loading when we've
// already aborted. Ideally there should be a single path
// for this.
if (!q.finished) {
if (q.aborted) {
_abort(id);
} else {
if ((--q.remaining) === 0) {
_complete(id);
} else if (sync) {
_next(id);
}
}
}
},
/**
* Detects when a node has been loaded. In the case of
* script nodes, this does not guarantee that contained
* script is ready to use.
* @method _trackLoad
* @param {string} type the type of node to track.
* @param {HTMLElement} n the node to track.
* @param {string} id the id of the request.
* @param {string} url the url that is being loaded.
* @private
*/
_trackLoad = function(type, n, id, url) {
// TODO: Can we massage this to use ONLOAD_SUPPORTED[type]?
// IE supports the readystatechange event for script and css nodes
// Opera only for script nodes. Opera support onload for script
// nodes, but this doesn't fire when there is a load failure.
// The onreadystatechange appears to be a better way to respond
// to both success and failure.
if (ua.ie) {
n.onreadystatechange = function() {
var rs = this.readyState;
if ('loaded' === rs || 'complete' === rs) {
// Y.log(id + " onreadstatechange " + url, "info", "get");
n.onreadystatechange = null;
_loaded(id, url);
}
};
} else if (ua.webkit) {
// webkit prior to 3.x is no longer supported
if (type === SCRIPT) {
// Safari 3.x supports the load event for script nodes (DOM2)
n.addEventListener('load', function() {
_loaded(id, url);
}, false);
}
} else {
// FireFox and Opera support onload (but not DOM2 in FF) handlers for
// script nodes. Opera, but not FF, supports the onload event for link nodes.
n.onload = function() {
// Y.log(id + " onload " + url, "info", "get");
_loaded(id, url);
};
n.onerror = function(e) {
_fail(id, e + ': ' + url);
};
}
},
_insertInDoc = function(node, id, win) {
// Add it to the head or insert it before 'insertBefore'.
// Work around IE bug if there is a base tag.
var q = queues[id],
doc = win.document,
insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0],
sibling;
if (insertBefore) {
sibling = _getNodeRef(insertBefore, id);
if (sibling) {
Y.log('inserting before: ' + insertBefore, 'info', 'get');
sibling.parentNode.insertBefore(node, sibling);
}
} else {
// 3.3.0 assumed head is always around.
doc.getElementsByTagName('head')[0].appendChild(node);
}
},
/**
* Loads the next item for a given request
* @method _next
* @param {string} id the id of the request.
* @return {string} the result.
* @private
*/
_next = function(id) {
// Assigning out here for readability
var q = queues[id],
type = q.type,
attrs = q.attributes,
win = q.win,
timeout = q.timeout,
node,
url;
if (q.url.length > 0) {
url = q.url.shift();
Y.log('attempting to load ' + url, 'info', 'get');
// !q.timer ensures that this only happens once for async
if (timeout && !q.timer) {
q.timer = setTimeout(function() {
_timeout(id);
}, timeout);
}
if (type === SCRIPT) {
node = _scriptNode(url, win, attrs);
} else {
node = _linkNode(url, win, attrs);
}
// add the node to the queue so we can return it in the callback
q.nodes.push(node);
_trackLoad(type, node, id, url);
_insertInDoc(node, id, win);
if (!ONLOAD_SUPPORTED[type]) {
_loaded(id, url);
}
if (q.async) {
// For sync, the _next call is chained in _loaded
_next(id);
}
}
},
/**
* Removes processed queues and corresponding nodes
* @method _autoPurge
* @private
*/
_autoPurge = function() {
if (purging) {
return;
}
purging = true;
var i, q;
for (i in queues) {
if (queues.hasOwnProperty(i)) {
q = queues[i];
if (q.autopurge && q.finished) {
_purge(q.tId);
delete queues[i];
}
}
}
purging = false;
},
/**
* Saves the state for the request and begins loading
* the requested urls
* @method queue
* @param {string} type the type of node to insert.
* @param {string} url the url to load.
* @param {object} opts the hash of options for this request.
* @return {object} transaction object.
* @private
*/
_queue = function(type, url, opts) {
opts = opts || {};
var id = 'q' + (qidx++),
thresh = opts.purgethreshold || Y.Get.PURGE_THRESH,
q;
if (qidx % thresh === 0) {
_autoPurge();
}
// Merge to protect opts (grandfathered in).
q = queues[id] = Y.merge(opts);
// Avoid mix, merge overhead. Known set of props.
q.tId = id;
q.type = type;
q.url = url;
q.finished = false;
q.nodes = [];
q.win = q.win || Y.config.win;
q.context = q.context || q;
q.autopurge = (AUTOPURGE in q) ? q.autopurge : (type === SCRIPT) ? true : false;
q.attributes = q.attributes || {};
q.attributes.charset = opts.charset || q.attributes.charset || UTF8;
if (ASYNC in q && type === SCRIPT) {
q.attributes.async = q.async;
}
q.url = (L.isString(q.url)) ? [q.url] : q.url;
// TODO: Do we really need to account for this developer error?
// If the url is undefined, this is probably a trailing comma problem in IE.
if (!q.url[0]) {
q.url.shift();
Y.log('skipping empty url');
}
q.remaining = q.url.length;
_next(id);
return {
tId: id
};
};
Y.Get = {
/**
* The number of request required before an automatic purge.
* Can be configured via the 'purgethreshold' config
* @property PURGE_THRESH
* @static
* @type int
* @default 20
* @private
*/
PURGE_THRESH: 20,
/**
* Abort a transaction
* @method abort
* @static
* @param {string|object} o Either the tId or the object returned from
* script() or css().
*/
abort : function(o) {
var id = (L.isString(o)) ? o : o.tId,
q = queues[id];
if (q) {
Y.log('Aborting ' + id, 'info', 'get');
q.aborted = true;
}
},
/**
* Fetches and inserts one or more script nodes into the head
* of the current document or the document in a specified window.
*
* @method script
* @static
* @param {string|string[]} url the url or urls to the script(s).
* @param {object} opts Options:
* <dl>
* <dt>onSuccess</dt>
* <dd>
* callback to execute when the script(s) are finished loading
* The callback receives an object back with the following
* data:
* <dl>
* <dt>win</dt>
* <dd>the window the script(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove the nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onTimeout</dt>
* <dd>
* callback to execute when a timeout occurs.
* The callback receives an object back with the following
* data:
* <dl>
* <dt>win</dt>
* <dd>the window the script(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove the nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onEnd</dt>
* <dd>a function that executes when the transaction finishes,
* regardless of the exit path</dd>
* <dt>onFailure</dt>
* <dd>
* callback to execute when the script load operation fails
* The callback receives an object back with the following
* data:
* <dl>
* <dt>win</dt>
* <dd>the window the script(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted successfully</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove any nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onProgress</dt>
* <dd>callback to execute when each individual file is done loading
* (useful when passing in an array of js files). Receives the same
* payload as onSuccess, with the addition of a <code>url</code>
* property, which identifies the file which was loaded.</dd>
* <dt>async</dt>
* <dd>
* <p>When passing in an array of JS files, setting this flag to true
* will insert them into the document in parallel, as opposed to the
* default behavior, which is to chain load them serially. It will also
* set the async attribute on the script node to true.</p>
* <p>Setting async:true
* will lead to optimal file download performance allowing the browser to
* download multiple scripts in parallel, and execute them as soon as they
* are available.</p>
* <p>Note that async:true does not guarantee execution order of the
* scripts being downloaded. They are executed in whichever order they
* are received.</p>
* </dd>
* <dt>context</dt>
* <dd>the execution context for the callbacks</dd>
* <dt>win</dt>
* <dd>a window other than the one the utility occupies</dd>
* <dt>autopurge</dt>
* <dd>
* setting to true will let the utilities cleanup routine purge
* the script once loaded
* </dd>
* <dt>purgethreshold</dt>
* <dd>
* The number of transaction before autopurge should be initiated
* </dd>
* <dt>data</dt>
* <dd>
* data that is supplied to the callback when the script(s) are
* loaded.
* </dd>
* <dt>insertBefore</dt>
* <dd>node or node id that will become the new node's nextSibling.
* If this is not specified, nodes will be inserted before a base
* tag should it exist. Otherwise, the nodes will be appended to the
* end of the document head.</dd>
* </dl>
* <dt>charset</dt>
* <dd>Node charset, default utf-8 (deprecated, use the attributes
* config)</dd>
* <dt>attributes</dt>
* <dd>An object literal containing additional attributes to add to
* the link tags</dd>
* <dt>timeout</dt>
* <dd>Number of milliseconds to wait before aborting and firing
* the timeout event</dd>
* <pre>
* Y.Get.script(
* ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js",
* "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"],
* {
* onSuccess: function(o) {
* this.log("won't cause error because Y is the context");
* Y.log(o.data); // foo
* Y.log(o.nodes.length === 2) // true
* // o.purge(); // optionally remove the script nodes
* // immediately
* },
* onFailure: function(o) {
* Y.log("transaction failed");
* },
* onTimeout: function(o) {
* Y.log("transaction timed out");
* },
* data: "foo",
* timeout: 10000, // 10 second timeout
* context: Y, // make the YUI instance
* // win: otherframe // target another window/frame
* autopurge: true // allow the utility to choose when to
* // remove the nodes
* purgetheshold: 1 // purge previous transaction before
* // next transaction
* });.
* </pre>
* @return {tId: string} an object containing info about the
* transaction.
*/
script: function(url, opts) {
return _queue(SCRIPT, url, opts);
},
/**
* Fetches and inserts one or more css link nodes into the
* head of the current document or the document in a specified
* window.
* @method css
* @static
* @param {string} url the url or urls to the css file(s).
* @param {object} opts Options:
* <dl>
* <dt>onSuccess</dt>
* <dd>
* callback to execute when the css file(s) are finished loading
* The callback receives an object back with the following
* data:
* <dl>win</dl>
* <dd>the window the link nodes(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove the nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onProgress</dt>
* <dd>callback to execute when each individual file is done loading (useful when passing in an array of css files). Receives the same
* payload as onSuccess, with the addition of a <code>url</code> property, which identifies the file which was loaded. Currently only useful for non Webkit/Gecko browsers,
* where onload for css is detected accurately.</dd>
* <dt>async</dt>
* <dd>When passing in an array of css files, setting this flag to true will insert them
* into the document in parallel, as oppposed to the default behavior, which is to chain load them (where possible).
* This flag is more useful for scripts currently, since for css Get only chains if not Webkit/Gecko.</dd>
* <dt>context</dt>
* <dd>the execution context for the callbacks</dd>
* <dt>win</dt>
* <dd>a window other than the one the utility occupies</dd>
* <dt>data</dt>
* <dd>
* data that is supplied to the callbacks when the nodes(s) are
* loaded.
* </dd>
* <dt>insertBefore</dt>
* <dd>node or node id that will become the new node's nextSibling</dd>
* <dt>charset</dt>
* <dd>Node charset, default utf-8 (deprecated, use the attributes
* config)</dd>
* <dt>attributes</dt>
* <dd>An object literal containing additional attributes to add to
* the link tags</dd>
* </dl>
* <pre>
* Y.Get.css("http://localhost/css/menu.css");
* </pre>
* <pre>
* Y.Get.css(
* ["http://localhost/css/menu.css",
* "http://localhost/css/logger.css"], {
* insertBefore: 'custom-styles' // nodes will be inserted
* // before the specified node
* });.
* </pre>
* @return {tId: string} an object containing info about the
* transaction.
*/
css: function(url, opts) {
return _queue('css', url, opts);
}
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('features', function(Y) {
var feature_tests = {};
Y.mix(Y.namespace('Features'), {
tests: feature_tests,
add: function(cat, name, o) {
feature_tests[cat] = feature_tests[cat] || {};
feature_tests[cat][name] = o;
},
all: function(cat, args) {
var cat_o = feature_tests[cat],
// results = {};
result = [];
if (cat_o) {
Y.Object.each(cat_o, function(v, k) {
result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0));
});
}
return (result.length) ? result.join(';') : '';
},
test: function(cat, name, args) {
args = args || [];
var result, ua, test,
cat_o = feature_tests[cat],
feature = cat_o && cat_o[name];
if (!feature) {
Y.log('Feature test ' + cat + ', ' + name + ' not found');
} else {
result = feature.result;
if (Y.Lang.isUndefined(result)) {
ua = feature.ua;
if (ua) {
result = (Y.UA[ua]);
}
test = feature.test;
if (test && ((!ua) || result)) {
result = test.apply(Y, args);
}
feature.result = result;
}
}
return result;
}
});
// Y.Features.add("load", "1", {});
// Y.Features.test("load", "1");
// caps=1:1;2:0;3:1;
/* This file is auto-generated by src/loader/scripts/meta_join.py */
var add = Y.Features.add;
// graphics-canvas-default
add('load', '0', {
"name": "graphics-canvas-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
});
// autocomplete-list-keys
add('load', '1', {
"name": "autocomplete-list-keys",
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
});
// graphics-svg
add('load', '2', {
"name": "graphics-svg",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
});
// history-hash-ie
add('load', '3', {
"name": "history-hash-ie",
"test": function (Y) {
var docMode = Y.config.doc && Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
});
// graphics-vml-default
add('load', '4', {
"name": "graphics-vml-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-svg-default
add('load', '5', {
"name": "graphics-svg-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
});
// widget-base-ie
add('load', '6', {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
});
// transition-timer
add('load', '7', {
"name": "transition-timer",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
node = (DOCUMENT) ? DOCUMENT.documentElement: null,
ret = true;
if (node && node.style) {
ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style);
}
return ret;
},
"trigger": "transition"
});
// dom-style-ie
add('load', '8', {
"name": "dom-style-ie",
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
});
// selector-css2
add('load', '9', {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
});
// event-base-ie
add('load', '10', {
"name": "event-base-ie",
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
});
// dd-gestures
add('load', '11', {
"name": "dd-gestures",
"test": function(Y) {
return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome));
},
"trigger": "dd-drag"
});
// scrollview-base-ie
add('load', '12', {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
});
// graphics-canvas
add('load', '13', {
"name": "graphics-canvas",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-vml
add('load', '14', {
"name": "graphics-vml",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('intl-base', function(Y) {
/**
* The Intl utility provides a central location for managing sets of
* localized resources (strings and formatting patterns).
*
* @class Intl
* @uses EventTarget
* @static
*/
var SPLIT_REGEX = /[, ]/;
Y.mix(Y.namespace('Intl'), {
/**
* Returns the language among those available that
* best matches the preferred language list, using the Lookup
* algorithm of BCP 47.
* If none of the available languages meets the user's preferences,
* then "" is returned.
* Extended language ranges are not supported.
*
* @method lookupBestLang
* @param {String[] | String} preferredLanguages The list of preferred
* languages in descending preference order, represented as BCP 47
* language tags. A string array or a comma-separated list.
* @param {String[]} availableLanguages The list of languages
* that the application supports, represented as BCP 47 language
* tags.
*
* @return {String} The available language that best matches the
* preferred language list, or "".
* @since 3.1.0
*/
lookupBestLang: function(preferredLanguages, availableLanguages) {
var i, language, result, index;
// check whether the list of available languages contains language;
// if so return it
function scan(language) {
var i;
for (i = 0; i < availableLanguages.length; i += 1) {
if (language.toLowerCase() ===
availableLanguages[i].toLowerCase()) {
return availableLanguages[i];
}
}
}
if (Y.Lang.isString(preferredLanguages)) {
preferredLanguages = preferredLanguages.split(SPLIT_REGEX);
}
for (i = 0; i < preferredLanguages.length; i += 1) {
language = preferredLanguages[i];
if (!language || language === '*') {
continue;
}
// check the fallback sequence for one language
while (language.length > 0) {
result = scan(language);
if (result) {
return result;
} else {
index = language.lastIndexOf('-');
if (index >= 0) {
language = language.substring(0, index);
// one-character subtags get cut along with the
// following subtag
if (index >= 2 && language.charAt(index - 2) === '-') {
language = language.substring(0, index - 2);
}
} else {
// nothing available for this language
break;
}
}
}
}
return '';
}
});
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('yui-log', function(Y) {
/**
* Provides console log capability and exposes a custom event for
* console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-log
*/
var INSTANCE = Y,
LOGEVENT = 'yui:log',
UNDEFINED = 'undefined',
LEVELS = { debug: 1,
info: 1,
warn: 1,
error: 1 };
/**
* If the 'debug' config is true, a 'yui:log' event will be
* dispatched, which the Console widget and anything else
* can consume. If the 'useBrowserConsole' config is true, it will
* write to the browser console if available. YUI-specific log
* messages will only be present in the -debug versions of the
* JS files. The build system is supposed to remove log statements
* from the raw and minified versions of the files.
*
* @method log
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.log = function(msg, cat, src, silent) {
var bail, excl, incl, m, f,
Y = INSTANCE,
c = Y.config,
publisher = (Y.fire) ? Y : YUI.Env.globalEvents;
// suppress log message if the config is off or the event stack
// or the event call stack contains a consumer of the yui:log event
if (c.debug) {
// apply source filters
if (src) {
excl = c.logExclude;
incl = c.logInclude;
if (incl && !(src in incl)) {
bail = 1;
} else if (incl && (src in incl)) {
bail = !incl[src];
} else if (excl && (src in excl)) {
bail = excl[src];
}
}
if (!bail) {
if (c.useBrowserConsole) {
m = (src) ? src + ': ' + msg : msg;
if (Y.Lang.isFunction(c.logFn)) {
c.logFn.call(Y, msg, cat, src);
} else if (typeof console != UNDEFINED && console.log) {
f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log';
console[f](m);
} else if (typeof opera != UNDEFINED) {
opera.postError(m);
}
}
if (publisher && !silent) {
if (publisher == Y && (!publisher.getEvent(LOGEVENT))) {
publisher.publish(LOGEVENT, {
broadcast: 2
});
}
publisher.fire(LOGEVENT, {
msg: msg,
cat: cat,
src: src
});
}
}
}
return Y;
};
/**
* Write a system message. This message will be preserved in the
* minified and raw versions of the YUI files, unlike log statements.
* @method message
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.message = function() {
return INSTANCE.log.apply(INSTANCE, arguments);
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('yui-later', function(Y) {
/**
* Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-later
*/
var NO_ARGS = [];
/**
* Executes the supplied function in the context of the supplied
* object 'when' milliseconds later. Executes the function a
* single time unless periodic is set to true.
* @for YUI
* @method later
* @param when {int} the number of milliseconds to wait until the fn
* is executed.
* @param o the context object.
* @param fn {Function|String} the function to execute or the name of
* the method in the 'o' object to execute.
* @param data [Array] data that is provided to the function. This
* accepts either a single item or an array. If an array is provided,
* the function is executed with one parameter for each array item.
* If you need to pass a single array parameter, it needs to be wrapped
* in an array [myarray].
*
* Note: native methods in IE may not have the call and apply methods.
* In this case, it will work, but you are limited to four arguments.
*
* @param periodic {boolean} if true, executes continuously at supplied
* interval until canceled.
* @return {object} a timer object. Call the cancel() method on this
* object to stop the timer.
*/
Y.later = function(when, o, fn, data, periodic) {
when = when || 0;
data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : data;
var cancelled = false,
method = (o && Y.Lang.isString(fn)) ? o[fn] : fn,
wrapper = function() {
// IE 8- may execute a setInterval callback one last time
// after clearInterval was called, so in order to preserve
// the cancel() === no more runny-run, we have to jump through
// an extra hoop.
if (!cancelled) {
if (!method.apply) {
method(data[0], data[1], data[2], data[3]);
} else {
method.apply(o, data || NO_ARGS);
}
}
},
id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when);
return {
id: id,
interval: periodic,
cancel: function() {
cancelled = true;
if (this.interval) {
clearInterval(id);
} else {
clearTimeout(id);
}
}
};
};
Y.Lang.later = Y.later;
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('loader-base', function(Y) {
/**
* The YUI loader core
* @module loader
* @submodule loader-base
*/
if (!YUI.Env[Y.version]) {
(function() {
var VERSION = Y.version,
BUILD = '/build/',
ROOT = VERSION + BUILD,
CDN_BASE = Y.Env.base,
GALLERY_VERSION = 'gallery-2011.08.04-15-16',
TNT = '2in3',
TNT_VERSION = '4',
YUI2_VERSION = '2.9.0',
COMBO_BASE = CDN_BASE + 'combo?',
META = { version: VERSION,
root: ROOT,
base: Y.Env.base,
comboBase: COMBO_BASE,
skin: { defaultSkin: 'sam',
base: 'assets/skins/',
path: 'skin.css',
after: ['cssreset',
'cssfonts',
'cssgrids',
'cssbase',
'cssreset-context',
'cssfonts-context']},
groups: {},
patterns: {} },
groups = META.groups,
yui2Update = function(tnt, yui2) {
var root = TNT + '.' +
(tnt || TNT_VERSION) + '/' +
(yui2 || YUI2_VERSION) + BUILD;
groups.yui2.base = CDN_BASE + root;
groups.yui2.root = root;
},
galleryUpdate = function(tag) {
var root = (tag || GALLERY_VERSION) + BUILD;
groups.gallery.base = CDN_BASE + root;
groups.gallery.root = root;
};
groups[VERSION] = {};
groups.gallery = {
ext: false,
combine: true,
comboBase: COMBO_BASE,
update: galleryUpdate,
patterns: { 'gallery-': { },
'lang/gallery-': {},
'gallerycss-': { type: 'css' } }
};
groups.yui2 = {
combine: true,
ext: false,
comboBase: COMBO_BASE,
update: yui2Update,
patterns: {
'yui2-': {
configFn: function(me) {
if (/-skin|reset|fonts|grids|base/.test(me.name)) {
me.type = 'css';
me.path = me.path.replace(/\.js/, '.css');
// this makes skins in builds earlier than
// 2.6.0 work as long as combine is false
me.path = me.path.replace(/\/yui2-skin/,
'/assets/skins/sam/yui2-skin');
}
}
}
}
};
galleryUpdate();
yui2Update();
YUI.Env[VERSION] = META;
}());
}
/**
* Loader dynamically loads script and css files. It includes the dependency
* info for the version of the library in use, and will automatically pull in
* dependencies for the modules requested. It supports rollup files and will
* automatically use these when appropriate in order to minimize the number of
* http connections required to load all of the dependencies. It can load the
* files from the Yahoo! CDN, and it can utilize the combo service provided on
* this network to reduce the number of http connections required to download
* YUI files.
*
* @module loader
* @submodule loader-base
*/
var NOT_FOUND = {},
NO_REQUIREMENTS = [],
MAX_URL_LENGTH = 2048,
GLOBAL_ENV = YUI.Env,
GLOBAL_LOADED = GLOBAL_ENV._loaded,
CSS = 'css',
JS = 'js',
INTL = 'intl',
VERSION = Y.version,
ROOT_LANG = '',
YObject = Y.Object,
oeach = YObject.each,
YArray = Y.Array,
_queue = GLOBAL_ENV._loaderQueue,
META = GLOBAL_ENV[VERSION],
SKIN_PREFIX = 'skin-',
L = Y.Lang,
ON_PAGE = GLOBAL_ENV.mods,
modulekey,
cache,
_path = function(dir, file, type, nomin) {
var path = dir + '/' + file;
if (!nomin) {
path += '-min';
}
path += '.' + (type || CSS);
return path;
};
/**
* The component metadata is stored in Y.Env.meta.
* Part of the loader module.
* @property Env.meta
* @for YUI
*/
Y.Env.meta = META;
/**
* Loader dynamically loads script and css files. It includes the dependency
* info for the version of the library in use, and will automatically pull in
* dependencies for the modules requested. It supports rollup files and will
* automatically use these when appropriate in order to minimize the number of
* http connections required to load all of the dependencies. It can load the
* files from the Yahoo! CDN, and it can utilize the combo service provided on
* this network to reduce the number of http connections required to download
* YUI files.
*
* While the loader can be instantiated by the end user, it normally is not.
* @see YUI.use for the normal use case. The use function automatically will
* pull in missing dependencies.
*
* @constructor
* @class Loader
* @param {object} o an optional set of configuration options. Valid options:
* <ul>
* <li>base:
* The base dir</li>
* <li>comboBase:
* The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li>
* <li>root:
* The root path to prepend to module names for the combo service.
* Ex: 2.5.2/build/</li>
* <li>filter:.
*
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the Logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).
* </dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
* <pre>
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
* </pre>
*
* </li>
* <li>filters: per-component filter specification. If specified
* for a given component, this overrides the filter config. _Note:_ This does not work on combo urls, use the filter property instead.</li>
* <li>combine:
* Use the YUI combo service to reduce the number of http connections
* required to load your dependencies</li>
* <li>ignore:
* A list of modules that should never be dynamically loaded</li>
* <li>force:
* A list of modules that should always be loaded when required, even if
* already present on the page</li>
* <li>insertBefore:
* Node or id for a node that should be used as the insertion point for
* new nodes</li>
* <li>charset:
* charset for dynamic nodes (deprecated, use jsAttributes or cssAttributes)
* </li>
* <li>jsAttributes: object literal containing attributes to add to script
* nodes</li>
* <li>cssAttributes: object literal containing attributes to add to link
* nodes</li>
* <li>timeout:
* The number of milliseconds before a timeout occurs when dynamically
* loading nodes. If not set, there is no timeout</li>
* <li>context:
* execution context for all callbacks</li>
* <li>onSuccess:
* callback for the 'success' event</li>
* <li>onFailure: callback for the 'failure' event</li>
* <li>onCSS: callback for the 'CSSComplete' event. When loading YUI
* components with CSS the CSS is loaded first, then the script. This
* provides a moment you can tie into to improve
* the presentation of the page while the script is loading.</li>
* <li>onTimeout:
* callback for the 'timeout' event</li>
* <li>onProgress:
* callback executed each time a script or css file is loaded</li>
* <li>modules:
* A list of module definitions. See Loader.addModule for the supported
* module metadata</li>
* <li>groups:
* A list of group definitions. Each group can contain specific definitions
* for base, comboBase, combine, and accepts a list of modules. See above
* for the description of these properties.</li>
* <li>2in3: the version of the YUI 2 in 3 wrapper to use. The intrinsic
* support for YUI 2 modules in YUI 3 relies on versions of the YUI 2
* components inside YUI 3 module wrappers. These wrappers
* change over time to accomodate the issues that arise from running YUI 2
* in a YUI 3 sandbox.</li>
* <li>yui2: when using the 2in3 project, you can select the version of
* YUI 2 to use. Valid values * are 2.2.2, 2.3.1, 2.4.1, 2.5.2, 2.6.0,
* 2.7.0, 2.8.0, and 2.8.1 [default] -- plus all versions of YUI 2
* going forward.</li>
* </ul>
*/
Y.Loader = function(o) {
var defaults = META.modules,
self = this;
modulekey = META.md5;
/**
* Internal callback to handle multiple internal insert() calls
* so that css is inserted prior to js
* @property _internalCallback
* @private
*/
// self._internalCallback = null;
/**
* Callback that will be executed when the loader is finished
* with an insert
* @method onSuccess
* @type function
*/
// self.onSuccess = null;
/**
* Callback that will be executed if there is a failure
* @method onFailure
* @type function
*/
// self.onFailure = null;
/**
* Callback for the 'CSSComplete' event. When loading YUI components
* with CSS the CSS is loaded first, then the script. This provides
* a moment you can tie into to improve the presentation of the page
* while the script is loading.
* @method onCSS
* @type function
*/
// self.onCSS = null;
/**
* Callback executed each time a script or css file is loaded
* @method onProgress
* @type function
*/
// self.onProgress = null;
/**
* Callback that will be executed if a timeout occurs
* @method onTimeout
* @type function
*/
// self.onTimeout = null;
/**
* The execution context for all callbacks
* @property context
* @default {YUI} the YUI instance
*/
self.context = Y;
/**
* Data that is passed to all callbacks
* @property data
*/
// self.data = null;
/**
* Node reference or id where new nodes should be inserted before
* @property insertBefore
* @type string|HTMLElement
*/
// self.insertBefore = null;
/**
* The charset attribute for inserted nodes
* @property charset
* @type string
* @deprecated , use cssAttributes or jsAttributes.
*/
// self.charset = null;
/**
* An object literal containing attributes to add to link nodes
* @property cssAttributes
* @type object
*/
// self.cssAttributes = null;
/**
* An object literal containing attributes to add to script nodes
* @property jsAttributes
* @type object
*/
// self.jsAttributes = null;
/**
* The base directory.
* @property base
* @type string
* @default http://yui.yahooapis.com/[YUI VERSION]/build/
*/
self.base = Y.Env.meta.base + Y.Env.meta.root;
/**
* Base path for the combo service
* @property comboBase
* @type string
* @default http://yui.yahooapis.com/combo?
*/
self.comboBase = Y.Env.meta.comboBase;
/*
* Base path for language packs.
*/
// self.langBase = Y.Env.meta.langBase;
// self.lang = "";
/**
* If configured, the loader will attempt to use the combo
* service for YUI resources and configured external resources.
* @property combine
* @type boolean
* @default true if a base dir isn't in the config
*/
self.combine = o.base &&
(o.base.indexOf(self.comboBase.substr(0, 20)) > -1);
/**
* The default seperator to use between files in a combo URL
* @property comboSep
* @type {String}
* @default Ampersand
*/
self.comboSep = '&';
/**
* Max url length for combo urls. The default is 2048. This is the URL
* limit for the Yahoo! hosted combo servers. If consuming
* a different combo service that has a different URL limit
* it is possible to override this default by supplying
* the maxURLLength config option. The config option will
* only take effect if lower than the default.
*
* @property maxURLLength
* @type int
*/
self.maxURLLength = MAX_URL_LENGTH;
/**
* Ignore modules registered on the YUI global
* @property ignoreRegistered
* @default false
*/
// self.ignoreRegistered = false;
/**
* Root path to prepend to module path for the combo
* service
* @property root
* @type string
* @default [YUI VERSION]/build/
*/
self.root = Y.Env.meta.root;
/**
* Timeout value in milliseconds. If set, self value will be used by
* the get utility. the timeout event will fire if
* a timeout occurs.
* @property timeout
* @type int
*/
self.timeout = 0;
/**
* A list of modules that should not be loaded, even if
* they turn up in the dependency tree
* @property ignore
* @type string[]
*/
// self.ignore = null;
/**
* A list of modules that should always be loaded, even
* if they have already been inserted into the page.
* @property force
* @type string[]
*/
// self.force = null;
self.forceMap = {};
/**
* Should we allow rollups
* @property allowRollup
* @type boolean
* @default false
*/
self.allowRollup = false;
/**
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the Logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).
* </dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
* <pre>
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
* </pre>
* @property filter
* @type string| {searchExp: string, replaceStr: string}
*/
// self.filter = null;
/**
* per-component filter specification. If specified for a given
* component, this overrides the filter config.
* @property filters
* @type object
*/
self.filters = {};
/**
* The list of requested modules
* @property required
* @type {string: boolean}
*/
self.required = {};
/**
* If a module name is predefined when requested, it is checked againsts
* the patterns provided in this property. If there is a match, the
* module is added with the default configuration.
*
* At the moment only supporting module prefixes, but anticipate
* supporting at least regular expressions.
* @property patterns
* @type Object
*/
// self.patterns = Y.merge(Y.Env.meta.patterns);
self.patterns = {};
/**
* The library metadata
* @property moduleInfo
*/
// self.moduleInfo = Y.merge(Y.Env.meta.moduleInfo);
self.moduleInfo = {};
self.groups = Y.merge(Y.Env.meta.groups);
/**
* Provides the information used to skin the skinnable components.
* The following skin definition would result in 'skin1' and 'skin2'
* being loaded for calendar (if calendar was requested), and
* 'sam' for all other skinnable components:
*
* <code>
* skin: {
*
* // The default skin, which is automatically applied if not
* // overriden by a component-specific skin definition.
* // Change this in to apply a different skin globally
* defaultSkin: 'sam',
*
* // This is combined with the loader base property to get
* // the default root directory for a skin. ex:
* // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/
* base: 'assets/skins/',
*
* // Any component-specific overrides can be specified here,
* // making it possible to load different skins for different
* // components. It is possible to load more than one skin
* // for a given component as well.
* overrides: {
* calendar: ['skin1', 'skin2']
* }
* }
* </code>
* @property skin
*/
self.skin = Y.merge(Y.Env.meta.skin);
/*
* Map of conditional modules
* @since 3.2.0
*/
self.conditions = {};
// map of modules with a hash of modules that meet the requirement
// self.provides = {};
self.config = o;
self._internal = true;
cache = GLOBAL_ENV._renderedMods;
if (cache) {
oeach(cache, function modCache(v, k) {
//self.moduleInfo[k] = Y.merge(v);
self.moduleInfo[k] = v;
});
cache = GLOBAL_ENV._conditions;
oeach(cache, function condCache(v, k) {
//self.conditions[k] = Y.merge(v);
self.conditions[k] = v;
});
} else {
oeach(defaults, self.addModule, self);
}
if (!GLOBAL_ENV._renderedMods) {
//GLOBAL_ENV._renderedMods = Y.merge(self.moduleInfo);
//GLOBAL_ENV._conditions = Y.merge(self.conditions);
GLOBAL_ENV._renderedMods = self.moduleInfo;
GLOBAL_ENV._conditions = self.conditions;
}
self._inspectPage();
self._internal = false;
self._config(o);
self.testresults = null;
if (Y.config.tests) {
self.testresults = Y.config.tests;
}
/**
* List of rollup files found in the library metadata
* @property rollups
*/
// self.rollups = null;
/**
* Whether or not to load optional dependencies for
* the requested modules
* @property loadOptional
* @type boolean
* @default false
*/
// self.loadOptional = false;
/**
* All of the derived dependencies in sorted order, which
* will be populated when either calculate() or insert()
* is called
* @property sorted
* @type string[]
*/
self.sorted = [];
/**
* Set when beginning to compute the dependency tree.
* Composed of what YUI reports to be loaded combined
* with what has been loaded by any instance on the page
* with the version number specified in the metadata.
* @property loaded
* @type {string: boolean}
*/
self.loaded = GLOBAL_LOADED[VERSION];
/*
* A list of modules to attach to the YUI instance when complete.
* If not supplied, the sorted list of dependencies are applied.
* @property attaching
*/
// self.attaching = null;
/**
* Flag to indicate the dependency tree needs to be recomputed
* if insert is called again.
* @property dirty
* @type boolean
* @default true
*/
self.dirty = true;
/**
* List of modules inserted by the utility
* @property inserted
* @type {string: boolean}
*/
self.inserted = {};
/**
* List of skipped modules during insert() because the module
* was not defined
* @property skipped
*/
self.skipped = {};
// Y.on('yui:load', self.loadNext, self);
self.tested = {};
/*
* Cached sorted calculate results
* @property results
* @since 3.2.0
*/
//self.results = {};
};
Y.Loader.prototype = {
FILTER_DEFS: {
RAW: {
'searchExp': '-min\\.js',
'replaceStr': '.js'
},
DEBUG: {
'searchExp': '-min\\.js',
'replaceStr': '-debug.js'
}
},
/*
* Check the pages meta-data and cache the result.
* @method _inspectPage
* @private
*/
_inspectPage: function() {
oeach(ON_PAGE, function(v, k) {
if (v.details) {
var m = this.moduleInfo[k],
req = v.details.requires,
mr = m && m.requires;
if (m) {
if (!m._inspected && req && mr.length != req.length) {
// console.log('deleting ' + m.name);
// m.requres = YObject.keys(Y.merge(YArray.hash(req), YArray.hash(mr)));
delete m.expanded;
// delete m.expanded_map;
}
} else {
m = this.addModule(v.details, k);
}
m._inspected = true;
}
}, this);
},
/*
* returns true if b is not loaded, and is required directly or by means of modules it supersedes.
* @private
* @method _requires
* @param {String} mod1 The first module to compare
* @param {String} mod2 The second module to compare
*/
_requires: function(mod1, mod2) {
var i, rm, after_map, s,
info = this.moduleInfo,
m = info[mod1],
other = info[mod2];
if (!m || !other) {
return false;
}
rm = m.expanded_map;
after_map = m.after_map;
// check if this module should be sorted after the other
// do this first to short circut circular deps
if (after_map && (mod2 in after_map)) {
return true;
}
after_map = other.after_map;
// and vis-versa
if (after_map && (mod1 in after_map)) {
return false;
}
// check if this module requires one the other supersedes
s = info[mod2] && info[mod2].supersedes;
if (s) {
for (i = 0; i < s.length; i++) {
if (this._requires(mod1, s[i])) {
return true;
}
}
}
s = info[mod1] && info[mod1].supersedes;
if (s) {
for (i = 0; i < s.length; i++) {
if (this._requires(mod2, s[i])) {
return false;
}
}
}
// check if this module requires the other directly
// if (r && YArray.indexOf(r, mod2) > -1) {
if (rm && (mod2 in rm)) {
return true;
}
// external css files should be sorted below yui css
if (m.ext && m.type == CSS && !other.ext && other.type == CSS) {
return true;
}
return false;
},
/**
* Apply a new config to the Loader instance
* @method _config
* @param {Object} o The new configuration
*/
_config: function(o) {
var i, j, val, f, group, groupName, self = this;
// apply config values
if (o) {
for (i in o) {
if (o.hasOwnProperty(i)) {
val = o[i];
if (i == 'require') {
self.require(val);
} else if (i == 'skin') {
Y.mix(self.skin, o[i], true);
} else if (i == 'groups') {
for (j in val) {
if (val.hasOwnProperty(j)) {
// Y.log('group: ' + j);
groupName = j;
group = val[j];
self.addGroup(group, groupName);
}
}
} else if (i == 'modules') {
// add a hash of module definitions
oeach(val, self.addModule, self);
} else if (i == 'gallery') {
this.groups.gallery.update(val);
} else if (i == 'yui2' || i == '2in3') {
this.groups.yui2.update(o['2in3'], o.yui2);
} else if (i == 'maxURLLength') {
self[i] = Math.min(MAX_URL_LENGTH, val);
} else {
self[i] = val;
}
}
}
}
// fix filter
f = self.filter;
if (L.isString(f)) {
f = f.toUpperCase();
self.filterName = f;
self.filter = self.FILTER_DEFS[f];
if (f == 'DEBUG') {
self.require('yui-log', 'dump');
}
}
if (self.lang) {
self.require('intl-base', 'intl');
}
},
/**
* Returns the skin module name for the specified skin name. If a
* module name is supplied, the returned skin module name is
* specific to the module passed in.
* @method formatSkin
* @param {string} skin the name of the skin.
* @param {string} mod optional: the name of a module to skin.
* @return {string} the full skin module name.
*/
formatSkin: function(skin, mod) {
var s = SKIN_PREFIX + skin;
if (mod) {
s = s + '-' + mod;
}
return s;
},
/**
* Adds the skin def to the module info
* @method _addSkin
* @param {string} skin the name of the skin.
* @param {string} mod the name of the module.
* @param {string} parent parent module if this is a skin of a
* submodule or plugin.
* @return {string} the module name for the skin.
* @private
*/
_addSkin: function(skin, mod, parent) {
var mdef, pkg, name, nmod,
info = this.moduleInfo,
sinf = this.skin,
ext = info[mod] && info[mod].ext;
// Add a module definition for the module-specific skin css
if (mod) {
name = this.formatSkin(skin, mod);
if (!info[name]) {
mdef = info[mod];
pkg = mdef.pkg || mod;
nmod = {
name: name,
group: mdef.group,
type: 'css',
after: sinf.after,
path: (parent || pkg) + '/' + sinf.base + skin +
'/' + mod + '.css',
ext: ext
};
if (mdef.base) {
nmod.base = mdef.base;
}
if (mdef.configFn) {
nmod.configFn = mdef.configFn;
}
this.addModule(nmod, name);
Y.log('adding skin ' + name + ', ' + parent + ', ' + pkg + ', ' + info[name].path);
}
}
return name;
},
/**
* Add a new module group
* <dl>
* <dt>name:</dt> <dd>required, the group name</dd>
* <dt>base:</dt> <dd>The base dir for this module group</dd>
* <dt>root:</dt> <dd>The root path to add to each combo
* resource path</dd>
* <dt>combine:</dt> <dd>combo handle</dd>
* <dt>comboBase:</dt> <dd>combo service base path</dd>
* <dt>modules:</dt> <dd>the group of modules</dd>
* </dl>
* @method addGroup
* @param {object} o An object containing the module data.
* @param {string} name the group name.
*/
addGroup: function(o, name) {
var mods = o.modules,
self = this;
name = name || o.name;
o.name = name;
self.groups[name] = o;
if (o.patterns) {
oeach(o.patterns, function(v, k) {
v.group = name;
self.patterns[k] = v;
});
}
if (mods) {
oeach(mods, function(v, k) {
v.group = name;
self.addModule(v, k);
}, self);
}
},
/**
* Add a new module to the component metadata.
* <dl>
* <dt>name:</dt> <dd>required, the component name</dd>
* <dt>type:</dt> <dd>required, the component type (js or css)
* </dd>
* <dt>path:</dt> <dd>required, the path to the script from
* "base"</dd>
* <dt>requires:</dt> <dd>array of modules required by this
* component</dd>
* <dt>optional:</dt> <dd>array of optional modules for this
* component</dd>
* <dt>supersedes:</dt> <dd>array of the modules this component
* replaces</dd>
* <dt>after:</dt> <dd>array of modules the components which, if
* present, should be sorted above this one</dd>
* <dt>after_map:</dt> <dd>faster alternative to 'after' -- supply
* a hash instead of an array</dd>
* <dt>rollup:</dt> <dd>the number of superseded modules required
* for automatic rollup</dd>
* <dt>fullpath:</dt> <dd>If fullpath is specified, this is used
* instead of the configured base + path</dd>
* <dt>skinnable:</dt> <dd>flag to determine if skin assets should
* automatically be pulled in</dd>
* <dt>submodules:</dt> <dd>a hash of submodules</dd>
* <dt>group:</dt> <dd>The group the module belongs to -- this
* is set automatically when it is added as part of a group
* configuration.</dd>
* <dt>lang:</dt>
* <dd>array of BCP 47 language tags of languages for which this
* module has localized resource bundles,
* e.g., ["en-GB","zh-Hans-CN"]</dd>
* <dt>condition:</dt>
* <dd>Specifies that the module should be loaded automatically if
* a condition is met. This is an object with up to three fields:
* [trigger] - the name of a module that can trigger the auto-load
* [test] - a function that returns true when the module is to be
* loaded.
* [when] - specifies the load order of the conditional module
* with regard to the position of the trigger module.
* This should be one of three values: 'before', 'after', or
* 'instead'. The default is 'after'.
* </dd>
* <dt>testresults:</dt><dd>a hash of test results from Y.Features.all()</dd>
* </dl>
* @method addModule
* @param {object} o An object containing the module data.
* @param {string} name the module name (optional), required if not
* in the module data.
* @return {object} the module definition or null if
* the object passed in did not provide all required attributes.
*/
addModule: function(o, name) {
name = name || o.name;
if (this.moduleInfo[name]) {
//This catches temp modules loaded via a pattern
// The module will be added twice, once from the pattern and
// Once from the actual add call, this ensures that properties
// that were added to the module the first time around (group: gallery)
// are also added the second time around too.
o = Y.merge(this.moduleInfo[name], o);
}
o.name = name;
if (!o || !o.name) {
return null;
}
if (!o.type) {
o.type = JS;
}
if (!o.path && !o.fullpath) {
o.path = _path(name, name, o.type);
}
o.supersedes = o.supersedes || o.use;
o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true;
o.requires = this.filterRequires(o.requires) || [];
// Handle submodule logic
var subs = o.submodules, i, l, t, sup, s, smod, plugins, plug,
j, langs, packName, supName, flatSup, flatLang, lang, ret,
overrides, skinname, when,
conditions = this.conditions, trigger;
// , existing = this.moduleInfo[name], newr;
this.moduleInfo[name] = o;
if (!o.langPack && o.lang) {
langs = YArray(o.lang);
for (j = 0; j < langs.length; j++) {
lang = langs[j];
packName = this.getLangPackName(lang, name);
smod = this.moduleInfo[packName];
if (!smod) {
smod = this._addLangPack(lang, o, packName);
}
}
}
if (subs) {
sup = o.supersedes || [];
l = 0;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
s.path = s.path || _path(name, i, o.type);
s.pkg = name;
s.group = o.group;
if (s.supersedes) {
sup = sup.concat(s.supersedes);
}
smod = this.addModule(s, i);
sup.push(i);
if (smod.skinnable) {
o.skinnable = true;
overrides = this.skin.overrides;
if (overrides && overrides[i]) {
for (j = 0; j < overrides[i].length; j++) {
skinname = this._addSkin(overrides[i][j],
i, name);
sup.push(skinname);
}
}
skinname = this._addSkin(this.skin.defaultSkin,
i, name);
sup.push(skinname);
}
// looks like we are expected to work out the metadata
// for the parent module language packs from what is
// specified in the child modules.
if (s.lang && s.lang.length) {
langs = YArray(s.lang);
for (j = 0; j < langs.length; j++) {
lang = langs[j];
packName = this.getLangPackName(lang, name);
supName = this.getLangPackName(lang, i);
smod = this.moduleInfo[packName];
if (!smod) {
smod = this._addLangPack(lang, o, packName);
}
flatSup = flatSup || YArray.hash(smod.supersedes);
if (!(supName in flatSup)) {
smod.supersedes.push(supName);
}
o.lang = o.lang || [];
flatLang = flatLang || YArray.hash(o.lang);
if (!(lang in flatLang)) {
o.lang.push(lang);
}
// Y.log('pack ' + packName + ' should supersede ' + supName);
// Add rollup file, need to add to supersedes list too
// default packages
packName = this.getLangPackName(ROOT_LANG, name);
supName = this.getLangPackName(ROOT_LANG, i);
smod = this.moduleInfo[packName];
if (!smod) {
smod = this._addLangPack(lang, o, packName);
}
if (!(supName in flatSup)) {
smod.supersedes.push(supName);
}
// Y.log('pack ' + packName + ' should supersede ' + supName);
// Add rollup file, need to add to supersedes list too
}
}
l++;
}
}
//o.supersedes = YObject.keys(YArray.hash(sup));
o.supersedes = YArray.dedupe(sup);
if (this.allowRollup) {
o.rollup = (l < 4) ? l : Math.min(l - 1, 4);
}
}
plugins = o.plugins;
if (plugins) {
for (i in plugins) {
if (plugins.hasOwnProperty(i)) {
plug = plugins[i];
plug.pkg = name;
plug.path = plug.path || _path(name, i, o.type);
plug.requires = plug.requires || [];
plug.group = o.group;
this.addModule(plug, i);
if (o.skinnable) {
this._addSkin(this.skin.defaultSkin, i, name);
}
}
}
}
if (o.condition) {
t = o.condition.trigger;
if (YUI.Env.aliases[t]) {
t = YUI.Env.aliases[t];
}
if (!Y.Lang.isArray(t)) {
t = [t];
}
for (i = 0; i < t.length; i++) {
trigger = t[i];
when = o.condition.when;
conditions[trigger] = conditions[trigger] || {};
conditions[trigger][name] = o.condition;
// the 'when' attribute can be 'before', 'after', or 'instead'
// the default is after.
if (when && when != 'after') {
if (when == 'instead') { // replace the trigger
o.supersedes = o.supersedes || [];
o.supersedes.push(trigger);
} else { // before the trigger
// the trigger requires the conditional mod,
// so it should appear before the conditional
// mod if we do not intersede.
}
} else { // after the trigger
o.after = o.after || [];
o.after.push(trigger);
}
}
}
if (o.after) {
o.after_map = YArray.hash(o.after);
}
// this.dirty = true;
if (o.configFn) {
ret = o.configFn(o);
if (ret === false) {
delete this.moduleInfo[name];
o = null;
}
}
return o;
},
/**
* Add a requirement for one or more module
* @method require
* @param {string[] | string*} what the modules to load.
*/
require: function(what) {
var a = (typeof what === 'string') ? YArray(arguments) : what;
this.dirty = true;
this.required = Y.merge(this.required, YArray.hash(this.filterRequires(a)));
this._explodeRollups();
},
/**
* Grab all the items that were asked for, check to see if the Loader
* meta-data contains a "use" array. If it doesm remove the asked item and replace it with
* the content of the "use".
* This will make asking for: "dd"
* Actually ask for: "dd-ddm-base,dd-ddm,dd-ddm-drop,dd-drag,dd-proxy,dd-constrain,dd-drop,dd-scroll,dd-drop-plugin"
* @private
* @method _explodeRollups
*/
_explodeRollups: function() {
var self = this, m,
r = self.required;
if (!self.allowRollup) {
oeach(r, function(v, name) {
m = self.getModule(name);
if (m && m.use) {
//delete r[name];
YArray.each(m.use, function(v) {
m = self.getModule(v);
if (m && m.use) {
//delete r[v];
YArray.each(m.use, function(v) {
r[v] = true;
});
} else {
r[v] = true;
}
});
}
});
self.required = r;
}
},
/**
* Explodes the required array to remove aliases and replace them with real modules
* @method filterRequires
* @param {Array} r The original requires array
* @return {Array} The new array of exploded requirements
*/
filterRequires: function(r) {
if (r) {
if (!Y.Lang.isArray(r)) {
r = [r];
}
r = Y.Array(r);
var c = [], i, mod, o, m;
for (i = 0; i < r.length; i++) {
mod = this.getModule(r[i]);
if (mod && mod.use) {
for (o = 0; o < mod.use.length; o++) {
//Must walk the other modules in case a module is a rollup of rollups (datatype)
m = this.getModule(mod.use[o]);
if (m && m.use) {
c = Y.Array.dedupe([].concat(c, this.filterRequires(m.use)));
} else {
c.push(mod.use[o]);
}
}
} else {
c.push(r[i]);
}
}
r = c;
}
return r;
},
/**
* Returns an object containing properties for all modules required
* in order to load the requested module
* @method getRequires
* @param {object} mod The module definition from moduleInfo.
* @return {array} the expanded requirement list.
*/
getRequires: function(mod) {
if (!mod || mod._parsed) {
// Y.log('returning no reqs for ' + mod.name);
return NO_REQUIREMENTS;
}
var i, m, j, add, packName, lang, testresults = this.testresults,
name = mod.name, cond, go,
adddef = ON_PAGE[name] && ON_PAGE[name].details,
d, k, m1,
r, old_mod,
o, skinmod, skindef, skinpar, skinname,
intl = mod.lang || mod.intl,
info = this.moduleInfo,
ftests = Y.Features && Y.Features.tests.load,
hash;
// console.log(name);
// pattern match leaves module stub that needs to be filled out
if (mod.temp && adddef) {
old_mod = mod;
mod = this.addModule(adddef, name);
mod.group = old_mod.group;
mod.pkg = old_mod.pkg;
delete mod.expanded;
}
// console.log('cache: ' + mod.langCache + ' == ' + this.lang);
// if (mod.expanded && (!mod.langCache || mod.langCache == this.lang)) {
if (mod.expanded && (!this.lang || mod.langCache === this.lang)) {
//Y.log('Already expanded ' + name + ', ' + mod.expanded);
return mod.expanded;
}
d = [];
hash = {};
r = this.filterRequires(mod.requires);
if (mod.lang) {
//If a module has a lang attribute, auto add the intl requirement.
d.unshift('intl');
r.unshift('intl');
intl = true;
}
o = mod.optional;
// Y.log("getRequires: " + name + " (dirty:" + this.dirty +
// ", expanded:" + mod.expanded + ")");
mod._parsed = true;
mod.langCache = this.lang;
for (i = 0; i < r.length; i++) {
//Y.log(name + ' requiring ' + r[i], 'info', 'loader');
if (!hash[r[i]]) {
d.push(r[i]);
hash[r[i]] = true;
m = this.getModule(r[i]);
if (m) {
add = this.getRequires(m);
intl = intl || (m.expanded_map &&
(INTL in m.expanded_map));
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
// get the requirements from superseded modules, if any
r = mod.supersedes;
if (r) {
for (i = 0; i < r.length; i++) {
if (!hash[r[i]]) {
// if this module has submodules, the requirements list is
// expanded to include the submodules. This is so we can
// prevent dups when a submodule is already loaded and the
// parent is requested.
if (mod.submodules) {
d.push(r[i]);
}
hash[r[i]] = true;
m = this.getModule(r[i]);
if (m) {
add = this.getRequires(m);
intl = intl || (m.expanded_map &&
(INTL in m.expanded_map));
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
}
if (o && this.loadOptional) {
for (i = 0; i < o.length; i++) {
if (!hash[o[i]]) {
d.push(o[i]);
hash[o[i]] = true;
m = info[o[i]];
if (m) {
add = this.getRequires(m);
intl = intl || (m.expanded_map &&
(INTL in m.expanded_map));
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
}
cond = this.conditions[name];
if (cond) {
if (testresults && ftests) {
oeach(testresults, function(result, id) {
var condmod = ftests[id].name;
if (!hash[condmod] && ftests[id].trigger == name) {
if (result && ftests[id]) {
hash[condmod] = true;
d.push(condmod);
}
}
});
} else {
oeach(cond, function(def, condmod) {
if (!hash[condmod]) {
go = def && ((def.ua && Y.UA[def.ua]) ||
(def.test && def.test(Y, r)));
if (go) {
hash[condmod] = true;
d.push(condmod);
m = this.getModule(condmod);
// Y.log('conditional', m);
if (m) {
add = this.getRequires(m);
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
}, this);
}
}
// Create skin modules
if (mod.skinnable) {
skindef = this.skin.overrides;
oeach(YUI.Env.aliases, function(o, n) {
if (Y.Array.indexOf(o, name) > -1) {
skinpar = n;
}
});
if (skindef && (skindef[name] || (skinpar && skindef[skinpar]))) {
skinname = name;
if (skindef[skinpar]) {
skinname = skinpar;
}
for (i = 0; i < skindef[skinname].length; i++) {
skinmod = this._addSkin(skindef[skinname][i], name);
d.push(skinmod);
}
} else {
skinmod = this._addSkin(this.skin.defaultSkin, name);
d.push(skinmod);
}
}
mod._parsed = false;
if (intl) {
if (mod.lang && !mod.langPack && Y.Intl) {
lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang);
//Y.log('Best lang: ' + lang + ', this.lang: ' + this.lang + ', mod.lang: ' + mod.lang);
packName = this.getLangPackName(lang, name);
if (packName) {
d.unshift(packName);
}
}
d.unshift(INTL);
}
mod.expanded_map = YArray.hash(d);
mod.expanded = YObject.keys(mod.expanded_map);
return mod.expanded;
},
/**
* Returns a hash of module names the supplied module satisfies.
* @method getProvides
* @param {string} name The name of the module.
* @return {object} what this module provides.
*/
getProvides: function(name) {
var m = this.getModule(name), o, s;
// supmap = this.provides;
if (!m) {
return NOT_FOUND;
}
if (m && !m.provides) {
o = {};
s = m.supersedes;
if (s) {
YArray.each(s, function(v) {
Y.mix(o, this.getProvides(v));
}, this);
}
o[name] = true;
m.provides = o;
}
return m.provides;
},
/**
* Calculates the dependency tree, the result is stored in the sorted
* property.
* @method calculate
* @param {object} o optional options object.
* @param {string} type optional argument to prune modules.
*/
calculate: function(o, type) {
if (o || type || this.dirty) {
if (o) {
this._config(o);
}
if (!this._init) {
this._setup();
}
this._explode();
if (this.allowRollup) {
this._rollup();
} else {
this._explodeRollups();
}
this._reduce();
this._sort();
}
},
/**
* Creates a "psuedo" package for languages provided in the lang array
* @method _addLangPack
* @param {String} lang The language to create
* @param {Object} m The module definition to create the language pack around
* @param {String} packName The name of the package (e.g: lang/datatype-date-en-US)
* @return {Object} The module definition
*/
_addLangPack: function(lang, m, packName) {
var name = m.name,
packPath,
existing = this.moduleInfo[packName];
if (!existing) {
packPath = _path((m.pkg || name), packName, JS, true);
this.addModule({ path: packPath,
intl: true,
langPack: true,
ext: m.ext,
group: m.group,
supersedes: [] }, packName);
if (lang) {
Y.Env.lang = Y.Env.lang || {};
Y.Env.lang[lang] = Y.Env.lang[lang] || {};
Y.Env.lang[lang][name] = true;
}
}
return this.moduleInfo[packName];
},
/**
* Investigates the current YUI configuration on the page. By default,
* modules already detected will not be loaded again unless a force
* option is encountered. Called by calculate()
* @method _setup
* @private
*/
_setup: function() {
var info = this.moduleInfo, name, i, j, m, l,
packName;
for (name in info) {
if (info.hasOwnProperty(name)) {
m = info[name];
if (m) {
// remove dups
//m.requires = YObject.keys(YArray.hash(m.requires));
m.requires = YArray.dedupe(m.requires);
// Create lang pack modules
if (m.lang && m.lang.length) {
// Setup root package if the module has lang defined,
// it needs to provide a root language pack
packName = this.getLangPackName(ROOT_LANG, name);
this._addLangPack(null, m, packName);
}
}
}
}
//l = Y.merge(this.inserted);
l = {};
// available modules
if (!this.ignoreRegistered) {
Y.mix(l, GLOBAL_ENV.mods);
}
// add the ignore list to the list of loaded packages
if (this.ignore) {
Y.mix(l, YArray.hash(this.ignore));
}
// expand the list to include superseded modules
for (j in l) {
if (l.hasOwnProperty(j)) {
Y.mix(l, this.getProvides(j));
}
}
// remove modules on the force list from the loaded list
if (this.force) {
for (i = 0; i < this.force.length; i++) {
if (this.force[i] in l) {
delete l[this.force[i]];
}
}
}
Y.mix(this.loaded, l);
this._init = true;
},
/**
* Builds a module name for a language pack
* @method getLangPackName
* @param {string} lang the language code.
* @param {string} mname the module to build it for.
* @return {string} the language pack module name.
*/
getLangPackName: function(lang, mname) {
return ('lang/' + mname + ((lang) ? '_' + lang : ''));
},
/**
* Inspects the required modules list looking for additional
* dependencies. Expands the required list to include all
* required modules. Called by calculate()
* @method _explode
* @private
*/
_explode: function() {
var r = this.required, m, reqs, done = {},
self = this;
// the setup phase is over, all modules have been created
self.dirty = false;
self._explodeRollups();
r = self.required;
oeach(r, function(v, name) {
if (!done[name]) {
done[name] = true;
m = self.getModule(name);
if (m) {
var expound = m.expound;
if (expound) {
r[expound] = self.getModule(expound);
reqs = self.getRequires(r[expound]);
Y.mix(r, YArray.hash(reqs));
}
reqs = self.getRequires(m);
Y.mix(r, YArray.hash(reqs));
}
}
});
// Y.log('After explode: ' + YObject.keys(r));
},
/**
* Get's the loader meta data for the requested module
* @method getModule
* @param {String} mname The module name to get
* @return {Object} The module metadata
*/
getModule: function(mname) {
//TODO: Remove name check - it's a quick hack to fix pattern WIP
if (!mname) {
return null;
}
var p, found, pname,
m = this.moduleInfo[mname],
patterns = this.patterns;
// check the patterns library to see if we should automatically add
// the module with defaults
if (!m) {
// Y.log('testing patterns ' + YObject.keys(patterns));
for (pname in patterns) {
if (patterns.hasOwnProperty(pname)) {
// Y.log('testing pattern ' + i);
p = patterns[pname];
// use the metadata supplied for the pattern
// as the module definition.
if (mname.indexOf(pname) > -1) {
found = p;
break;
}
}
}
if (found) {
if (p.action) {
// Y.log('executing pattern action: ' + pname);
p.action.call(this, mname, pname);
} else {
Y.log('Undefined module: ' + mname + ', matched a pattern: ' +
pname, 'info', 'loader');
// ext true or false?
m = this.addModule(Y.merge(found), mname);
m.temp = true;
}
}
}
return m;
},
// impl in rollup submodule
_rollup: function() { },
/**
* Remove superceded modules and loaded modules. Called by
* calculate() after we have the mega list of all dependencies
* @method _reduce
* @return {object} the reduced dependency hash.
* @private
*/
_reduce: function(r) {
r = r || this.required;
var i, j, s, m, type = this.loadType,
ignore = this.ignore ? YArray.hash(this.ignore) : false;
for (i in r) {
if (r.hasOwnProperty(i)) {
m = this.getModule(i);
// remove if already loaded
if (((this.loaded[i] || ON_PAGE[i]) &&
!this.forceMap[i] && !this.ignoreRegistered) ||
(type && m && m.type != type)) {
delete r[i];
}
if (ignore && ignore[i]) {
delete r[i];
}
// remove anything this module supersedes
s = m && m.supersedes;
if (s) {
for (j = 0; j < s.length; j++) {
if (s[j] in r) {
delete r[s[j]];
}
}
}
}
}
return r;
},
/**
* Handles the queue when a module has been loaded for all cases
* @method _finish
* @private
* @param {String} msg The message from Loader
* @param {Boolean} success A boolean denoting success or failure
*/
_finish: function(msg, success) {
Y.log('loader finishing: ' + msg + ', ' + Y.id + ', ' +
this.data, 'info', 'loader');
_queue.running = false;
var onEnd = this.onEnd;
if (onEnd) {
onEnd.call(this.context, {
msg: msg,
data: this.data,
success: success
});
}
this._continue();
},
/**
* The default Loader onSuccess handler, calls this.onSuccess with a payload
* @method _onSuccess
* @private
*/
_onSuccess: function() {
var self = this, skipped = Y.merge(self.skipped), fn,
failed = [], rreg = self.requireRegistration,
success, msg;
oeach(skipped, function(k) {
delete self.inserted[k];
});
self.skipped = {};
oeach(self.inserted, function(v, k) {
var mod = self.getModule(k);
if (mod && rreg && mod.type == JS && !(k in YUI.Env.mods)) {
failed.push(k);
} else {
Y.mix(self.loaded, self.getProvides(k));
}
});
fn = self.onSuccess;
msg = (failed.length) ? 'notregistered' : 'success';
success = !(failed.length);
if (fn) {
fn.call(self.context, {
msg: msg,
data: self.data,
success: success,
failed: failed,
skipped: skipped
});
}
self._finish(msg, success);
},
/**
* The default Loader onFailure handler, calls this.onFailure with a payload
* @method _onFailure
* @private
*/
_onFailure: function(o) {
Y.log('load error: ' + o.msg + ', ' + Y.id, 'error', 'loader');
var f = this.onFailure, msg = 'failure: ' + o.msg;
if (f) {
f.call(this.context, {
msg: msg,
data: this.data,
success: false
});
}
this._finish(msg, false);
},
/**
* The default Loader onTimeout handler, calls this.onTimeout with a payload
* @method _onTimeout
* @private
*/
_onTimeout: function() {
Y.log('loader timeout: ' + Y.id, 'error', 'loader');
var f = this.onTimeout;
if (f) {
f.call(this.context, {
msg: 'timeout',
data: this.data,
success: false
});
}
this._finish('timeout', false);
},
/**
* Sorts the dependency tree. The last step of calculate()
* @method _sort
* @private
*/
_sort: function() {
// create an indexed list
var s = YObject.keys(this.required),
// loaded = this.loaded,
done = {},
p = 0, l, a, b, j, k, moved, doneKey;
// keep going until we make a pass without moving anything
for (;;) {
l = s.length;
moved = false;
// start the loop after items that are already sorted
for (j = p; j < l; j++) {
// check the next module on the list to see if its
// dependencies have been met
a = s[j];
// check everything below current item and move if we
// find a requirement for the current item
for (k = j + 1; k < l; k++) {
doneKey = a + s[k];
if (!done[doneKey] && this._requires(a, s[k])) {
// extract the dependency so we can move it up
b = s.splice(k, 1);
// insert the dependency above the item that
// requires it
s.splice(j, 0, b[0]);
// only swap two dependencies once to short circut
// circular dependencies
done[doneKey] = true;
// keep working
moved = true;
break;
}
}
// jump out of loop if we moved something
if (moved) {
break;
// this item is sorted, move our pointer and keep going
} else {
p++;
}
}
// when we make it here and moved is false, we are
// finished sorting
if (!moved) {
break;
}
}
this.sorted = s;
},
/**
* (Unimplemented)
* @method partial
* @unimplemented
*/
partial: function(partial, o, type) {
this.sorted = partial;
this.insert(o, type, true);
},
/**
* Handles the actual insertion of script/link tags
* @method _insert
* @param {Object} source The YUI instance the request came from
* @param {Object} o The metadata to include
* @param {String} type JS or CSS
* @param {Boolean} [skipcalc=false] Do a Loader.calculate on the meta
*/
_insert: function(source, o, type, skipcalc) {
// Y.log('private _insert() ' + (type || '') + ', ' + Y.id, "info", "loader");
// restore the state at the time of the request
if (source) {
this._config(source);
}
// build the dependency list
// don't include type so we can process CSS and script in
// one pass when the type is not specified.
if (!skipcalc) {
this.calculate(o);
}
this.loadType = type;
if (!type) {
var self = this;
// Y.log("trying to load css first");
this._internalCallback = function() {
var f = self.onCSS, n, p, sib;
// IE hack for style overrides that are not being applied
if (this.insertBefore && Y.UA.ie) {
n = Y.config.doc.getElementById(this.insertBefore);
p = n.parentNode;
sib = n.nextSibling;
p.removeChild(n);
if (sib) {
p.insertBefore(n, sib);
} else {
p.appendChild(n);
}
}
if (f) {
f.call(self.context, Y);
}
self._internalCallback = null;
self._insert(null, null, JS);
};
this._insert(null, null, CSS);
return;
}
// set a flag to indicate the load has started
this._loading = true;
// flag to indicate we are done with the combo service
// and any additional files will need to be loaded
// individually
this._combineComplete = {};
// start the load
this.loadNext();
},
/**
* Once a loader operation is completely finished, process any additional queued items.
* @method _continue
* @private
*/
_continue: function() {
if (!(_queue.running) && _queue.size() > 0) {
_queue.running = true;
_queue.next()();
}
},
/**
* inserts the requested modules and their dependencies.
* <code>type</code> can be "js" or "css". Both script and
* css are inserted if type is not provided.
* @method insert
* @param {object} o optional options object.
* @param {string} type the type of dependency to insert.
*/
insert: function(o, type, skipsort) {
// Y.log('public insert() ' + (type || '') + ', ' +
// Y.Object.keys(this.required), "info", "loader");
var self = this, copy = Y.merge(this);
delete copy.require;
delete copy.dirty;
_queue.add(function() {
self._insert(copy, o, type, skipsort);
});
this._continue();
},
/**
* Executed every time a module is loaded, and if we are in a load
* cycle, we attempt to load the next script. Public so that it
* is possible to call this if using a method other than
* Y.register to determine when scripts are fully loaded
* @method loadNext
* @param {string} mname optional the name of the module that has
* been loaded (which is usually why it is time to load the next
* one).
*/
loadNext: function(mname) {
// It is possible that this function is executed due to something
// else on the page loading a YUI module. Only react when we
// are actively loading something
if (!this._loading) {
return;
}
var s, len, i, m, url, fn, msg, attr, group, groupName, j, frag,
comboSource, comboSources, mods, combining, urls, comboBase,
self = this,
type = self.loadType,
handleSuccess = function(o) {
self.loadNext(o.data);
},
handleCombo = function(o) {
self._combineComplete[type] = true;
var i, len = combining.length;
for (i = 0; i < len; i++) {
self.inserted[combining[i]] = true;
}
handleSuccess(o);
};
if (self.combine && (!self._combineComplete[type])) {
combining = [];
self._combining = combining;
s = self.sorted;
len = s.length;
// the default combo base
comboBase = self.comboBase;
url = comboBase;
urls = [];
comboSources = {};
for (i = 0; i < len; i++) {
comboSource = comboBase;
m = self.getModule(s[i]);
groupName = m && m.group;
if (groupName) {
group = self.groups[groupName];
if (!group.combine) {
m.combine = false;
continue;
}
m.combine = true;
if (group.comboBase) {
comboSource = group.comboBase;
}
if ("root" in group && L.isValue(group.root)) {
m.root = group.root;
}
}
comboSources[comboSource] = comboSources[comboSource] || [];
comboSources[comboSource].push(m);
}
for (j in comboSources) {
if (comboSources.hasOwnProperty(j)) {
url = j;
mods = comboSources[j];
len = mods.length;
for (i = 0; i < len; i++) {
// m = self.getModule(s[i]);
m = mods[i];
// Do not try to combine non-yui JS unless combo def
// is found
if (m && (m.type === type) && (m.combine || !m.ext)) {
frag = ((L.isValue(m.root)) ? m.root : self.root) + m.path;
if ((url !== j) && (i <= (len - 1)) &&
((frag.length + url.length) > self.maxURLLength)) {
//Hack until this is rewritten to use an array and not string concat:
if (url.substr(url.length - 1, 1) === self.comboSep) {
url = url.substr(0, (url.length - 1));
}
urls.push(self._filter(url));
url = j;
}
url += frag;
if (i < (len - 1)) {
url += self.comboSep;
}
combining.push(m.name);
}
}
if (combining.length && (url != j)) {
//Hack until this is rewritten to use an array and not string concat:
if (url.substr(url.length - 1, 1) === self.comboSep) {
url = url.substr(0, (url.length - 1));
}
urls.push(self._filter(url));
}
}
}
if (combining.length) {
Y.log('Attempting to use combo: ' + combining, 'info', 'loader');
// if (m.type === CSS) {
if (type === CSS) {
fn = Y.Get.css;
attr = self.cssAttributes;
} else {
fn = Y.Get.script;
attr = self.jsAttributes;
}
fn(urls, {
data: self._loading,
onSuccess: handleCombo,
onFailure: self._onFailure,
onTimeout: self._onTimeout,
insertBefore: self.insertBefore,
charset: self.charset,
attributes: attr,
timeout: self.timeout,
autopurge: false,
context: self
});
return;
} else {
self._combineComplete[type] = true;
}
}
if (mname) {
// if the module that was just loaded isn't what we were expecting,
// continue to wait
if (mname !== self._loading) {
return;
}
// Y.log("loadNext executing, just loaded " + mname + ", " +
// Y.id, "info", "loader");
// The global handler that is called when each module is loaded
// will pass that module name to this function. Storing this
// data to avoid loading the same module multiple times
// centralize this in the callback
self.inserted[mname] = true;
// self.loaded[mname] = true;
// provided = self.getProvides(mname);
// Y.mix(self.loaded, provided);
// Y.mix(self.inserted, provided);
if (self.onProgress) {
self.onProgress.call(self.context, {
name: mname,
data: self.data
});
}
}
s = self.sorted;
len = s.length;
for (i = 0; i < len; i = i + 1) {
// this.inserted keeps track of what the loader has loaded.
// move on if this item is done.
if (s[i] in self.inserted) {
continue;
}
// Because rollups will cause multiple load notifications
// from Y, loadNext may be called multiple times for
// the same module when loading a rollup. We can safely
// skip the subsequent requests
if (s[i] === self._loading) {
Y.log('still loading ' + s[i] + ', waiting', 'info', 'loader');
return;
}
// log("inserting " + s[i]);
m = self.getModule(s[i]);
if (!m) {
if (!self.skipped[s[i]]) {
msg = 'Undefined module ' + s[i] + ' skipped';
Y.log(msg, 'warn', 'loader');
// self.inserted[s[i]] = true;
self.skipped[s[i]] = true;
}
continue;
}
group = (m.group && self.groups[m.group]) || NOT_FOUND;
// The load type is stored to offer the possibility to load
// the css separately from the script.
if (!type || type === m.type) {
self._loading = s[i];
Y.log('attempting to load ' + s[i] + ', ' + self.base, 'info', 'loader');
if (m.type === CSS) {
fn = Y.Get.css;
attr = self.cssAttributes;
} else {
fn = Y.Get.script;
attr = self.jsAttributes;
}
url = (m.fullpath) ? self._filter(m.fullpath, s[i]) :
self._url(m.path, s[i], group.base || m.base);
fn(url, {
data: s[i],
onSuccess: handleSuccess,
insertBefore: self.insertBefore,
charset: self.charset,
attributes: attr,
onFailure: self._onFailure,
onTimeout: self._onTimeout,
timeout: self.timeout,
autopurge: false,
context: self
});
return;
}
}
// we are finished
self._loading = null;
fn = self._internalCallback;
// internal callback for loading css first
if (fn) {
// Y.log('loader internal');
self._internalCallback = null;
fn.call(self);
} else {
// Y.log('loader complete');
self._onSuccess();
}
},
/**
* Apply filter defined for this instance to a url/path
* @method _filter
* @param {string} u the string to filter.
* @param {string} name the name of the module, if we are processing
* a single module as opposed to a combined url.
* @return {string} the filtered string.
* @private
*/
_filter: function(u, name) {
var f = this.filter,
hasFilter = name && (name in this.filters),
modFilter = hasFilter && this.filters[name];
if (u) {
if (hasFilter) {
f = (L.isString(modFilter)) ?
this.FILTER_DEFS[modFilter.toUpperCase()] || null :
modFilter;
}
if (f) {
u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr);
}
}
return u;
},
/**
* Generates the full url for a module
* @method _url
* @param {string} path the path fragment.
* @param {String} name The name of the module
* @pamra {String} [base=self.base] The base url to use
* @return {string} the full url.
* @private
*/
_url: function(path, name, base) {
return this._filter((base || this.base || '') + path, name);
},
/**
* Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules.
* @method resolve
* @param {Boolean} [calc=false] Perform a loader.calculate() before anything else
* @param {Array} [s=loader.sorted] An override for the loader.sorted array
* @return {Object} Object hash (js and css) of two arrays of file lists
* @example This method can be used as an off-line dep calculator
*
* var Y = YUI();
* var loader = new Y.Loader({
* filter: 'debug',
* base: '../../',
* root: 'build/',
* combine: true,
* require: ['node', 'dd', 'console']
* });
* var out = loader.resolve(true);
*
*/
resolve: function(calc, s) {
var self = this, i, m, url, out = { js: [], css: [] };
if (calc) {
self.calculate();
}
s = s || self.sorted;
for (i = 0; i < s.length; i++) {
m = self.getModule(s[i]);
if (m) {
if (self.combine) {
url = self._filter((self.root + m.path), m.name, self.root);
} else {
url = self._filter(m.fullpath, m.name, '') || self._url(m.path, m.name);
}
out[m.type].push(url);
}
}
if (self.combine) {
out.js = [self.comboBase + out.js.join(self.comboSep)];
out.css = [self.comboBase + out.css.join(self.comboSep)];
}
return out;
},
/**
* Returns an Object hash of hashes built from `loader.sorted` or from an arbitrary list of sorted modules.
* @method hash
* @private
* @param {Boolean} [calc=false] Perform a loader.calculate() before anything else
* @param {Array} [s=loader.sorted] An override for the loader.sorted array
* @return {Object} Object hash (js and css) of two object hashes of file lists, with the module name as the key
* @example This method can be used as an off-line dep calculator
*
* var Y = YUI();
* var loader = new Y.Loader({
* filter: 'debug',
* base: '../../',
* root: 'build/',
* combine: true,
* require: ['node', 'dd', 'console']
* });
* var out = loader.hash(true);
*
*/
hash: function(calc, s) {
var self = this, i, m, url, out = { js: {}, css: {} };
if (calc) {
self.calculate();
}
s = s || self.sorted;
for (i = 0; i < s.length; i++) {
m = self.getModule(s[i]);
if (m) {
url = self._filter(m.fullpath, m.name, '') || self._url(m.path, m.name);
out[m.type][m.name] = url;
}
}
return out;
}
};
}, '@VERSION@' ,{requires:['get']});
YUI.add('loader-rollup', function(Y) {
/**
* Optional automatic rollup logic for reducing http connections
* when not using a combo service.
* @module loader
* @submodule rollup
*/
/**
* Look for rollup packages to determine if all of the modules a
* rollup supersedes are required. If so, include the rollup to
* help reduce the total number of connections required. Called
* by calculate(). This is an optional feature, and requires the
* appropriate submodule to function.
* @method _rollup
* @for Loader
* @private
*/
Y.Loader.prototype._rollup = function() {
var i, j, m, s, r = this.required, roll,
info = this.moduleInfo, rolled, c, smod;
// find and cache rollup modules
if (this.dirty || !this.rollups) {
this.rollups = {};
for (i in info) {
if (info.hasOwnProperty(i)) {
m = this.getModule(i);
// if (m && m.rollup && m.supersedes) {
if (m && m.rollup) {
this.rollups[i] = m;
}
}
}
this.forceMap = (this.force) ? Y.Array.hash(this.force) : {};
}
// make as many passes as needed to pick up rollup rollups
for (;;) {
rolled = false;
// go through the rollup candidates
for (i in this.rollups) {
if (this.rollups.hasOwnProperty(i)) {
// there can be only one, unless forced
if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) {
m = this.getModule(i);
s = m.supersedes || [];
roll = false;
// @TODO remove continue
if (!m.rollup) {
continue;
}
c = 0;
// check the threshold
for (j = 0; j < s.length; j++) {
smod = info[s[j]];
// if the superseded module is loaded, we can't
// load the rollup unless it has been forced.
if (this.loaded[s[j]] && !this.forceMap[s[j]]) {
roll = false;
break;
// increment the counter if this module is required.
// if we are beyond the rollup threshold, we will
// use the rollup module
} else if (r[s[j]] && m.type == smod.type) {
c++;
// Y.log("adding to thresh: " + c + ", " + s[j]);
roll = (c >= m.rollup);
if (roll) {
// Y.log("over thresh " + c + ", " + s[j]);
break;
}
}
}
if (roll) {
// Y.log("adding rollup: " + i);
// add the rollup
r[i] = true;
rolled = true;
// expand the rollup's dependencies
this.getRequires(m);
}
}
}
}
// if we made it here w/o rolling up something, we are done
if (!rolled) {
break;
}
}
};
}, '@VERSION@' ,{requires:['loader-base']});
YUI.add('loader-yui3', function(Y) {
/* This file is auto-generated by src/loader/scripts/meta_join.py */
/**
* YUI 3 module metadata
* @module loader
* @submodule yui3
*/
YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || {
"align-plugin": {
"requires": [
"node-screen",
"node-pluginhost"
]
},
"anim": {
"use": [
"anim-base",
"anim-color",
"anim-curve",
"anim-easing",
"anim-node-plugin",
"anim-scroll",
"anim-xy"
]
},
"anim-base": {
"requires": [
"base-base",
"node-style"
]
},
"anim-color": {
"requires": [
"anim-base"
]
},
"anim-curve": {
"requires": [
"anim-xy"
]
},
"anim-easing": {
"requires": [
"anim-base"
]
},
"anim-node-plugin": {
"requires": [
"node-pluginhost",
"anim-base"
]
},
"anim-scroll": {
"requires": [
"anim-base"
]
},
"anim-xy": {
"requires": [
"anim-base",
"node-screen"
]
},
"app": {
"use": [
"controller",
"model",
"model-list",
"view"
]
},
"array-extras": {},
"array-invoke": {},
"arraylist": {},
"arraylist-add": {
"requires": [
"arraylist"
]
},
"arraylist-filter": {
"requires": [
"arraylist"
]
},
"arraysort": {
"requires": [
"yui-base"
]
},
"async-queue": {
"requires": [
"event-custom"
]
},
"attribute": {
"use": [
"attribute-base",
"attribute-complex"
]
},
"attribute-base": {
"requires": [
"event-custom"
]
},
"attribute-complex": {
"requires": [
"attribute-base"
]
},
"autocomplete": {
"use": [
"autocomplete-base",
"autocomplete-sources",
"autocomplete-list",
"autocomplete-plugin"
]
},
"autocomplete-base": {
"optional": [
"autocomplete-sources"
],
"requires": [
"array-extras",
"base-build",
"escape",
"event-valuechange",
"node-base"
]
},
"autocomplete-filters": {
"requires": [
"array-extras",
"text-wordbreak"
]
},
"autocomplete-filters-accentfold": {
"requires": [
"array-extras",
"text-accentfold",
"text-wordbreak"
]
},
"autocomplete-highlighters": {
"requires": [
"array-extras",
"highlight-base"
]
},
"autocomplete-highlighters-accentfold": {
"requires": [
"array-extras",
"highlight-accentfold"
]
},
"autocomplete-list": {
"after": [
"autocomplete-sources"
],
"lang": [
"en"
],
"requires": [
"autocomplete-base",
"event-resize",
"node-screen",
"selector-css3",
"shim-plugin",
"widget",
"widget-position",
"widget-position-align"
],
"skinnable": true
},
"autocomplete-list-keys": {
"condition": {
"name": "autocomplete-list-keys",
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
},
"requires": [
"autocomplete-list",
"base-build"
]
},
"autocomplete-plugin": {
"requires": [
"autocomplete-list",
"node-pluginhost"
]
},
"autocomplete-sources": {
"optional": [
"io-base",
"json-parse",
"jsonp",
"yql"
],
"requires": [
"autocomplete-base"
]
},
"base": {
"use": [
"base-base",
"base-pluginhost",
"base-build"
]
},
"base-base": {
"after": [
"attribute-complex"
],
"requires": [
"attribute-base"
]
},
"base-build": {
"requires": [
"base-base"
]
},
"base-pluginhost": {
"requires": [
"base-base",
"pluginhost"
]
},
"cache": {
"use": [
"cache-base",
"cache-offline",
"cache-plugin"
]
},
"cache-base": {
"requires": [
"base"
]
},
"cache-offline": {
"requires": [
"cache-base",
"json"
]
},
"cache-plugin": {
"requires": [
"plugin",
"cache-base"
]
},
"calendar": {
"lang": [
"en",
"ru"
],
"requires": [
"calendar-base",
"calendarnavigator"
],
"skinnable": true
},
"calendar-base": {
"lang": [
"en",
"ru"
],
"requires": [
"widget",
"substitute",
"datatype-date",
"datatype-date-math",
"cssgrids"
],
"skinnable": true
},
"calendarnavigator": {
"requires": [
"plugin",
"classnamemanager"
],
"skinnable": true
},
"charts": {
"requires": [
"dom",
"datatype-number",
"datatype-date",
"event-custom",
"event-mouseenter",
"widget",
"widget-position",
"widget-stack",
"graphics"
]
},
"classnamemanager": {
"requires": [
"yui-base"
]
},
"clickable-rail": {
"requires": [
"slider-base"
]
},
"collection": {
"use": [
"array-extras",
"arraylist",
"arraylist-add",
"arraylist-filter",
"array-invoke"
]
},
"console": {
"lang": [
"en",
"es"
],
"requires": [
"yui-log",
"widget",
"substitute"
],
"skinnable": true
},
"console-filters": {
"requires": [
"plugin",
"console"
],
"skinnable": true
},
"controller": {
"optional": [
"querystring-parse"
],
"requires": [
"array-extras",
"base-build",
"history"
]
},
"cookie": {
"requires": [
"yui-base"
]
},
"createlink-base": {
"requires": [
"editor-base"
]
},
"cssbase": {
"after": [
"cssreset",
"cssfonts",
"cssgrids",
"cssreset-context",
"cssfonts-context",
"cssgrids-context"
],
"type": "css"
},
"cssbase-context": {
"after": [
"cssreset",
"cssfonts",
"cssgrids",
"cssreset-context",
"cssfonts-context",
"cssgrids-context"
],
"type": "css"
},
"cssfonts": {
"type": "css"
},
"cssfonts-context": {
"type": "css"
},
"cssgrids": {
"optional": [
"cssreset",
"cssfonts"
],
"type": "css"
},
"cssreset": {
"type": "css"
},
"cssreset-context": {
"type": "css"
},
"dataschema": {
"use": [
"dataschema-base",
"dataschema-json",
"dataschema-xml",
"dataschema-array",
"dataschema-text"
]
},
"dataschema-array": {
"requires": [
"dataschema-base"
]
},
"dataschema-base": {
"requires": [
"base"
]
},
"dataschema-json": {
"requires": [
"dataschema-base",
"json"
]
},
"dataschema-text": {
"requires": [
"dataschema-base"
]
},
"dataschema-xml": {
"requires": [
"dataschema-base"
]
},
"datasource": {
"use": [
"datasource-local",
"datasource-io",
"datasource-get",
"datasource-function",
"datasource-cache",
"datasource-jsonschema",
"datasource-xmlschema",
"datasource-arrayschema",
"datasource-textschema",
"datasource-polling"
]
},
"datasource-arrayschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-array"
]
},
"datasource-cache": {
"requires": [
"datasource-local",
"plugin",
"cache-base"
]
},
"datasource-function": {
"requires": [
"datasource-local"
]
},
"datasource-get": {
"requires": [
"datasource-local",
"get"
]
},
"datasource-io": {
"requires": [
"datasource-local",
"io-base"
]
},
"datasource-jsonschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-json"
]
},
"datasource-local": {
"requires": [
"base"
]
},
"datasource-polling": {
"requires": [
"datasource-local"
]
},
"datasource-textschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-text"
]
},
"datasource-xmlschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-xml"
]
},
"datatable": {
"use": [
"datatable-base",
"datatable-datasource",
"datatable-sort",
"datatable-scroll"
]
},
"datatable-base": {
"requires": [
"recordset-base",
"widget",
"substitute",
"event-mouseenter"
],
"skinnable": true
},
"datatable-datasource": {
"requires": [
"datatable-base",
"plugin",
"datasource-local"
]
},
"datatable-scroll": {
"requires": [
"datatable-base",
"plugin",
"stylesheet"
]
},
"datatable-sort": {
"lang": [
"en"
],
"requires": [
"datatable-base",
"plugin",
"recordset-sort"
]
},
"datatype": {
"use": [
"datatype-number",
"datatype-date",
"datatype-xml"
]
},
"datatype-date": {
"supersedes": [
"datatype-date-format"
],
"use": [
"datatype-date-parse",
"datatype-date-format"
]
},
"datatype-date-format": {
"lang": [
"ar",
"ar-JO",
"ca",
"ca-ES",
"da",
"da-DK",
"de",
"de-AT",
"de-DE",
"el",
"el-GR",
"en",
"en-AU",
"en-CA",
"en-GB",
"en-IE",
"en-IN",
"en-JO",
"en-MY",
"en-NZ",
"en-PH",
"en-SG",
"en-US",
"es",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-EC",
"es-ES",
"es-MX",
"es-PE",
"es-PY",
"es-US",
"es-UY",
"es-VE",
"fi",
"fi-FI",
"fr",
"fr-BE",
"fr-CA",
"fr-FR",
"hi",
"hi-IN",
"id",
"id-ID",
"it",
"it-IT",
"ja",
"ja-JP",
"ko",
"ko-KR",
"ms",
"ms-MY",
"nb",
"nb-NO",
"nl",
"nl-BE",
"nl-NL",
"pl",
"pl-PL",
"pt",
"pt-BR",
"ro",
"ro-RO",
"ru",
"ru-RU",
"sv",
"sv-SE",
"th",
"th-TH",
"tr",
"tr-TR",
"vi",
"vi-VN",
"zh-Hans",
"zh-Hans-CN",
"zh-Hant",
"zh-Hant-HK",
"zh-Hant-TW"
]
},
"datatype-date-math": {
"requires": [
"yui-base"
]
},
"datatype-date-parse": {},
"datatype-number": {
"use": [
"datatype-number-parse",
"datatype-number-format"
]
},
"datatype-number-format": {},
"datatype-number-parse": {},
"datatype-xml": {
"use": [
"datatype-xml-parse",
"datatype-xml-format"
]
},
"datatype-xml-format": {},
"datatype-xml-parse": {},
"dd": {
"use": [
"dd-ddm-base",
"dd-ddm",
"dd-ddm-drop",
"dd-drag",
"dd-proxy",
"dd-constrain",
"dd-drop",
"dd-scroll",
"dd-delegate"
]
},
"dd-constrain": {
"requires": [
"dd-drag"
]
},
"dd-ddm": {
"requires": [
"dd-ddm-base",
"event-resize"
]
},
"dd-ddm-base": {
"requires": [
"node",
"base",
"yui-throttle",
"classnamemanager"
]
},
"dd-ddm-drop": {
"requires": [
"dd-ddm"
]
},
"dd-delegate": {
"requires": [
"dd-drag",
"dd-drop-plugin",
"event-mouseenter"
]
},
"dd-drag": {
"requires": [
"dd-ddm-base"
]
},
"dd-drop": {
"requires": [
"dd-drag",
"dd-ddm-drop"
]
},
"dd-drop-plugin": {
"requires": [
"dd-drop"
]
},
"dd-gestures": {
"condition": {
"name": "dd-gestures",
"test": function(Y) {
return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome));
},
"trigger": "dd-drag"
},
"requires": [
"dd-drag",
"event-synthetic",
"event-gestures"
]
},
"dd-plugin": {
"optional": [
"dd-constrain",
"dd-proxy"
],
"requires": [
"dd-drag"
]
},
"dd-proxy": {
"requires": [
"dd-drag"
]
},
"dd-scroll": {
"requires": [
"dd-drag"
]
},
"dial": {
"lang": [
"en",
"es"
],
"requires": [
"widget",
"dd-drag",
"substitute",
"event-mouseenter",
"event-move",
"event-key",
"transition",
"intl"
],
"skinnable": true
},
"dom": {
"use": [
"dom-base",
"dom-screen",
"dom-style",
"selector-native",
"selector"
]
},
"dom-base": {
"requires": [
"dom-core"
]
},
"dom-core": {
"requires": [
"oop",
"features"
]
},
"dom-deprecated": {
"requires": [
"dom-base"
]
},
"dom-screen": {
"requires": [
"dom-base",
"dom-style"
]
},
"dom-style": {
"requires": [
"dom-base"
]
},
"dom-style-ie": {
"condition": {
"name": "dom-style-ie",
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
},
"requires": [
"dom-style"
]
},
"dump": {},
"editor": {
"use": [
"frame",
"selection",
"exec-command",
"editor-base",
"editor-para",
"editor-br",
"editor-bidi",
"editor-tab",
"createlink-base"
]
},
"editor-base": {
"requires": [
"base",
"frame",
"node",
"exec-command",
"selection"
]
},
"editor-bidi": {
"requires": [
"editor-base"
]
},
"editor-br": {
"requires": [
"editor-base"
]
},
"editor-lists": {
"requires": [
"editor-base"
]
},
"editor-para": {
"requires": [
"editor-base"
]
},
"editor-tab": {
"requires": [
"editor-base"
]
},
"escape": {},
"event": {
"after": [
"node-base"
],
"use": [
"event-base",
"event-delegate",
"event-synthetic",
"event-mousewheel",
"event-mouseenter",
"event-key",
"event-focus",
"event-resize",
"event-hover",
"event-outside"
]
},
"event-base": {
"after": [
"node-base"
],
"requires": [
"event-custom-base"
]
},
"event-base-ie": {
"after": [
"event-base"
],
"condition": {
"name": "event-base-ie",
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
},
"requires": [
"node-base"
]
},
"event-custom": {
"use": [
"event-custom-base",
"event-custom-complex"
]
},
"event-custom-base": {
"requires": [
"oop"
]
},
"event-custom-complex": {
"requires": [
"event-custom-base"
]
},
"event-delegate": {
"requires": [
"node-base"
]
},
"event-flick": {
"requires": [
"node-base",
"event-touch",
"event-synthetic"
]
},
"event-focus": {
"requires": [
"event-synthetic"
]
},
"event-gestures": {
"use": [
"event-flick",
"event-move"
]
},
"event-hover": {
"requires": [
"event-mouseenter"
]
},
"event-key": {
"requires": [
"event-synthetic"
]
},
"event-mouseenter": {
"requires": [
"event-synthetic"
]
},
"event-mousewheel": {
"requires": [
"node-base"
]
},
"event-move": {
"requires": [
"node-base",
"event-touch",
"event-synthetic"
]
},
"event-outside": {
"requires": [
"event-synthetic"
]
},
"event-resize": {
"requires": [
"node-base"
]
},
"event-simulate": {
"requires": [
"event-base"
]
},
"event-synthetic": {
"requires": [
"node-base",
"event-custom-complex"
]
},
"event-touch": {
"requires": [
"node-base"
]
},
"event-valuechange": {
"requires": [
"event-focus",
"event-synthetic"
]
},
"exec-command": {
"requires": [
"frame"
]
},
"features": {
"requires": [
"yui-base"
]
},
"frame": {
"requires": [
"base",
"node",
"selector-css3",
"substitute",
"yui-throttle"
]
},
"get": {
"requires": [
"yui-base"
]
},
"graphics": {
"requires": [
"node",
"event-custom",
"pluginhost"
]
},
"graphics-canvas": {
"condition": {
"name": "graphics-canvas",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
},
"requires": [
"graphics"
]
},
"graphics-canvas-default": {
"condition": {
"name": "graphics-canvas-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
}
},
"graphics-svg": {
"condition": {
"name": "graphics-svg",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
},
"requires": [
"graphics"
]
},
"graphics-svg-default": {
"condition": {
"name": "graphics-svg-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
}
},
"graphics-vml": {
"condition": {
"name": "graphics-vml",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
},
"requires": [
"graphics"
]
},
"graphics-vml-default": {
"condition": {
"name": "graphics-vml-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
}
},
"highlight": {
"use": [
"highlight-base",
"highlight-accentfold"
]
},
"highlight-accentfold": {
"requires": [
"highlight-base",
"text-accentfold"
]
},
"highlight-base": {
"requires": [
"array-extras",
"escape",
"text-wordbreak"
]
},
"history": {
"use": [
"history-base",
"history-hash",
"history-hash-ie",
"history-html5"
]
},
"history-base": {
"requires": [
"event-custom-complex"
]
},
"history-hash": {
"after": [
"history-html5"
],
"requires": [
"event-synthetic",
"history-base",
"yui-later"
]
},
"history-hash-ie": {
"condition": {
"name": "history-hash-ie",
"test": function (Y) {
var docMode = Y.config.doc && Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
},
"requires": [
"history-hash",
"node-base"
]
},
"history-html5": {
"optional": [
"json"
],
"requires": [
"event-base",
"history-base",
"node-base"
]
},
"imageloader": {
"requires": [
"base-base",
"node-style",
"node-screen"
]
},
"intl": {
"requires": [
"intl-base",
"event-custom"
]
},
"intl-base": {
"requires": [
"yui-base"
]
},
"io": {
"use": [
"io-base",
"io-xdr",
"io-form",
"io-upload-iframe",
"io-queue"
]
},
"io-base": {
"requires": [
"event-custom-base",
"querystring-stringify-simple"
]
},
"io-form": {
"requires": [
"io-base",
"node-base"
]
},
"io-queue": {
"requires": [
"io-base",
"queue-promote"
]
},
"io-upload-iframe": {
"requires": [
"io-base",
"node-base"
]
},
"io-xdr": {
"requires": [
"io-base",
"datatype-xml"
]
},
"json": {
"use": [
"json-parse",
"json-stringify"
]
},
"json-parse": {},
"json-stringify": {},
"jsonp": {
"requires": [
"get",
"oop"
]
},
"jsonp-url": {
"requires": [
"jsonp"
]
},
"loader": {
"use": [
"loader-base",
"loader-rollup",
"loader-yui3"
]
},
"loader-base": {
"requires": [
"get"
]
},
"loader-rollup": {
"requires": [
"loader-base"
]
},
"loader-yui3": {
"requires": [
"loader-base"
]
},
"model": {
"requires": [
"base-build",
"escape",
"json-parse"
]
},
"model-list": {
"requires": [
"array-extras",
"array-invoke",
"arraylist",
"base-build",
"escape",
"json-parse",
"model"
]
},
"node": {
"use": [
"node-base",
"node-event-delegate",
"node-pluginhost",
"node-screen",
"node-style"
]
},
"node-base": {
"requires": [
"event-base",
"node-core",
"dom-base"
]
},
"node-core": {
"requires": [
"dom-core",
"selector"
]
},
"node-deprecated": {
"requires": [
"node-base"
]
},
"node-event-delegate": {
"requires": [
"node-base",
"event-delegate"
]
},
"node-event-html5": {
"requires": [
"node-base"
]
},
"node-event-simulate": {
"requires": [
"node-base",
"event-simulate"
]
},
"node-flick": {
"requires": [
"classnamemanager",
"transition",
"event-flick",
"plugin"
],
"skinnable": true
},
"node-focusmanager": {
"requires": [
"attribute",
"node",
"plugin",
"node-event-simulate",
"event-key",
"event-focus"
]
},
"node-load": {
"requires": [
"node-base",
"io-base"
]
},
"node-menunav": {
"requires": [
"node",
"classnamemanager",
"plugin",
"node-focusmanager"
],
"skinnable": true
},
"node-pluginhost": {
"requires": [
"node-base",
"pluginhost"
]
},
"node-screen": {
"requires": [
"dom-screen",
"node-base"
]
},
"node-style": {
"requires": [
"dom-style",
"node-base"
]
},
"oop": {
"requires": [
"yui-base"
]
},
"overlay": {
"requires": [
"widget",
"widget-stdmod",
"widget-position",
"widget-position-align",
"widget-stack",
"widget-position-constrain"
],
"skinnable": true
},
"panel": {
"requires": [
"widget",
"widget-stdmod",
"widget-position",
"widget-position-align",
"widget-stack",
"widget-position-constrain",
"widget-modality",
"widget-autohide",
"widget-buttons"
],
"skinnable": true
},
"plugin": {
"requires": [
"base-base"
]
},
"pluginhost": {
"use": [
"pluginhost-base",
"pluginhost-config"
]
},
"pluginhost-base": {
"requires": [
"yui-base"
]
},
"pluginhost-config": {
"requires": [
"pluginhost-base"
]
},
"profiler": {
"requires": [
"yui-base"
]
},
"querystring": {
"use": [
"querystring-parse",
"querystring-stringify"
]
},
"querystring-parse": {
"requires": [
"yui-base",
"array-extras"
]
},
"querystring-parse-simple": {
"requires": [
"yui-base"
]
},
"querystring-stringify": {
"requires": [
"yui-base"
]
},
"querystring-stringify-simple": {
"requires": [
"yui-base"
]
},
"queue-promote": {
"requires": [
"yui-base"
]
},
"range-slider": {
"requires": [
"slider-base",
"slider-value-range",
"clickable-rail"
]
},
"recordset": {
"use": [
"recordset-base",
"recordset-sort",
"recordset-filter",
"recordset-indexer"
]
},
"recordset-base": {
"requires": [
"base",
"arraylist"
]
},
"recordset-filter": {
"requires": [
"recordset-base",
"array-extras",
"plugin"
]
},
"recordset-indexer": {
"requires": [
"recordset-base",
"plugin"
]
},
"recordset-sort": {
"requires": [
"arraysort",
"recordset-base",
"plugin"
]
},
"resize": {
"use": [
"resize-base",
"resize-proxy",
"resize-constrain"
]
},
"resize-base": {
"requires": [
"base",
"widget",
"substitute",
"event",
"oop",
"dd-drag",
"dd-delegate",
"dd-drop"
],
"skinnable": true
},
"resize-constrain": {
"requires": [
"plugin",
"resize-base"
]
},
"resize-plugin": {
"optional": [
"resize-constrain"
],
"requires": [
"resize-base",
"plugin"
]
},
"resize-proxy": {
"requires": [
"plugin",
"resize-base"
]
},
"rls": {
"requires": [
"get",
"features"
]
},
"scrollview": {
"requires": [
"scrollview-base",
"scrollview-scrollbars"
]
},
"scrollview-base": {
"requires": [
"widget",
"event-gestures",
"transition"
],
"skinnable": true
},
"scrollview-base-ie": {
"condition": {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
},
"requires": [
"scrollview-base"
]
},
"scrollview-list": {
"requires": [
"plugin"
],
"skinnable": true
},
"scrollview-paginator": {
"requires": [
"plugin"
]
},
"scrollview-scrollbars": {
"requires": [
"classnamemanager",
"transition",
"plugin"
],
"skinnable": true
},
"selection": {
"requires": [
"node"
]
},
"selector": {
"requires": [
"selector-native"
]
},
"selector-css2": {
"condition": {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
},
"requires": [
"selector-native"
]
},
"selector-css3": {
"requires": [
"selector-native",
"selector-css2"
]
},
"selector-native": {
"requires": [
"dom-base"
]
},
"shim-plugin": {
"requires": [
"node-style",
"node-pluginhost"
]
},
"slider": {
"use": [
"slider-base",
"slider-value-range",
"clickable-rail",
"range-slider"
]
},
"slider-base": {
"requires": [
"widget",
"dd-constrain",
"substitute"
],
"skinnable": true
},
"slider-value-range": {
"requires": [
"slider-base"
]
},
"sortable": {
"requires": [
"dd-delegate",
"dd-drop-plugin",
"dd-proxy"
]
},
"sortable-scroll": {
"requires": [
"dd-scroll",
"sortable"
]
},
"stylesheet": {},
"substitute": {
"optional": [
"dump"
]
},
"swf": {
"requires": [
"event-custom",
"node",
"swfdetect",
"escape"
]
},
"swfdetect": {},
"tabview": {
"requires": [
"widget",
"widget-parent",
"widget-child",
"tabview-base",
"node-pluginhost",
"node-focusmanager"
],
"skinnable": true
},
"tabview-base": {
"requires": [
"node-event-delegate",
"classnamemanager",
"skin-sam-tabview"
]
},
"tabview-plugin": {
"requires": [
"tabview-base"
]
},
"test": {
"requires": [
"event-simulate",
"event-custom",
"substitute",
"json-stringify"
],
"skinnable": true
},
"text": {
"use": [
"text-accentfold",
"text-wordbreak"
]
},
"text-accentfold": {
"requires": [
"array-extras",
"text-data-accentfold"
]
},
"text-data-accentfold": {},
"text-data-wordbreak": {},
"text-wordbreak": {
"requires": [
"array-extras",
"text-data-wordbreak"
]
},
"transition": {
"requires": [
"node-style"
]
},
"transition-timer": {
"condition": {
"name": "transition-timer",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
node = (DOCUMENT) ? DOCUMENT.documentElement: null,
ret = true;
if (node && node.style) {
ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style);
}
return ret;
},
"trigger": "transition"
},
"requires": [
"transition"
]
},
"uploader": {
"requires": [
"event-custom",
"node",
"base",
"swf"
]
},
"view": {
"requires": [
"base-build",
"node-event-delegate"
]
},
"widget": {
"use": [
"widget-base",
"widget-htmlparser",
"widget-uievents",
"widget-skin"
]
},
"widget-anim": {
"requires": [
"plugin",
"anim-base",
"widget"
]
},
"widget-autohide": {
"requires": [
"widget",
"event-outside",
"base-build",
"event-key"
],
"skinnable": false
},
"widget-base": {
"requires": [
"attribute",
"event-focus",
"base-base",
"base-pluginhost",
"node-base",
"node-style",
"classnamemanager"
],
"skinnable": true
},
"widget-base-ie": {
"condition": {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
},
"requires": [
"widget-base"
]
},
"widget-buttons": {
"requires": [
"widget",
"base-build"
],
"skinnable": false
},
"widget-child": {
"requires": [
"base-build",
"widget"
]
},
"widget-htmlparser": {
"requires": [
"widget-base"
]
},
"widget-locale": {
"requires": [
"widget-base"
]
},
"widget-modality": {
"requires": [
"widget",
"event-outside",
"base-build"
],
"skinnable": false
},
"widget-parent": {
"requires": [
"base-build",
"arraylist",
"widget"
]
},
"widget-position": {
"requires": [
"base-build",
"node-screen",
"widget"
]
},
"widget-position-align": {
"requires": [
"widget-position"
]
},
"widget-position-constrain": {
"requires": [
"widget-position"
]
},
"widget-skin": {
"requires": [
"widget-base"
]
},
"widget-stack": {
"requires": [
"base-build",
"widget"
],
"skinnable": true
},
"widget-stdmod": {
"requires": [
"base-build",
"widget"
]
},
"widget-uievents": {
"requires": [
"widget-base",
"node-event-delegate"
]
},
"yql": {
"requires": [
"jsonp",
"jsonp-url"
]
},
"yui": {},
"yui-base": {},
"yui-later": {
"requires": [
"yui-base"
]
},
"yui-log": {
"requires": [
"yui-base"
]
},
"yui-rls": {},
"yui-throttle": {
"requires": [
"yui-base"
]
}
};
YUI.Env[Y.version].md5 = '516f2598fb0cef4337e32df3a89e5124';
}, '@VERSION@' ,{requires:['loader-base']});
YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3' ]});
|
application/ui/pages/login.js | areida/spacesynter | 'use strict';
import React from 'react';
import Button from '../components/buttons/button';
class Login extends React.Component {
constructor(props)
{
super(props);
this.state = {
loggedIn : props.flux.store('Token').isLoggedIn()
};
}
componentDidMount()
{
this.authenticate();
}
componentDidUpdate()
{
this.authenticate();
}
authenticate()
{
if (this.state.loggedIn) {
this.context.router.transitionTo('/');
}
}
render()
{
return (
<div className='login'>
<Button><a href='/gh-login'>Login with GitHub</a></Button>
</div>
);
}
}
Login.displayName = 'Login';
Login.contextTypes = {
router : React.PropTypes.func
};
export default Login; |
app/javascript/mastodon/containers/timeline_container.js | verniy6462/mastodon | import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { hydrateStore } from '../actions/store';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import PublicTimeline from '../features/standalone/public_timeline';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
const store = configureStore();
const initialStateContainer = document.getElementById('initial-state');
if (initialStateContainer !== null) {
const initialState = JSON.parse(initialStateContainer.textContent);
store.dispatch(hydrateStore(initialState));
}
export default class TimelineContainer extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
};
render () {
const { locale } = this.props;
return (
<IntlProvider locale={locale} messages={messages}>
<Provider store={store}>
<PublicTimeline />
</Provider>
</IntlProvider>
);
}
}
|
data-browser-ui/public/app/components/tableComponents/td/listComponents/genericAddToList.js | CloudBoost/cloudboost | import React from 'react';
import ReactDOM from 'react-dom';
import Dropzone from 'react-dropzone';
import SelectRelation from '../relationComponents/selectRelation.js'
import FilePicker from '../filePicker'
class GenericAddToList extends React.Component {
constructor(){
super()
this.state = {
isOpenSelect:false,
isFilePickerOpen:false
}
}
addRecord(type,e){
if(type == 'Number'){
this.props.addToElementData(0)
} else if(type == 'DateTime'){
this.props.addToElementData(new Date())
} else if(type == 'GeoPoint'){
this.props.addToElementData(new CB.CloudGeoPoint(0,0))
} else if(type == 'Boolean'){
this.props.addToElementData(false)
} else {
this.props.addToElementData('')
}
}
// drop handler for filepicker
dropHandler(file){
this.props.addToElementData(file)
}
// close/open handler for file pciker
openCloseFilePicker(what){
this.state.isFilePickerOpen = what
this.setState(this.state)
}
updateElementRealtion(relationObject){
this.props.addToElementData(relationObject)
}
updateObject(){
//dummy --- to make select relation re-usable
}
openCloseModal(what,which){
this.state[which] = what
this.setState(this.state)
}
componentDidMount(){
}
render() {
let element = ''
if(this.props.columnType == 'File'){
element =
<div>
<div className="filelistpopoeveraddfile" onClick={this.openCloseFilePicker.bind(this,true)}>
<i className="ion-paperclip attahcfilepop" aria-hidden="true"></i>
</div>
<FilePicker chooseFile={ this.dropHandler.bind(this) } isFilePickerOpen={this.state.isFilePickerOpen} openCloseFilePicker={this.openCloseFilePicker.bind(this)} />
</div>
} else if(['Text','Email','URL','EncryptedText','Boolean','Number','DateTime','GeoPoint','Object'].indexOf(this.props.columnType) == -1){
// for relation type
element = <div className="listbottomdiv"><button className="addtextrecord" onClick={this.openCloseModal.bind(this,true,'isOpenSelect')}>+ Add New Record</button></div>
} else {
// for other datatypes except from relation and File
element = <div className="listbottomdiv"><button className="addtextrecord" onClick={ this.addRecord.bind(this,this.props.columnType) }>+ Add New Record</button></div>
}
return (
<div>
{ element }
{
this.state.isOpenSelect ? <SelectRelation
table={ this.props.columnType }
updateObject={ this.updateObject.bind(this) }
updateElement={ this.updateElementRealtion.bind(this) }
open={ this.state.isOpenSelect }
openCloseModal={ this.openCloseModal.bind(this) }
/> : ''
}
</div>
);
}
}
export default GenericAddToList; |
src/svg-icons/image/blur-off.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBlurOff = (props) => (
<SvgIcon {...props}>
<path d="M14 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-.2 4.48l.2.02c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5l.02.2c.09.67.61 1.19 1.28 1.28zM14 3.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm-4 0c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm11 7c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM10 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm8 8c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-4 13.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM2.5 5.27l3.78 3.78L6 9c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l2.81 2.81c-.71.11-1.25.73-1.25 1.47 0 .83.67 1.5 1.5 1.5.74 0 1.36-.54 1.47-1.25l2.81 2.81c-.09-.03-.18-.06-.28-.06-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l3.78 3.78L20 20.23 3.77 4 2.5 5.27zM10 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm11-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 13c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zM3 9.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm7 11c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-3-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5z"/>
</SvgIcon>
);
ImageBlurOff = pure(ImageBlurOff);
ImageBlurOff.displayName = 'ImageBlurOff';
ImageBlurOff.muiName = 'SvgIcon';
export default ImageBlurOff;
|
public/js/components/trends/TrendContainer.react.js | MadushikaPerera/Coupley | import React from 'react';
import List from 'material-ui/lib/lists/list';
import Divider from 'material-ui/lib/divider';
import TextField from 'material-ui/lib/text-field';
import TrendsStore from '../../stores/TrendsStore';
import TrendsAction from '../../actions/TrendsAction';
import Trend from './trendbox.react';
import TrendPost from './trendactivityListComp.react';
var SearchCeck = true;
var listClick = true;
const style1={
width:200,
height:300,
};
const searchconvo = {
marginTop:'-18',
paddingLeft:10,
paddingRight:50,
width:150,
};
function validateStatusText(textStatus) {
if (textStatus.length > 250) {
return {
error: '*search is too long',
};
} else if (textStatus.length == 0) {
console.log('empty');
return {
error: '*search cannot be empty',
};
} else {
return true;
}
};
const TrendContainer = React.createClass({
getInitialState: function() {
return {
trendsResult:TrendsStore.gettrendslist(),
statusText: '',
value:'',
trendsPostResult:TrendsStore.getFirstTrendsSearchPost(),
}
},
componentDidMount: function() {
TrendsStore.addChangeListener(this._onChange);
TrendsAction.getTrendsList();
TrendsAction.getTrendsInitialSearchPosts();
},
_onChange: function () {
if (SearchCeck) {
this.setState({trendsResult:TrendsStore.gettrendslist()});
} else if (!SearchCeck) {
this.setState({ trendsResult:TrendsStore.getTrendsSearchList()});
}
this.setState({ trendsPostResult:TrendsStore. getFirstTrendsSearchPost()});
},
trendItem: function () {
return this.state.trendsResult.map((result) => {
return (<Trend abc={this.getHashtag} trends={result.trend} tid={result.id}/>);
});
},
SearchTren:function () {
var trd=this.refs.SearchT.getValue();
let ThisTrend ={
trend:trd,
}
console.log(ThisTrend.trend);
if (validateStatusText(ThisTrend).error) {
console.log('menna error');
this.setState({
statusText: validateStatusText(ThisTrend).error,
});
val = false;
} else {
console.log('error na');
TrendsAction.getTrendsSearchList(ThisTrend);
SearchCeck = false;
this.setState({
statusText: '',
});
}
{this.trendSearchItem();}
{this.clearText();}
},
getHashtag:function (e) {
console.log('clicked');
var E= e.substr(1);
let trend={
strend:E,
};
console.log(E);
TrendsAction.getTrendsSearchPosts(trend);
},
trendSearchItem: function () {
this.setState({ trendsResult:TrendsStore.getTrendsSearchList()});
console.log('menna result');
console.log(this.state.trendsResult);
return this.state.trendsResult.map((result) => {
return (<Trend trends={result.trend} tid={result.id}/>);
});
},
trendPostItem: function () {
return this.state.trendsPostResult.map((result) => {
return (<TrendPost firstName={result.firstname} postText={result.post_text} created_at={result.created_at}/>);
});
},
clearText:function () {
document.getElementById('SearchField').value = '';
},
EnterKey(e) {
if (e.key === 'Enter') {
console.log('enter una');
{this.SearchTren();}
}
},
render:function(){
return(
<div>
<div style={style1} className="col-xs-4">
<List zDepth={1}>
<div><h4>Trends</h4></div>
<Divider/>
<div>
<TextField hintText="#Trends" floatingLabelText="Search Trends" style={searchconvo} errorText={this.state.statusText} onKeyPress={this.EnterKey}
ref="SearchT" id="SearchField"/>
</div>
<Divider/>
{this.trendItem()}
</List>
</div>
<div className="col-xs-8">
{this.trendPostItem()}
</div>
</div>
);
}
});
export default TrendContainer;
|
test/AlertSpec.js | RichardLitt/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Alert from '../src/Alert';
describe('Alert', function () {
it('Should output a alert with message', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert>
<strong>Message</strong>
</Alert>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
});
it('Should have bsType by default', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert>
Message
</Alert>
);
assert.ok(instance.getDOMNode().className.match(/\balert\b/));
});
it('Should have dismissable style with onDismiss', function () {
let noOp = function () {};
let instance = ReactTestUtils.renderIntoDocument(
<Alert onDismiss={noOp}>
Message
</Alert>
);
assert.ok(instance.getDOMNode().className.match(/\balert-dismissable\b/));
});
it('Should call onDismiss callback on dismiss click', function (done) {
let doneOp = function () {
done();
};
let instance = ReactTestUtils.renderIntoDocument(
<Alert onDismiss={doneOp}>
Message
</Alert>
);
ReactTestUtils.Simulate.click(instance.getDOMNode().children[0]);
});
it('Should call onDismiss callback on dismissAfter time', function (done) {
let doneOp = function () {
done();
};
ReactTestUtils.renderIntoDocument(
<Alert onDismiss={doneOp} dismissAfter={1}>
Message
</Alert>
);
});
it('Should have a default bsStyle class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert>
Message
</Alert>
);
assert.ok(instance.getDOMNode().className.match(/\balert-\w+\b/));
});
it('Should have use bsStyle class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert bsStyle='danger'>
Message
</Alert>
);
assert.ok(instance.getDOMNode().className.match(/\balert-danger\b/));
});
});
|
src/layouts/index.js | hologram-io/docs | import React from 'react'
import Helmet from 'react-helmet'
import { Navbar } from '../components'
import '../scss/main.scss'
import { SEO_DEFAULTS } from '../constants'
const { TITLE, DESCRIPTION, KEYWORDS } = SEO_DEFAULTS;
/*
This layout is applied to any page in the "pages" folder.
*/
class Basic extends React.Component {
constructor(props) {
super(props);
}
render() {
const { children } = this.props;
return (
<div className="full-height row-stacked docs">
<Helmet title={TITLE} meta={this.getMetaData()} />
<Navbar />
{children()}
</div>
)
}
getMetaData() {
return [
{ name: 'description', content: DESCRIPTION },
{ name: 'keywords', content: KEYWORDS }
];
}
}
export default Basic;
|
src/Grid/Grid.js | react-mdl/react-mdl | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import clamp from 'clamp';
import shadows from '../utils/shadows';
const propTypes = {
className: PropTypes.string,
component: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
PropTypes.func
]),
noSpacing: PropTypes.bool,
shadow: PropTypes.number
};
const Grid = (props) => {
const { noSpacing, className, children, component, shadow, ...otherProps } = props;
const hasShadow = typeof shadow !== 'undefined';
const shadowLevel = clamp(shadow || 0, 0, shadows.length - 1);
const classes = classNames('mdl-grid', {
'mdl-grid--no-spacing': noSpacing,
[shadows[shadowLevel]]: hasShadow
}, className);
return React.createElement(component || 'div', {
className: classes,
...otherProps
}, children);
};
Grid.propTypes = propTypes;
export default Grid;
|
src/ButtonGroup.js | tonylinyy/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import CustomPropTypes from './utils/CustomPropTypes';
const ButtonGroup = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
vertical: React.PropTypes.bool,
justified: React.PropTypes.bool,
/**
* Display block buttons, only useful when used with the "vertical" prop.
* @type {bool}
*/
block: CustomPropTypes.all([
React.PropTypes.bool,
function(props, propName, componentName) {
if (props.block && !props.vertical) {
return new Error('The block property requires the vertical property to be set to have any effect');
}
}
])
},
getDefaultProps() {
return {
bsClass: 'button-group'
};
},
render() {
let classes = this.getBsClassSet();
classes['btn-group'] = !this.props.vertical;
classes['btn-group-vertical'] = this.props.vertical;
classes['btn-group-justified'] = this.props.justified;
classes['btn-block'] = this.props.block;
return (
<div
{...this.props}
className={classNames(this.props.className, classes)}>
{this.props.children}
</div>
);
}
});
export default ButtonGroup;
|
src/Button/Button.spec.js | dsslimshaddy/material-ui | // @flow
import React from 'react';
import { assert } from 'chai';
import { createShallow, createRender, getClasses } from '../test-utils';
import Button from './Button';
describe('<Button />', () => {
let shallow;
let render;
let classes;
before(() => {
shallow = createShallow({ dive: true });
render = createRender();
classes = getClasses(<Button>Hello World</Button>);
});
it('should render a <ButtonBase> element', () => {
const wrapper = shallow(<Button>Hello World</Button>);
assert.strictEqual(wrapper.name(), 'withStyles(ButtonBase)');
assert.strictEqual(
wrapper.props().type,
'button',
'should render with the button type attribute',
);
});
it('should render with the root class but no others', () => {
const wrapper = shallow(<Button>Hello World</Button>);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.raised), false, 'should not have the raised class');
assert.strictEqual(wrapper.hasClass(classes.fab), false, 'should not have the fab class');
assert.strictEqual(
wrapper.hasClass(classes.flatPrimary),
false,
'should not have the primary class',
);
assert.strictEqual(
wrapper.hasClass(classes.flatAccent),
false,
'should not have the accent class',
);
});
it('should render the custom className and the root class', () => {
const wrapper = shallow(<Button className="test-class-name">Hello World</Button>);
assert.strictEqual(wrapper.is('.test-class-name'), true, 'should pass the test className');
assert.strictEqual(wrapper.hasClass(classes.root), true);
});
it('should render a primary button', () => {
const wrapper = shallow(<Button color="primary">Hello World</Button>);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.raised), false, 'should have the raised class');
assert.strictEqual(wrapper.hasClass(classes.fab), false, 'should not have the fab class');
assert.strictEqual(
wrapper.hasClass(classes.flatPrimary),
true,
'should have the primary class',
);
assert.strictEqual(
wrapper.hasClass(classes.flatAccent),
false,
'should not have the accent class',
);
});
it('should render an accent button', () => {
const wrapper = shallow(<Button color="accent">Hello World</Button>);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.raised), false, 'should have the raised class');
assert.strictEqual(wrapper.hasClass(classes.fab), false, 'should not have the fab class');
assert.strictEqual(
wrapper.hasClass(classes.flatPrimary),
false,
'should not have the primary class',
);
assert.strictEqual(
wrapper.hasClass(classes.flatAccent),
true,
'should not have the accent class',
);
});
it('should render a raised button', () => {
const wrapper = shallow(<Button raised>Hello World</Button>);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.raised), true, 'should have the raised class');
assert.strictEqual(wrapper.hasClass(classes.fab), false, 'should not have the fab class');
assert.strictEqual(
wrapper.hasClass(classes.flatPrimary),
false,
'should not have the primary class',
);
assert.strictEqual(
wrapper.hasClass(classes.flatAccent),
false,
'should not have the accent class',
);
});
it('should render a raised primary button', () => {
const wrapper = shallow(
<Button raised color="primary">
Hello World
</Button>,
);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.raised), true, 'should have the raised class');
assert.strictEqual(wrapper.hasClass(classes.fab), false, 'should not have the fab class');
assert.strictEqual(
wrapper.hasClass(classes.raisedPrimary),
true,
'should not have the primary class',
);
assert.strictEqual(
wrapper.hasClass(classes.raisedAccent),
false,
'should not have the accent class',
);
});
it('should render a raised accent button', () => {
const wrapper = shallow(
<Button raised color="accent">
Hello World
</Button>,
);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.raised), true, 'should have the raised class');
assert.strictEqual(wrapper.hasClass(classes.fab), false, 'should not have the fab class');
assert.strictEqual(
wrapper.hasClass(classes.raisedPrimary),
false,
'should not have the primary class',
);
assert.strictEqual(
wrapper.hasClass(classes.raisedAccent),
true,
'should have the accent class',
);
});
it('should render a floating action button', () => {
const wrapper = shallow(<Button fab>Hello World</Button>);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.raised), true, 'should have the raised class');
assert.strictEqual(wrapper.hasClass(classes.fab), true, 'should have the fab class');
assert.strictEqual(
wrapper.hasClass(classes.flatPrimary),
false,
'should not have the primary class',
);
assert.strictEqual(
wrapper.hasClass(classes.flatAccent),
false,
'should not have the accent class',
);
});
it('should render a primary floating action button', () => {
const wrapper = shallow(
<Button fab color="primary">
Hello World
</Button>,
);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.raised), true, 'should have the raised class');
assert.strictEqual(wrapper.hasClass(classes.fab), true, 'should have the fab class');
assert.strictEqual(
wrapper.hasClass(classes.raisedPrimary),
true,
'should have the primary class',
);
assert.strictEqual(
wrapper.hasClass(classes.raisedAccent),
false,
'should not have the accent class',
);
});
it('should render an accent floating action button', () => {
const wrapper = shallow(
<Button fab color="accent">
Hello World
</Button>,
);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.raised), true, 'should have the raised class');
assert.strictEqual(wrapper.hasClass(classes.fab), true, 'should have the fab class');
assert.strictEqual(
wrapper.hasClass(classes.raisedPrimary),
false,
'should not have the primary class',
);
assert.strictEqual(
wrapper.hasClass(classes.raisedAccent),
true,
'should have the accent class',
);
});
it('should have a ripple by default', () => {
const wrapper = shallow(<Button>Hello World</Button>);
assert.strictEqual(wrapper.props().disableRipple, false);
});
it('should pass disableRipple to ButtonBase', () => {
const wrapper = shallow(<Button disableRipple>Hello World</Button>);
assert.strictEqual(wrapper.props().disableRipple, true);
});
it('should have a focusRipple by default', () => {
const wrapper = shallow(<Button>Hello World</Button>);
assert.strictEqual(wrapper.props().focusRipple, true, 'should set focusRipple to true');
});
it('should pass disableFocusRipple to ButtonBase', () => {
const wrapper = shallow(<Button disableFocusRipple>Hello World</Button>);
assert.strictEqual(wrapper.props().focusRipple, false, 'should set focusRipple to false');
});
describe('server side', () => {
// Only run the test on node.
if (!/jsdom/.test(window.navigator.userAgent)) {
return;
}
it('should server side render', () => {
const markup = render(<Button>Hello World</Button>);
assert.strictEqual(markup.text(), 'Hello World');
});
});
});
|
docs/api/swagger-ui-standalone-preset.js | phenoscape/owlery | !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SwaggerUIStandalonePreset=e():t.SwaggerUIStandalonePreset=e()}(this,function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.i=function(t){return t},n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/dist",n(n.s=540)}([function(t,e,n){"use strict";var r=n(47),i=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],o=["scalar","sequence","mapping"];t.exports=function(t,e){var n,s;if(e=e||{},Object.keys(e).forEach(function(e){if(-1===i.indexOf(e))throw new r('Unknown option "'+e+'" is met in definition of "'+t+'" YAML type.')}),this.tag=t,this.kind=e.kind||null,this.resolve=e.resolve||function(){return!0},this.construct=e.construct||function(t){return t},this.instanceOf=e.instanceOf||null,this.predicate=e.predicate||null,this.represent=e.represent||null,this.defaultStyle=e.defaultStyle||null,this.styleAliases=(n=e.styleAliases||null,s={},null!==n&&Object.keys(n).forEach(function(t){n[t].forEach(function(e){s[String(e)]=t})}),s),-1===o.indexOf(this.kind))throw new r('Unknown kind "'+this.kind+'" is specified for "'+t+'" YAML type.')}},function(t,e,n){var r=n(154)("wks"),i=n(109),o=n(4).Symbol,s="function"==typeof o;(t.exports=function(t){return r[t]||(r[t]=s&&o[t]||(s?o:i)("Symbol."+t))}).store=r},function(t,e){var n=t.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n)},function(t,e,n){var r=n(4),i=n(10),o=n(19),s=n(30),a=n(60),u=function(t,e,n){var c,l,h,f,p=t&u.F,d=t&u.G,m=t&u.S,v=t&u.P,y=t&u.B,g=d?r:m?r[e]||(r[e]={}):(r[e]||{}).prototype,x=d?i:i[e]||(i[e]={}),b=x.prototype||(x.prototype={});for(c in d&&(n=e),n)h=((l=!p&&g&&void 0!==g[c])?g:n)[c],f=y&&l?a(h,r):v&&"function"==typeof h?a(Function.call,h):h,g&&s(g,c,h,t&u.U),x[c]!=h&&o(x,c,f),v&&b[c]!=h&&(b[c]=h)};r.core=i,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e,n){var r=n(3),i=n(42),o=n(11),s=/"/g,a=function(t,e,n,r){var i=String(o(t)),a="<"+e;return""!==n&&(a+=" "+n+'="'+String(r).replace(s,""")+'"'),a+">"+i+"</"+e+">"};t.exports=function(t,e){var n={};n[t]=e(a),r(r.P+r.F*i(function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3}),"String",n)}},function(t,e,n){var r=n(94)("wks"),i=n(58),o=n(9).Symbol,s="function"==typeof o;(t.exports=function(t){return r[t]||(r[t]=s&&o[t]||(s?o:i)("Symbol."+t))}).store=r},function(t,e,n){var r=n(178),i="object"==typeof self&&self&&self.Object===Object&&self,o=r||i||Function("return this")();t.exports=o},function(t,e){var n=Array.isArray;t.exports=n},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e){var n=t.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n)},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){"use strict";t.exports=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t}},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){t.exports=!n(25)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(9),i=n(2),o=n(135),s=n(26),a=n(16),u=function(t,e,n){var c,l,h,f=t&u.F,p=t&u.G,d=t&u.S,m=t&u.P,v=t&u.B,y=t&u.W,g=p?i:i[e]||(i[e]={}),x=g.prototype,b=p?r:d?r[e]:(r[e]||{}).prototype;for(c in p&&(n=e),n)(l=!f&&b&&void 0!==b[c])&&a(g,c)||(h=l?b[c]:n[c],g[c]=p&&"function"!=typeof b[c]?n[c]:v&&l?o(h,r):y&&b[c]==h?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e.prototype=t.prototype,e}(h):m&&"function"==typeof h?o(Function.call,h):h,m&&((g.virtual||(g.virtual={}))[c]=h,t&u.R&&x&&!x[c]&&s(x,c,h)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){var r=n(24),i=n(137),o=n(96),s=Object.defineProperty;e.f=n(14)?Object.defineProperty:function(t,e,n){if(r(t),e=o(e,!0),r(n),i)try{return s(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){var r=n(29);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e,n){var r=n(63),i=n(153);t.exports=n(41)?function(t,e,n){return r.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){"use strict";var r=n(340),i=Math.max;t.exports=function(t){return i(0,r(t))}},function(t,e,n){"use strict";var r=function(t){};t.exports=function(t,e,n,i,o,s,a,u){if(r(e),!t){var c;if(void 0===e)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,i,o,s,a,u],h=0;(c=new Error(e.replace(/%s/g,function(){return l[h++]}))).name="Invariant Violation"}throw c.framesToPop=1,c}}},function(t,e,n){"use strict"},function(t,e,n){"use strict";var r=n(82),i=Object.keys||function(t){var e=[];for(var n in t)e.push(n);return e};t.exports=h;var o=n(45);o.inherits=n(32);var s=n(198),a=n(121);o.inherits(h,s);for(var u=i(a.prototype),c=0;c<u.length;c++){var l=u[c];h.prototype[l]||(h.prototype[l]=a.prototype[l])}function h(t){if(!(this instanceof h))return new h(t);s.call(this,t),a.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",f)}function f(){this.allowHalfOpen||this._writableState.ended||r.nextTick(p,this)}function p(t){t.end()}Object.defineProperty(h.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(h.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}),h.prototype._destroy=function(t,e){this.push(null),this.end(),r.nextTick(e,t)}},function(t,e,n){var r=n(27);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,n){var r=n(17),i=n(56);t.exports=n(14)?function(t,e,n){return r.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,n){var r=n(138),i=n(88);t.exports=function(t){return r(i(t))}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,n){var r=n(4),i=n(19),o=n(62),s=n(109)("src"),a=Function.toString,u=(""+a).split("toString");n(10).inspectSource=function(t){return a.call(t)},(t.exports=function(t,e,n,a){var c="function"==typeof n;c&&(o(n,"name")||i(n,"name",e)),t[e]!==n&&(c&&(o(n,s)||i(n,s,t[e]?""+t[e]:u.join(String(e)))),t===r?t[e]=n:a?t[e]?t[e]=n:i(t,e,n):(delete t[e],i(t,e,n)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[s]||a.call(this)})},function(t,e,n){"use strict";var r=n(161)();t.exports=function(t){return t!==r&&null!==t}},function(t,e){"function"==typeof Object.create?t.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(t,e){t.super_=e;var n=function(){};n.prototype=e.prototype,t.prototype=new n,t.prototype.constructor=t}},function(t,e,n){"use strict";function r(t){return void 0===t||null===t}t.exports.isNothing=r,t.exports.isObject=function(t){return"object"==typeof t&&null!==t},t.exports.toArray=function(t){return Array.isArray(t)?t:r(t)?[]:[t]},t.exports.repeat=function(t,e){var n,r="";for(n=0;n<e;n+=1)r+=t;return r},t.exports.isNegativeZero=function(t){return 0===t&&Number.NEGATIVE_INFINITY===1/t},t.exports.extend=function(t,e){var n,r,i,o;if(e)for(n=0,r=(o=Object.keys(e)).length;n<r;n+=1)t[i=o[n]]=e[i];return t}},function(t,e,n){"use strict";var r=n(33),i=n(47),o=n(0);function s(t,e,n){var r=[];return t.include.forEach(function(t){n=s(t,e,n)}),t[e].forEach(function(t){n.forEach(function(e,n){e.tag===t.tag&&e.kind===t.kind&&r.push(n)}),n.push(t)}),n.filter(function(t,e){return-1===r.indexOf(e)})}function a(t){this.include=t.include||[],this.implicit=t.implicit||[],this.explicit=t.explicit||[],this.implicit.forEach(function(t){if(t.loadKind&&"scalar"!==t.loadKind)throw new i("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=s(this,"implicit",[]),this.compiledExplicit=s(this,"explicit",[]),this.compiledTypeMap=function(){var t,e,n={scalar:{},sequence:{},mapping:{},fallback:{}};function r(t){n[t.kind][t.tag]=n.fallback[t.tag]=t}for(t=0,e=arguments.length;t<e;t+=1)arguments[t].forEach(r);return n}(this.compiledImplicit,this.compiledExplicit)}a.DEFAULT=null,a.create=function(){var t,e;switch(arguments.length){case 1:t=a.DEFAULT,e=arguments[0];break;case 2:t=arguments[0],e=arguments[1];break;default:throw new i("Wrong number of arguments for Schema.create function")}if(t=r.toArray(t),e=r.toArray(e),!t.every(function(t){return t instanceof a}))throw new i("Specified list of super schemas (or a single Schema object) contains a non-Schema object.");if(!e.every(function(t){return t instanceof o}))throw new i("Specified list of YAML types (or a single Type object) contains a non-Type object.");return new a({include:t,explicit:e})},t.exports=a},function(t,e,n){var r=n(405),i=n(434);t.exports=function(t,e){var n=i(t,e);return r(n)?n:void 0}},function(t,e){var n,r,i=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(t){n=o}try{r="function"==typeof clearTimeout?clearTimeout:s}catch(t){r=s}}();var u,c=[],l=!1,h=-1;function f(){l&&u&&(l=!1,u.length?c=u.concat(c):h=-1,c.length&&p())}function p(){if(!l){var t=a(f);l=!0;for(var e=c.length;e;){for(u=c,c=[];++h<e;)u&&u[h].run();h=-1,e=c.length}u=null,l=!1,function(t){if(r===clearTimeout)return clearTimeout(t);if((r===s||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(t);try{r(t)}catch(e){try{return r.call(null,t)}catch(e){return r.call(this,t)}}}(t)}}function d(t,e){this.fun=t,this.array=e}function m(){}i.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new d(t,e)),1!==c.length||l||a(p)},d.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=m,i.addListener=m,i.once=m,i.off=m,i.removeListener=m,i.removeAllListeners=m,i.emit=m,i.prependListener=m,i.prependOnceListener=m,i.listeners=function(t){return[]},i.binding=function(t){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(t){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},function(t,e,n){"use strict";var r=n(53),i=n(193),o=(n(69),n(196),Object.prototype.hasOwnProperty),s=n(194),a={key:!0,ref:!0,__self:!0,__source:!0};function u(t){return void 0!==t.ref}function c(t){return void 0!==t.key}var l=function(t,e,n,r,i,o,a){var u={$$typeof:s,type:t,key:e,ref:n,props:a,_owner:o};return u};l.createElement=function(t,e,n){var r,s={},h=null,f=null;if(null!=e)for(r in u(e)&&(f=e.ref),c(e)&&(h=""+e.key),void 0===e.__self?null:e.__self,void 0===e.__source?null:e.__source,e)o.call(e,r)&&!a.hasOwnProperty(r)&&(s[r]=e[r]);var p=arguments.length-2;if(1===p)s.children=n;else if(p>1){for(var d=Array(p),m=0;m<p;m++)d[m]=arguments[m+2];0,s.children=d}if(t&&t.defaultProps){var v=t.defaultProps;for(r in v)void 0===s[r]&&(s[r]=v[r])}return l(t,h,f,0,0,i.current,s)},l.createFactory=function(t){var e=l.createElement.bind(null,t);return e.type=t,e},l.cloneAndReplaceKey=function(t,e){return l(t.type,e,t.ref,t._self,t._source,t._owner,t.props)},l.cloneElement=function(t,e,n){var s,h,f=r({},t.props),p=t.key,d=t.ref,m=(t._self,t._source,t._owner);if(null!=e)for(s in u(e)&&(d=e.ref,m=i.current),c(e)&&(p=""+e.key),t.type&&t.type.defaultProps&&(h=t.type.defaultProps),e)o.call(e,s)&&!a.hasOwnProperty(s)&&(void 0===e[s]&&void 0!==h?f[s]=h[s]:f[s]=e[s]);var v=arguments.length-2;if(1===v)f.children=n;else if(v>1){for(var y=Array(v),g=0;g<v;g++)y[g]=arguments[g+2];f.children=y}return l(t.type,p,d,0,0,m,f)},l.isValidElement=function(t){return"object"==typeof t&&null!==t&&t.$$typeof===s},t.exports=l},function(t,e){t.exports={}},function(t,e,n){var r=n(143),i=n(89);t.exports=Object.keys||function(t){return r(t,i)}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e,n){t.exports=!n(42)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e){t.exports={}},function(t,e,n){var r=n(64),i=Math.min;t.exports=function(t){return t>0?i(r(t),9007199254740991):0}},function(t,e,n){(function(t){function n(t){return Object.prototype.toString.call(t)}e.isArray=function(t){return Array.isArray?Array.isArray(t):"[object Array]"===n(t)},e.isBoolean=function(t){return"boolean"==typeof t},e.isNull=function(t){return null===t},e.isNullOrUndefined=function(t){return null==t},e.isNumber=function(t){return"number"==typeof t},e.isString=function(t){return"string"==typeof t},e.isSymbol=function(t){return"symbol"==typeof t},e.isUndefined=function(t){return void 0===t},e.isRegExp=function(t){return"[object RegExp]"===n(t)},e.isObject=function(t){return"object"==typeof t&&null!==t},e.isDate=function(t){return"[object Date]"===n(t)},e.isError=function(t){return"[object Error]"===n(t)||t instanceof Error},e.isFunction=function(t){return"function"==typeof t},e.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},e.isBuffer=t.isBuffer}).call(e,n(81).Buffer)},function(t,e,n){"use strict";var r=n(31);t.exports=function(t){if(!r(t))throw new TypeError("Cannot use null or undefined");return t}},function(t,e,n){"use strict";function r(t,e){Error.call(this),this.name="YAMLException",this.reason=t,this.mark=e,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack||""}r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r.prototype.toString=function(t){var e=this.name+": ";return e+=this.reason||"(unknown reason)",!t&&this.mark&&(e+=" "+this.mark.toString()),e},t.exports=r},function(t,e,n){"use strict";var r=n(34);t.exports=new r({include:[n(170)],implicit:[n(381),n(374)],explicit:[n(366),n(376),n(377),n(379)]})},function(t,e,n){var r=n(72),i=n(431),o=n(460),s="[object Null]",a="[object Undefined]",u=r?r.toStringTag:void 0;t.exports=function(t){return null==t?void 0===t?a:s:u&&u in Object(t)?i(t):o(t)}},function(t,e){t.exports=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}},function(t,e){t.exports=function(t){return null!=t&&"object"==typeof t}},function(t,e,n){var r=n(416);t.exports=function(t){return null==t?"":r(t)}},function(t,e,n){"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/var r=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(e).map(function(t){return e[t]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(t){r[t]=t}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var n,s,a=function(t){if(null===t||void 0===t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),u=1;u<arguments.length;u++){for(var c in n=Object(arguments[u]))i.call(n,c)&&(a[c]=n[c]);if(r){s=r(n);for(var l=0;l<s.length;l++)o.call(n,s[l])&&(a[s[l]]=n[s[l]])}}return a}},function(t,e){t.exports=!0},function(t,e){e.f={}.propertyIsEnumerable},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var r=n(88);t.exports=function(t){return Object(r(t))}},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,n){var r=n(59);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)}}return function(){return t.apply(e,arguments)}}},function(t,e,n){"use strict";var r=n(19),i=n(30),o=n(42),s=n(11),a=n(1);t.exports=function(t,e,n){var u=a(t),c=n(s,u,""[t]),l=c[0],h=c[1];o(function(){var e={};return e[u]=function(){return 7},7!=""[t](e)})&&(i(String.prototype,t,l),r(RegExp.prototype,u,2==e?function(t,e){return h.call(t,this,e)}:function(t){return h.call(t,this)}))}},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){var r=n(18),i=n(273),o=n(292),s=Object.defineProperty;e.f=n(41)?Object.defineProperty:function(t,e,n){if(r(t),e=o(e,!0),r(n),i)try{return s(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e,n){var r=n(275),i=n(11);t.exports=function(t){return r(i(t))}},function(t,e,n){"use strict";var r=n(162),i=n(165),o=n(344),s=n(349);(t.exports=function(t,e){var n,o,a,u,c;return arguments.length<2||"string"!=typeof t?(u=e,e=t,t=null):u=arguments[2],null==t?(n=a=!0,o=!1):(n=s.call(t,"c"),o=s.call(t,"e"),a=s.call(t,"w")),c={value:e,configurable:n,enumerable:o,writable:a},u?r(i(u),c):c}).gs=function(t,e,n){var a,u,c,l;return"string"!=typeof t?(c=n,n=e,e=t,t=null):c=arguments[3],null==e?e=void 0:o(e)?null==n?n=void 0:o(n)||(c=n,n=void 0):(c=e,e=n=void 0),null==t?(a=!0,u=!1):(a=s.call(t,"c"),u=s.call(t,"e")),l={get:e,set:n,configurable:a,enumerable:u},c?r(i(c),l):l}},function(t,e,n){"use strict";t.exports=n(341)("forEach")},function(t,e,n){"use strict";function r(t){return function(){return t}}var i=function(){};i.thatReturns=r,i.thatReturnsFalse=r(!1),i.thatReturnsTrue=r(!0),i.thatReturnsNull=r(null),i.thatReturnsThis=function(){return this},i.thatReturnsArgument=function(t){return t},t.exports=i},function(t,e,n){"use strict";var r=n(68);t.exports=r},function(t,e,n){"use strict";var r=n(34);t.exports=r.DEFAULT=new r({include:[n(48)],explicit:[n(372),n(371),n(370)]})},function(t,e,n){var r=n(446),i=n(447),o=n(448),s=n(449),a=n(450);function u(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}u.prototype.clear=r,u.prototype.delete=i,u.prototype.get=o,u.prototype.has=s,u.prototype.set=a,t.exports=u},function(t,e,n){var r=n(7).Symbol;t.exports=r},function(t,e,n){var r=n(77);t.exports=function(t,e){for(var n=t.length;n--;)if(r(t[n][0],e))return n;return-1}},function(t,e,n){var r=n(443);t.exports=function(t,e){var n=t.__data__;return r(e)?n["string"==typeof e?"string":"hash"]:n.map}},function(t,e,n){var r=n(35)(Object,"create");t.exports=r},function(t,e,n){var r=n(79),i=1/0;t.exports=function(t){if("string"==typeof t||r(t))return t;var e=t+"";return"0"==e&&1/t==-i?"-0":e}},function(t,e){t.exports=function(t,e){return t===e||t!=t&&e!=e}},function(t,e,n){var r=n(185),i=n(119);t.exports=function(t){return null!=t&&i(t.length)&&!r(t)}},function(t,e,n){var r=n(49),i=n(51),o="[object Symbol]";t.exports=function(t){return"symbol"==typeof t||i(t)&&r(t)==o}},function(t,e,n){var r=n(390),i=n(407),o=n(78);t.exports=function(t){return o(t)?r(t):i(t)}},function(t,e,n){"use strict";(function(t){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
var r=n(225),i=n(360),o=n(169);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t,e){if(s()<e)throw new RangeError("Invalid typed array length");return u.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=u.prototype:(null===t&&(t=new u(e)),t.length=e),t}function u(t,e,n){if(!(u.TYPED_ARRAY_SUPPORT||this instanceof u))return new u(t,e,n);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return h(this,t)}return c(this,t,e,n)}function c(t,e,n,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(t,e,n,r){if(e.byteLength,n<0||e.byteLength<n)throw new RangeError("'offset' is out of bounds");if(e.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");e=void 0===n&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,n):new Uint8Array(e,n,r);u.TYPED_ARRAY_SUPPORT?(t=e).__proto__=u.prototype:t=f(t,e);return t}(t,e,n,r):"string"==typeof e?function(t,e,n){"string"==typeof n&&""!==n||(n="utf8");if(!u.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|d(e,n),i=(t=a(t,r)).write(e,n);i!==r&&(t=t.slice(0,i));return t}(t,e,n):function(t,e){if(u.isBuffer(e)){var n=0|p(e.length);return 0===(t=a(t,n)).length?t:(e.copy(t,0,0,n),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(r=e.length)!=r?a(t,0):f(t,e);if("Buffer"===e.type&&o(e.data))return f(t,e.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function l(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function h(t,e){if(l(e),t=a(t,e<0?0:0|p(e)),!u.TYPED_ARRAY_SUPPORT)for(var n=0;n<e;++n)t[n]=0;return t}function f(t,e){var n=e.length<0?0:0|p(e.length);t=a(t,n);for(var r=0;r<n;r+=1)t[r]=255&e[r];return t}function p(t){if(t>=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function d(t,e){if(u.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return z(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return U(t).length;default:if(r)return z(t).length;e=(""+e).toLowerCase(),r=!0}}function m(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function v(t,e,n,r,i){if(0===t.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(i)return-1;n=t.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof e&&(e=u.from(e,r)),u.isBuffer(e))return 0===e.length?-1:y(t,e,n,r,i);if("number"==typeof e)return e&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):y(t,[e],n,r,i);throw new TypeError("val must be string, number or Buffer")}function y(t,e,n,r,i){var o,s=1,a=t.length,u=e.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,n/=2}function c(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var l=-1;for(o=n;o<a;o++)if(c(t,o)===c(e,-1===l?0:o-l)){if(-1===l&&(l=o),o-l+1===u)return l*s}else-1!==l&&(o-=o-l),l=-1}else for(n+u>a&&(n=a-u),o=n;o>=0;o--){for(var h=!0,f=0;f<u;f++)if(c(t,o+f)!==c(e,f)){h=!1;break}if(h)return o}return-1}function g(t,e,n,r){n=Number(n)||0;var i=t.length-n;r?(r=Number(r))>i&&(r=i):r=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var s=0;s<r;++s){var a=parseInt(e.substr(2*s,2),16);if(isNaN(a))return s;t[n+s]=a}return s}function x(t,e,n,r){return J(z(e,t.length-n),t,n,r)}function b(t,e,n,r){return J(function(t){for(var e=[],n=0;n<t.length;++n)e.push(255&t.charCodeAt(n));return e}(e),t,n,r)}function D(t,e,n,r){return b(t,e,n,r)}function E(t,e,n,r){return J(U(e),t,n,r)}function w(t,e,n,r){return J(function(t,e){for(var n,r,i,o=[],s=0;s<t.length&&!((e-=2)<0);++s)n=t.charCodeAt(s),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(e,t.length-n),t,n,r)}function _(t,e,n){return 0===e&&n===t.length?r.fromByteArray(t):r.fromByteArray(t.slice(e,n))}function S(t,e,n){n=Math.min(t.length,n);for(var r=[],i=e;i<n;){var o,s,a,u,c=t[i],l=null,h=c>239?4:c>223?3:c>191?2:1;if(i+h<=n)switch(h){case 1:c<128&&(l=c);break;case 2:128==(192&(o=t[i+1]))&&(u=(31&c)<<6|63&o)>127&&(l=u);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(u=(15&c)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=t[i+1],s=t[i+2],a=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(l=u)}null===l?(l=65533,h=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),i+=h}return function(t){var e=t.length;if(e<=A)return String.fromCharCode.apply(String,t);var n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=A));return n}(r)}e.Buffer=u,e.SlowBuffer=function(t){+t!=t&&(t=0);return u.alloc(+t)},e.INSPECT_MAX_BYTES=50,u.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=s(),u.poolSize=8192,u._augment=function(t){return t.__proto__=u.prototype,t},u.from=function(t,e,n){return c(null,t,e,n)},u.TYPED_ARRAY_SUPPORT&&(u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0})),u.alloc=function(t,e,n){return function(t,e,n,r){return l(e),e<=0?a(t,e):void 0!==n?"string"==typeof r?a(t,e).fill(n,r):a(t,e).fill(n):a(t,e)}(null,t,e,n)},u.allocUnsafe=function(t){return h(null,t)},u.allocUnsafeSlow=function(t){return h(null,t)},u.isBuffer=function(t){return!(null==t||!t._isBuffer)},u.compare=function(t,e){if(!u.isBuffer(t)||!u.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var n=t.length,r=e.length,i=0,o=Math.min(n,r);i<o;++i)if(t[i]!==e[i]){n=t[i],r=e[i];break}return n<r?-1:r<n?1:0},u.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(t,e){if(!o(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return u.alloc(0);var n;if(void 0===e)for(e=0,n=0;n<t.length;++n)e+=t[n].length;var r=u.allocUnsafe(e),i=0;for(n=0;n<t.length;++n){var s=t[n];if(!u.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,i),i+=s.length}return r},u.byteLength=d,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)m(this,e,e+1);return this},u.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)m(this,e,e+3),m(this,e+1,e+2);return this},u.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)m(this,e,e+7),m(this,e+1,e+6),m(this,e+2,e+5),m(this,e+3,e+4);return this},u.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?S(this,0,t):function(t,e,n){var r=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return F(this,e,n);case"utf8":case"utf-8":return S(this,e,n);case"ascii":return C(this,e,n);case"latin1":case"binary":return k(this,e,n);case"base64":return _(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}.apply(this,arguments)},u.prototype.equals=function(t){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===u.compare(this,t)},u.prototype.inspect=function(){var t="",n=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),"<Buffer "+t+">"},u.prototype.compare=function(t,e,n,r,i){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),e<0||n>t.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&e>=n)return 0;if(r>=i)return-1;if(e>=n)return 1;if(e>>>=0,n>>>=0,r>>>=0,i>>>=0,this===t)return 0;for(var o=i-r,s=n-e,a=Math.min(o,s),c=this.slice(r,i),l=t.slice(e,n),h=0;h<a;++h)if(c[h]!==l[h]){o=c[h],s=l[h];break}return o<s?-1:s<o?1:0},u.prototype.includes=function(t,e,n){return-1!==this.indexOf(t,e,n)},u.prototype.indexOf=function(t,e,n){return v(this,t,e,n,!0)},u.prototype.lastIndexOf=function(t,e,n){return v(this,t,e,n,!1)},u.prototype.write=function(t,e,n,r){if(void 0===e)r="utf8",n=this.length,e=0;else if(void 0===n&&"string"==typeof e)r=e,n=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-e;if((void 0===n||n>i)&&(n=i),t.length>0&&(n<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return g(this,t,e,n);case"utf8":case"utf-8":return x(this,t,e,n);case"ascii":return b(this,t,e,n);case"latin1":case"binary":return D(this,t,e,n);case"base64":return E(this,t,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,t,e,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var A=4096;function C(t,e,n){var r="";n=Math.min(t.length,n);for(var i=e;i<n;++i)r+=String.fromCharCode(127&t[i]);return r}function k(t,e,n){var r="";n=Math.min(t.length,n);for(var i=e;i<n;++i)r+=String.fromCharCode(t[i]);return r}function F(t,e,n){var r=t.length;(!e||e<0)&&(e=0),(!n||n<0||n>r)&&(n=r);for(var i="",o=e;o<n;++o)i+=R(t[o]);return i}function T(t,e,n){for(var r=t.slice(e,n),i="",o=0;o<r.length;o+=2)i+=String.fromCharCode(r[o]+256*r[o+1]);return i}function I(t,e,n){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>n)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,n,r,i,o){if(!u.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<o)throw new RangeError('"value" argument is out of bounds');if(n+r>t.length)throw new RangeError("Index out of range")}function M(t,e,n,r){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-n,2);i<o;++i)t[n+i]=(e&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function B(t,e,n,r){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-n,4);i<o;++i)t[n+i]=e>>>8*(r?i:3-i)&255}function P(t,e,n,r,i,o){if(n+r>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function j(t,e,n,r,o){return o||P(t,0,n,4),i.write(t,e,n,r,23,4),n+4}function N(t,e,n,r,o){return o||P(t,0,n,8),i.write(t,e,n,r,52,8),n+8}u.prototype.slice=function(t,e){var n,r=this.length;if(t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t),u.TYPED_ARRAY_SUPPORT)(n=this.subarray(t,e)).__proto__=u.prototype;else{var i=e-t;n=new u(i,void 0);for(var o=0;o<i;++o)n[o]=this[o+t]}return n},u.prototype.readUIntLE=function(t,e,n){t|=0,e|=0,n||I(t,e,this.length);for(var r=this[t],i=1,o=0;++o<e&&(i*=256);)r+=this[t+o]*i;return r},u.prototype.readUIntBE=function(t,e,n){t|=0,e|=0,n||I(t,e,this.length);for(var r=this[t+--e],i=1;e>0&&(i*=256);)r+=this[t+--e]*i;return r},u.prototype.readUInt8=function(t,e){return e||I(t,1,this.length),this[t]},u.prototype.readUInt16LE=function(t,e){return e||I(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUInt16BE=function(t,e){return e||I(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUInt32LE=function(t,e){return e||I(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUInt32BE=function(t,e){return e||I(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readIntLE=function(t,e,n){t|=0,e|=0,n||I(t,e,this.length);for(var r=this[t],i=1,o=0;++o<e&&(i*=256);)r+=this[t+o]*i;return r>=(i*=128)&&(r-=Math.pow(2,8*e)),r},u.prototype.readIntBE=function(t,e,n){t|=0,e|=0,n||I(t,e,this.length);for(var r=e,i=1,o=this[t+--r];r>0&&(i*=256);)o+=this[t+--r]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},u.prototype.readInt8=function(t,e){return e||I(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u.prototype.readInt16LE=function(t,e){e||I(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt16BE=function(t,e){e||I(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt32LE=function(t,e){return e||I(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,e){return e||I(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readFloatLE=function(t,e){return e||I(t,4,this.length),i.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,e){return e||I(t,4,this.length),i.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,e){return e||I(t,8,this.length),i.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,e){return e||I(t,8,this.length),i.read(this,t,!1,52,8)},u.prototype.writeUIntLE=function(t,e,n,r){(t=+t,e|=0,n|=0,r)||O(this,t,e,n,Math.pow(2,8*n)-1,0);var i=1,o=0;for(this[e]=255&t;++o<n&&(i*=256);)this[e+o]=t/i&255;return e+n},u.prototype.writeUIntBE=function(t,e,n,r){(t=+t,e|=0,n|=0,r)||O(this,t,e,n,Math.pow(2,8*n)-1,0);var i=n-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+n},u.prototype.writeUInt8=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,1,255,0),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},u.prototype.writeUInt16LE=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):M(this,t,e,!0),e+2},u.prototype.writeUInt16BE=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):M(this,t,e,!1),e+2},u.prototype.writeUInt32LE=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):B(this,t,e,!0),e+4},u.prototype.writeUInt32BE=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):B(this,t,e,!1),e+4},u.prototype.writeIntLE=function(t,e,n,r){if(t=+t,e|=0,!r){var i=Math.pow(2,8*n-1);O(this,t,e,n,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o<n&&(s*=256);)t<0&&0===a&&0!==this[e+o-1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+n},u.prototype.writeIntBE=function(t,e,n,r){if(t=+t,e|=0,!r){var i=Math.pow(2,8*n-1);O(this,t,e,n,i-1,-i)}var o=n-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+n},u.prototype.writeInt8=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,1,127,-128),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},u.prototype.writeInt16LE=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):M(this,t,e,!0),e+2},u.prototype.writeInt16BE=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):M(this,t,e,!1),e+2},u.prototype.writeInt32LE=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):B(this,t,e,!0),e+4},u.prototype.writeInt32BE=function(t,e,n){return t=+t,e|=0,n||O(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):B(this,t,e,!1),e+4},u.prototype.writeFloatLE=function(t,e,n){return j(this,t,e,!0,n)},u.prototype.writeFloatBE=function(t,e,n){return j(this,t,e,!1,n)},u.prototype.writeDoubleLE=function(t,e,n){return N(this,t,e,!0,n)},u.prototype.writeDoubleBE=function(t,e,n){return N(this,t,e,!1,n)},u.prototype.copy=function(t,e,n,r){if(n||(n=0),r||0===r||(r=this.length),e>=t.length&&(e=t.length),e||(e=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),t.length-e<r-n&&(r=t.length-e+n);var i,o=r-n;if(this===t&&n<e&&e<r)for(i=o-1;i>=0;--i)t[i+e]=this[i+n];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(i=0;i<o;++i)t[i+e]=this[i+n];else Uint8Array.prototype.set.call(t,this.subarray(n,n+o),e);return o},u.prototype.fill=function(t,e,n,r){if("string"==typeof t){if("string"==typeof e?(r=e,e=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===t.length){var i=t.charCodeAt(0);i<256&&(t=i)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!u.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<n)throw new RangeError("Out of range index");if(n<=e)return this;var o;if(e>>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(o=e;o<n;++o)this[o]=t;else{var s=u.isBuffer(t)?t:z(new u(t,r).toString()),a=s.length;for(o=0;o<n-e;++o)this[o+e]=s[o%a]}return this};var L=/[^+\/0-9A-Za-z-_]/g;function R(t){return t<16?"0"+t.toString(16):t.toString(16)}function z(t,e){var n;e=e||1/0;for(var r=t.length,i=null,o=[],s=0;s<r;++s){if((n=t.charCodeAt(s))>55295&&n<57344){if(!i){if(n>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(e-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(e-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((e-=1)<0)break;o.push(n)}else if(n<2048){if((e-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((e-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function U(t){return r.toByteArray(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(L,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function J(t,e,n,r){for(var i=0;i<r&&!(i+n>=e.length||i>=t.length);++i)e[i+n]=t[i];return i}}).call(e,n(13))},function(t,e,n){"use strict";(function(e){!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:function(t,n,r,i){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o,s,a=arguments.length;switch(a){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function(){t.call(null,n)});case 3:return e.nextTick(function(){t.call(null,n,r)});case 4:return e.nextTick(function(){t.call(null,n,r,i)});default:for(o=new Array(a-1),s=0;s<o.length;)o[s++]=arguments[s];return e.nextTick(function(){t.apply(null,o)})}}}:t.exports=e}).call(e,n(36))},function(t,e,n){"use strict";t.exports=function(t){for(var e=arguments.length-1,n="Minified React error #"+t+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+t,r=0;r<e;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);n+=" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";var i=new Error(n);throw i.name="Invariant Violation",i.framesToPop=1,i}},function(t,e,n){var r=n(81),i=r.Buffer;function o(t,e){for(var n in t)e[n]=t[n]}function s(t,e,n){return i(t,e,n)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=r:(o(r,e),e.Buffer=s),o(i,s),s.from=function(t,e,n){if("number"==typeof t)throw new TypeError("Argument must not be a number");return i(t,e,n)},s.alloc=function(t,e,n){if("number"!=typeof t)throw new TypeError("Argument must be a number");var r=i(t);return void 0!==e?"string"==typeof n?r.fill(e,n):r.fill(e):r.fill(0),r},s.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return i(t)},s.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}},function(t,e,n){t.exports={default:n(228),__esModule:!0}},function(t,e,n){"use strict";e.__esModule=!0;var r=s(n(223)),i=s(n(222)),o="function"==typeof i.default&&"symbol"==typeof r.default?function(t){return typeof t}:function(t){return t&&"function"==typeof i.default&&t.constructor===i.default&&t!==i.default.prototype?"symbol":typeof t};function s(t){return t&&t.__esModule?t:{default:t}}e.default="function"==typeof i.default&&"symbol"===o(r.default)?function(t){return void 0===t?"undefined":o(t)}:function(t){return t&&"function"==typeof i.default&&t.constructor===i.default&&t!==i.default.prototype?"symbol":void 0===t?"undefined":o(t)}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,n){var r=n(24),i=n(249),o=n(89),s=n(93)("IE_PROTO"),a=function(){},u=function(){var t,e=n(136)("iframe"),r=o.length;for(e.style.display="none",n(243).appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),u=t.F;r--;)delete u.prototype[o[r]];return u()};t.exports=Object.create||function(t,e){var n;return null!==t?(a.prototype=r(t),n=new a,a.prototype=null,n[s]=t):n=u(),void 0===e?n:i(n,e)}},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e,n){var r=n(17).f,i=n(16),o=n(6)("toStringTag");t.exports=function(t,e,n){t&&!i(t=n?t:t.prototype,o)&&r(t,o,{configurable:!0,value:e})}},function(t,e,n){var r=n(94)("keys"),i=n(58);t.exports=function(t){return r[t]||(r[t]=i(t))}},function(t,e,n){var r=n(2),i=n(9),o=i["__core-js_shared__"]||(i["__core-js_shared__"]={});(t.exports=function(t,e){return o[t]||(o[t]=void 0!==e?e:{})})("versions",[]).push({version:r.version,mode:n(54)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"})},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e,n){var r=n(27);t.exports=function(t,e){if(!r(t))return t;var n,i;if(e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;if("function"==typeof(n=t.valueOf)&&!r(i=n.call(t)))return i;if(!e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;throw TypeError("Can't convert object to primitive value")}},function(t,e,n){var r=n(9),i=n(2),o=n(54),s=n(98),a=n(17).f;t.exports=function(t){var e=i.Symbol||(i.Symbol=o?{}:r.Symbol||{});"_"==t.charAt(0)||t in e||a(e,t,{value:s.f(t)})}},function(t,e,n){e.f=n(6)},function(t,e,n){"use strict";var r=n(252)(!0);n(139)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=r(e,n),this._i+=t.length,{value:t,done:!1})})},function(t,e,n){n(258);for(var r=n(9),i=n(26),o=n(38),s=n(6)("toStringTag"),a="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),u=0;u<a.length;u++){var c=a[u],l=r[c],h=l&&l.prototype;h&&!h[s]&&i(h,s,c),o[c]=o.Array}},function(t,e,n){var r=n(40),i=n(1)("toStringTag"),o="Arguments"==r(function(){return arguments}());t.exports=function(t){var e,n,s;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=Object(t),i))?n:o?r(e):"Object"==(s=r(e))&&"function"==typeof e.callee?"Arguments":s}},function(t,e,n){var r=n(29),i=n(4).document,o=r(i)&&r(i.createElement);t.exports=function(t){return o?i.createElement(t):{}}},function(t,e,n){var r=n(1)("match");t.exports=function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[r]=!1,!"/./"[t](e)}catch(t){}}return!0}},function(t,e){t.exports=!1},function(t,e,n){"use strict";var r=n(59);t.exports.f=function(t){return new function(t){var e,n;this.promise=new t(function(t,r){if(void 0!==e||void 0!==n)throw TypeError("Bad Promise constructor");e=t,n=r}),this.resolve=r(e),this.reject=r(n)}(t)}},function(t,e,n){var r=n(63).f,i=n(62),o=n(1)("toStringTag");t.exports=function(t,e,n){t&&!i(t=n?t:t.prototype,o)&&r(t,o,{configurable:!0,value:e})}},function(t,e,n){var r=n(154)("keys"),i=n(109);t.exports=function(t){return r[t]||(r[t]=i(t))}},function(t,e,n){var r=n(148),i=n(11);t.exports=function(t,e,n){if(r(e))throw TypeError("String#"+n+" doesn't accept regex!");return String(i(t))}},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e,n){"use strict";var r=n(337),i=n(20),o=n(46),s=Array.prototype.indexOf,a=Object.prototype.hasOwnProperty,u=Math.abs,c=Math.floor;t.exports=function(t){var e,n,l,h;if(!r(t))return s.apply(this,arguments);for(n=i(o(this).length),l=arguments[1],e=l=isNaN(l)?0:l>=0?c(l):i(this.length)-c(u(l));e<n;++e)if(a.call(this,e)&&(h=this[e],r(h)))return e;return-1}},function(t,e,n){"use strict";t.exports=n(328)()?Array.from:n(329)},function(t,e){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(t){return"function"==typeof t}function i(t){return"object"==typeof t&&null!==t}function o(t){return void 0===t}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,n,s,a,u,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var l=new Error('Uncaught, unspecified "error" event. ('+e+")");throw l.context=e,l}if(o(n=this._events[t]))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(i(n))for(a=Array.prototype.slice.call(arguments,1),s=(c=n.slice()).length,u=0;u<s;u++)c[u].apply(this,a);return!0},n.prototype.addListener=function(t,e){var s;if(!r(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,r(e.listener)?e.listener:e),this._events[t]?i(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,i(this._events[t])&&!this._events[t].warned&&(s=o(this._maxListeners)?n.defaultMaxListeners:this._maxListeners)&&s>0&&this._events[t].length>s&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){if(!r(e))throw TypeError("listener must be a function");var n=!1;function i(){this.removeListener(t,i),n||(n=!0,e.apply(this,arguments))}return i.listener=e,this.on(t,i),this},n.prototype.removeListener=function(t,e){var n,o,s,a;if(!r(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(s=(n=this._events[t]).length,o=-1,n===e||r(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(i(n)){for(a=s;a-- >0;)if(n[a]===e||n[a].listener&&n[a].listener===e){o=a;break}if(o<0)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r(n=this._events[t]))this.removeListener(t,n);else if(n)for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){return this._events&&this._events[t]?r(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(r(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,n){"use strict";var r=n(34);t.exports=new r({explicit:[n(380),n(378),n(373)]})},function(t,e,n){var r=n(35)(n(7),"Map");t.exports=r},function(t,e,n){var r=n(451),i=n(452),o=n(453),s=n(454),a=n(455);function u(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}u.prototype.clear=r,u.prototype.delete=i,u.prototype.get=o,u.prototype.has=s,u.prototype.set=a,t.exports=u},function(t,e,n){var r=n(408),i=n(409),o=n(481),s=n(8),a=n(482);t.exports=function(t){return"function"==typeof t?t:null==t?o:"object"==typeof t?s(t)?i(t[0],t[1]):r(t):a(t)}},function(t,e){var n=9007199254740991,r=/^(?:0|[1-9]\d*)$/;t.exports=function(t,e){var i=typeof t;return!!(e=null==e?n:e)&&("number"==i||"symbol"!=i&&r.test(t))&&t>-1&&t%1==0&&t<e}},function(t,e,n){var r=n(8),i=n(79),o=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,s=/^\w*$/;t.exports=function(t,e){if(r(t))return!1;var n=typeof t;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=t&&!i(t))||s.test(t)||!o.test(t)||null!=e&&t in Object(e)}},function(t,e){var n=9007199254740991;t.exports=function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=n}},function(t,e,n){"use strict";(function(e,n){var r,i;r=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t},i=function(t){var e,n,i=document.createTextNode(""),o=0;return new t(function(){var t;if(e)n&&(e=n.concat(e));else{if(!n)return;e=n}if(n=e,e=null,"function"==typeof n)return t=n,n=null,void t();for(i.data=o=++o%2;n;)t=n.shift(),n.length||(n=null),t()}).observe(i,{characterData:!0}),function(t){r(t),e?"function"==typeof e?e=[e,t]:e.push(t):(e=t,i.data=o=++o%2)}},t.exports=function(){if("object"==typeof e&&e&&"function"==typeof e.nextTick)return e.nextTick;if("object"==typeof document&&document){if("function"==typeof MutationObserver)return i(MutationObserver);if("function"==typeof WebKitMutationObserver)return i(WebKitMutationObserver)}return"function"==typeof n?function(t){n(r(t))}:"function"==typeof setTimeout||"object"==typeof setTimeout?function(t){setTimeout(r(t),0)}:null}()}).call(e,n(36),n(203).setImmediate)},function(t,e,n){"use strict";(function(e,r,i){var o=n(82);function s(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,n){var r=t.entry;t.entry=null;for(;r;){var i=r.callback;e.pendingcb--,i(n),r=r.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}(e,t)}}t.exports=g;var a,u=!e.browser&&["v0.10","v0.9."].indexOf(e.version.slice(0,5))>-1?r:o.nextTick;g.WritableState=y;var c=n(45);c.inherits=n(32);var l={deprecate:n(535)},h=n(201),f=n(84).Buffer,p=i.Uint8Array||function(){};var d,m=n(200);function v(){}function y(t,e){a=a||n(23),t=t||{};var r=e instanceof a;this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var i=t.highWaterMark,c=t.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:r&&(c||0===c)?c:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var h=!1===t.decodeStrings;this.decodeStrings=!h,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var n=t._writableState,r=n.sync,i=n.writecb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(n),e)!function(t,e,n,r,i){--e.pendingcb,n?(o.nextTick(i,r),o.nextTick(_,t,e),t._writableState.errorEmitted=!0,t.emit("error",r)):(i(r),t._writableState.errorEmitted=!0,t.emit("error",r),_(t,e))}(t,n,r,e,i);else{var s=E(n);s||n.corked||n.bufferProcessing||!n.bufferedRequest||D(t,n),r?u(b,t,n,s,i):b(t,n,s,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new s(this)}function g(t){if(a=a||n(23),!(d.call(g,this)||this instanceof a))return new g(t);this._writableState=new y(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),h.call(this)}function x(t,e,n,r,i,o,s){e.writelen=r,e.writecb=s,e.writing=!0,e.sync=!0,n?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function b(t,e,n,r){n||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,r(),_(t,e)}function D(t,e){e.bufferProcessing=!0;var n=e.bufferedRequest;if(t._writev&&n&&n.next){var r=e.bufferedRequestCount,i=new Array(r),o=e.corkedRequestsFree;o.entry=n;for(var a=0,u=!0;n;)i[a]=n,n.isBuf||(u=!1),n=n.next,a+=1;i.allBuffers=u,x(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new s(e),e.bufferedRequestCount=0}else{for(;n;){var c=n.chunk,l=n.encoding,h=n.callback;if(x(t,e,!1,e.objectMode?1:c.length,c,l,h),n=n.next,e.bufferedRequestCount--,e.writing)break}null===n&&(e.lastBufferedRequest=null)}e.bufferedRequest=n,e.bufferProcessing=!1}function E(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function w(t,e){t._final(function(n){e.pendingcb--,n&&t.emit("error",n),e.prefinished=!0,t.emit("prefinish"),_(t,e)})}function _(t,e){var n=E(e);return n&&(!function(t,e){e.prefinished||e.finalCalled||("function"==typeof t._final?(e.pendingcb++,e.finalCalled=!0,o.nextTick(w,t,e)):(e.prefinished=!0,t.emit("prefinish")))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"))),n}c.inherits(g,h),y.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(y.prototype,"buffer",{get:l.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(d=Function.prototype[Symbol.hasInstance],Object.defineProperty(g,Symbol.hasInstance,{value:function(t){return!!d.call(this,t)||this===g&&(t&&t._writableState instanceof y)}})):d=function(t){return t instanceof this},g.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},g.prototype.write=function(t,e,n){var r,i=this._writableState,s=!1,a=!i.objectMode&&(r=t,f.isBuffer(r)||r instanceof p);return a&&!f.isBuffer(t)&&(t=function(t){return f.from(t)}(t)),"function"==typeof e&&(n=e,e=null),a?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof n&&(n=v),i.ended?function(t,e){var n=new Error("write after end");t.emit("error",n),o.nextTick(e,n)}(this,n):(a||function(t,e,n,r){var i=!0,s=!1;return null===n?s=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||e.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(t.emit("error",s),o.nextTick(r,s),i=!1),i}(this,i,t,n))&&(i.pendingcb++,s=function(t,e,n,r,i,o){if(!n){var s=function(t,e,n){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=f.from(e,n));return e}(e,r,i);r!==s&&(n=!0,i="buffer",r=s)}var a=e.objectMode?1:r.length;e.length+=a;var u=e.length<e.highWaterMark;u||(e.needDrain=!0);if(e.writing||e.corked){var c=e.lastBufferedRequest;e.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:o,next:null},c?c.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else x(t,e,!1,a,r,i,o);return u}(this,i,a,t,e,n)),s},g.prototype.cork=function(){this._writableState.corked++},g.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||D(this,t))},g.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(g.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),g.prototype._write=function(t,e,n){n(new Error("_write() is not implemented"))},g.prototype._writev=null,g.prototype.end=function(t,e,n){var r=this._writableState;"function"==typeof t?(n=t,t=null,e=null):"function"==typeof e&&(n=e,e=null),null!==t&&void 0!==t&&this.write(t,e),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||function(t,e,n){e.ending=!0,_(t,e),n&&(e.finished?o.nextTick(n):t.once("finish",n));e.ended=!0,t.writable=!1}(this,r,n)},Object.defineProperty(g.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),g.prototype.destroy=m.destroy,g.prototype._undestroy=m.undestroy,g.prototype._destroy=function(t,e){this.end(),e(t)}}).call(e,n(36),n(203).setImmediate,n(13))},function(t,e,n){(e=t.exports=n(198)).Stream=e,e.Readable=e,e.Writable=n(121),e.Duplex=n(23),e.Transform=n(199),e.PassThrough=n(525)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.loaded=e.TOGGLE_CONFIGS=e.UPDATE_CONFIGS=void 0;var r,i=n(131),o=(r=i)&&r.__esModule?r:{default:r};e.update=function(t,e){return{type:s,payload:(0,o.default)({},t,e)}},e.toggle=function(t){return{type:a,payload:t}};var s=e.UPDATE_CONFIGS="configs_update",a=e.TOGGLE_CONFIGS="configs_toggle";e.loaded=function(){return function(){}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseYamlConfig=void 0;var r,i=n(361),o=(r=i)&&r.__esModule?r:{default:r};e.parseYamlConfig=function(t,e){try{return o.default.safeLoad(t)}catch(t){return e&&e.errActions.newThrownErr(new Error(t)),{}}}},function(t,e,n){"use strict";(function(t){Object.defineProperty(e,"__esModule",{value:!0}),e.getCommonExtensions=e.getExtensions=e.escapeDeepLinkPath=e.createDeepLinkPath=e.shallowEqualKeys=e.buildFormData=e.sorters=e.btoa=e.serializeSearch=e.parseSearch=e.getSampleSchema=e.validateParam=e.validatePattern=e.validateMinLength=e.validateMaxLength=e.validateGuid=e.validateDateTime=e.validateString=e.validateBoolean=e.validateFile=e.validateInteger=e.validateNumber=e.validateMinimum=e.validateMaximum=e.propChecker=e.memoize=e.isImmutable=void 0;var r=b(n(217)),i=b(n(224)),o=b(n(85)),s=b(n(218)),a=b(n(220)),u=b(n(86));e.isJSONObject=function(t){try{var e=JSON.parse(t);if(e&&"object"===(void 0===e?"undefined":(0,u.default)(e)))return e}catch(t){}return!1},e.objectify=function(t){return _(t)?E(t)?t.toObject():t:{}},e.arrayify=function(t){return t?t.toArray?t.toArray():w(t):[]},e.fromJSOrdered=function t(e){if(E(e))return e;if(e instanceof g.default.File)return e;return _(e)?Array.isArray(e)?c.default.Seq(e).map(t).toList():c.default.OrderedMap(e).map(t):e},e.bindToState=function(t,e){var n={};return(0,a.default)(t).filter(function(e){return"function"==typeof t[e]}).forEach(function(r){return n[r]=t[r].bind(null,e)}),n},e.normalizeArray=w,e.isFn=function(t){return"function"==typeof t},e.isObject=_,e.isFunc=function(t){return"function"==typeof t},e.isArray=function(t){return Array.isArray(t)},e.objMap=function(t,e){return(0,a.default)(t).reduce(function(n,r){return n[r]=e(t[r],r),n},{})},e.objReduce=function(t,e){return(0,a.default)(t).reduce(function(n,r){var i=e(t[r],r);return i&&"object"===(void 0===i?"undefined":(0,u.default)(i))&&(0,s.default)(n,i),n},{})},e.systemThunkMiddleware=function(t){return function(e){e.dispatch,e.getState;return function(e){return function(n){return"function"==typeof n?n(t()):e(n)}}}},e.defaultStatusCode=function(t){var e=t.keySeq();return e.contains(D)?D:e.filter(function(t){return"2"===(t+"")[0]}).sort().first()},e.getList=function(t,e){if(!c.default.Iterable.isIterable(t))return c.default.List();var n=t.getIn(Array.isArray(e)?e:[e]);return c.default.List.isList(n)?n:c.default.List()},e.highlight=function(t){var e=document;if(!t)return"";if(t.textContent.length>5e3)return t.textContent;return function(t){for(var n,r,i,o,s,a=t.textContent,u=0,c=a[0],l=1,h=t.innerHTML="",f=0;r=n,n=f<7&&"\\"==n?1:l;){if(l=c,c=a[++u],o=h.length>1,!l||f>8&&"\n"==l||[/\S/.test(l),1,1,!/[$\w]/.test(l),("/"==n||"\n"==n)&&o,'"'==n&&o,"'"==n&&o,a[u-4]+r+n=="--\x3e",r+n=="*/"][f])for(h&&(t.appendChild(s=e.createElement("span")).setAttribute("style",["color: #555; font-weight: bold;","","","color: #555;",""][f?f<3?2:f>6?4:f>3?3:+/^(a(bstract|lias|nd|rguments|rray|s(m|sert)?|uto)|b(ase|egin|ool(ean)?|reak|yte)|c(ase|atch|har|hecked|lass|lone|ompl|onst|ontinue)|de(bugger|cimal|clare|f(ault|er)?|init|l(egate|ete)?)|do|double|e(cho|ls?if|lse(if)?|nd|nsure|num|vent|x(cept|ec|p(licit|ort)|te(nds|nsion|rn)))|f(allthrough|alse|inal(ly)?|ixed|loat|or(each)?|riend|rom|unc(tion)?)|global|goto|guard|i(f|mp(lements|licit|ort)|n(it|clude(_once)?|line|out|stanceof|t(erface|ernal)?)?|s)|l(ambda|et|ock|ong)|m(icrolight|odule|utable)|NaN|n(amespace|ative|ext|ew|il|ot|ull)|o(bject|perator|r|ut|verride)|p(ackage|arams|rivate|rotected|rotocol|ublic)|r(aise|e(adonly|do|f|gister|peat|quire(_once)?|scue|strict|try|turn))|s(byte|ealed|elf|hort|igned|izeof|tatic|tring|truct|ubscript|uper|ynchronized|witch)|t(emplate|hen|his|hrows?|ransient|rue|ry|ype(alias|def|id|name|of))|u(n(checked|def(ined)?|ion|less|signed|til)|se|sing)|v(ar|irtual|oid|olatile)|w(char_t|hen|here|hile|ith)|xor|yield)$/.test(h):0]),s.appendChild(e.createTextNode(h))),i=f&&f<7?f:i,h="",f=11;![1,/[\/{}[(\-+*=<>:;|\\.,?!&@~]/.test(l),/[\])]/.test(l),/[$\w]/.test(l),"/"==l&&i<2&&"<"!=n,'"'==l,"'"==l,l+c+a[u+1]+a[u+2]=="\x3c!--",l+c=="/*",l+c=="//","#"==l][--f];);h+=l}}(t)},e.mapToList=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"key";var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:c.default.Map();if(!c.default.Map.isMap(e)||!e.size)return c.default.List();Array.isArray(n)||(n=[n]);if(n.length<1)return e.merge(r);var s=c.default.List();var a=n[0];var u=!0;var l=!1;var h=void 0;try{for(var f,p=(0,o.default)(e.entries());!(u=(f=p.next()).done);u=!0){var d=f.value,m=(0,i.default)(d,2),v=m[0],y=m[1],g=t(y,n.slice(1),r.set(a,v));s=c.default.List.isList(g)?s.concat(g):s.push(g)}}catch(t){l=!0,h=t}finally{try{!u&&p.return&&p.return()}finally{if(l)throw h}}return s},e.extractFileNameFromContentDispositionHeader=function(t){var e=/filename="([^;]*);?"/i.exec(t);null===e&&(e=/filename=([^;]*);?/i.exec(t));if(null!==e&&e.length>1)return e[1];return null},e.pascalCase=S,e.pascalCaseFilename=function(t){return S(t.replace(/\.[^./]*$/,""))},e.sanitizeUrl=function(t){if("string"!=typeof t||""===t)return"";return(0,l.sanitizeUrl)(t)},e.getAcceptControllingResponse=function(t){if(!c.default.OrderedMap.isOrderedMap(t))return null;if(!t.size)return null;var e=t.find(function(t,e){return e.startsWith("2")&&(0,a.default)(t.get("content")||{}).length>0}),n=t.get("default")||c.default.OrderedMap(),r=(n.get("content")||c.default.OrderedMap()).keySeq().toJS().length?n:null;return e||r},e.deeplyStripKey=function t(e,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0};if("object"!==(void 0===e?"undefined":(0,u.default)(e))||Array.isArray(e)||!n)return e;var i=(0,s.default)({},e);(0,a.default)(i).forEach(function(e){e===n&&r(i[e],e)?delete i[e]:i[e]=t(i[e],n,r)});return i};var c=b(n(167)),l=n(207),h=b(n(474)),f=b(n(188)),p=b(n(187)),d=b(n(477)),m=b(n(483)),v=b(n(77)),y=n(212),g=b(n(126)),x=b(n(327));function b(t){return t&&t.__esModule?t:{default:t}}var D="default",E=e.isImmutable=function(t){return c.default.Iterable.isIterable(t)};function w(t){return Array.isArray(t)?t:[t]}function _(t){return!!t&&"object"===(void 0===t?"undefined":(0,u.default)(t))}e.memoize=p.default;function S(t){return(0,f.default)((0,h.default)(t))}e.propChecker=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];return(0,a.default)(t).length!==(0,a.default)(e).length||((0,m.default)(t,function(t,n){if(r.includes(n))return!1;var i=e[n];return c.default.Iterable.isIterable(t)?!c.default.is(t,i):("object"!==(void 0===t?"undefined":(0,u.default)(t))||"object"!==(void 0===i?"undefined":(0,u.default)(i)))&&t!==i})||n.some(function(n){return!(0,v.default)(t[n],e[n])}))};var A=e.validateMaximum=function(t,e){if(t>e)return"Value must be less than Maximum"},C=e.validateMinimum=function(t,e){if(t<e)return"Value must be greater than Minimum"},k=e.validateNumber=function(t){if(!/^-?\d+(\.?\d+)?$/.test(t))return"Value must be a number"},F=e.validateInteger=function(t){if(!/^-?\d+$/.test(t))return"Value must be an integer"},T=e.validateFile=function(t){if(t&&!(t instanceof g.default.File))return"Value must be a file"},I=e.validateBoolean=function(t){if("true"!==t&&"false"!==t&&!0!==t&&!1!==t)return"Value must be a boolean"},O=e.validateString=function(t){if(t&&"string"!=typeof t)return"Value must be a string"},M=e.validateDateTime=function(t){if(isNaN(Date.parse(t)))return"Value must be a DateTime"},B=e.validateGuid=function(t){if(t=t.toString().toLowerCase(),!/^[{(]?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[)}]?$/.test(t))return"Value must be a Guid"},P=e.validateMaxLength=function(t,e){if(t.length>e)return"Value must be less than MaxLength"},j=e.validateMinLength=function(t,e){if(t.length<e)return"Value must be greater than MinLength"},N=e.validatePattern=function(t,e){if(!new RegExp(e).test(t))return"Value must follow pattern "+e};e.validateParam=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=[],i=e&&"body"===t.get("in")?t.get("value_xml"):t.get("value"),o=t.get("required"),s=n?t.get("schema"):t;if(!s)return r;var a=s.get("maximum"),l=s.get("minimum"),h=s.get("type"),f=s.get("format"),p=s.get("maxLength"),d=s.get("minLength"),m=s.get("pattern");if(h&&(o||i)){var v="string"===h&&i,y="array"===h&&Array.isArray(i)&&i.length,x="array"===h&&c.default.List.isList(i)&&i.count(),b="file"===h&&i instanceof g.default.File,D="boolean"===h&&(i||!1===i),E="number"===h&&(i||0===i),w="integer"===h&&(i||0===i),_=!1;if(n&&"object"===h)if("object"===(void 0===i?"undefined":(0,u.default)(i)))_=!0;else if("string"==typeof i)try{JSON.parse(i),_=!0}catch(t){return r.push("Parameter string value must be valid JSON"),r}var S=[v,y,x,b,D,E,w,_].some(function(t){return!!t});if(o&&!S)return r.push("Required field is not provided"),r;if(m){var L=N(i,m);L&&r.push(L)}if(p||0===p){var R=P(i,p);R&&r.push(R)}if(d){var z=j(i,d);z&&r.push(z)}if(a||0===a){var U=A(i,a);U&&r.push(U)}if(l||0===l){var J=C(i,l);J&&r.push(J)}if("string"===h){var X=void 0;if(!(X="date-time"===f?M(i):"uuid"===f?B(i):O(i)))return r;r.push(X)}else if("boolean"===h){var q=I(i);if(!q)return r;r.push(q)}else if("number"===h){var K=k(i);if(!K)return r;r.push(K)}else if("integer"===h){var W=F(i);if(!W)return r;r.push(W)}else if("array"===h){var Y;if(!x||!i.count())return r;Y=s.getIn(["items","type"]),i.forEach(function(t,e){var n=void 0;"number"===Y?n=k(t):"integer"===Y?n=F(t):"string"===Y&&(n=O(t)),n&&r.push({index:e,error:n})})}else if("file"===h){var H=T(i);if(!H)return r;r.push(H)}}return r},e.getSampleSchema=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(/xml/.test(e)){if(!t.xml||!t.xml.name){if(t.xml=t.xml||{},!t.$$ref)return t.type||t.items||t.properties||t.additionalProperties?'<?xml version="1.0" encoding="UTF-8"?>\n\x3c!-- XML example cannot be generated --\x3e':null;var i=t.$$ref.match(/\S*\/(\S+)$/);t.xml.name=i[1]}return(0,y.memoizedCreateXMLExample)(t,n)}return(0,r.default)((0,y.memoizedSampleFromSchema)(t,n),null,2)},e.parseSearch=function(){var t={},e=g.default.location.search;if(!e)return{};if(""!=e){var n=e.substr(1).split("&");for(var r in n)n.hasOwnProperty(r)&&(r=n[r].split("="),t[decodeURIComponent(r[0])]=r[1]&&decodeURIComponent(r[1])||"")}return t},e.serializeSearch=function(t){return(0,a.default)(t).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t[e])}).join("&")},e.btoa=function(e){return(e instanceof t?e:new t(e.toString(),"utf-8")).toString("base64")},e.sorters={operationsSorter:{alpha:function(t,e){return t.get("path").localeCompare(e.get("path"))},method:function(t,e){return t.get("method").localeCompare(e.get("method"))}},tagsSorter:{alpha:function(t,e){return t.localeCompare(e)}}},e.buildFormData=function(t){var e=[];for(var n in t){var r=t[n];void 0!==r&&""!==r&&e.push([n,"=",encodeURIComponent(r).replace(/%20/g,"+")].join(""))}return e.join("&")},e.shallowEqualKeys=function(t,e,n){return!!(0,d.default)(n,function(n){return(0,v.default)(t[n],e[n])})};var L=e.createDeepLinkPath=function(t){return"string"==typeof t||t instanceof String?t.trim().replace(/\s/g,"_"):""};e.escapeDeepLinkPath=function(t){return(0,x.default)(L(t))},e.getExtensions=function(t){return t.filter(function(t,e){return/^x-/.test(e)})},e.getCommonExtensions=function(t){return t.filter(function(t,e){return/^pattern|maxLength|minLength|maximum|minimum/.test(e)})}}).call(e,n(81).Buffer)},function(t,e,n){"use strict";var r,i=n(85),o=(r=i)&&r.__esModule?r:{default:r};t.exports=function(){var t={location:{},history:{},open:function(){},close:function(){},File:function(){}};if("undefined"==typeof window)return t;try{t=window;var e=!0,n=!1,r=void 0;try{for(var i,s=(0,o.default)(["File","Blob","FormData"]);!(e=(i=s.next()).done);e=!0){var a=i.value;a in window&&(t[a]=window[a])}}catch(t){n=!0,r=t}finally{try{!e&&s.return&&s.return()}finally{if(n)throw r}}}catch(t){console.error(t)}return t}()},function(t,e,n){t.exports={default:n(233),__esModule:!0}},function(t,e,n){t.exports={default:n(234),__esModule:!0}},function(t,e,n){"use strict";e.__esModule=!0,e.default=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}},function(t,e,n){"use strict";e.__esModule=!0;var r,i=n(127),o=(r=i)&&r.__esModule?r:{default:r};e.default=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),(0,o.default)(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}()},function(t,e,n){"use strict";e.__esModule=!0;var r,i=n(127),o=(r=i)&&r.__esModule?r:{default:r};e.default=function(t,e,n){return e in t?(0,o.default)(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}},function(t,e,n){"use strict";e.__esModule=!0;var r=s(n(221)),i=s(n(219)),o=s(n(86));function s(t){return t&&t.__esModule?t:{default:t}}e.default=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+(void 0===e?"undefined":(0,o.default)(e)));t.prototype=(0,i.default)(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(r.default?(0,r.default)(t,e):t.__proto__=e)}},function(t,e,n){"use strict";e.__esModule=!0;var r,i=n(86),o=(r=i)&&r.__esModule?r:{default:r};e.default=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!==(void 0===e?"undefined":(0,o.default)(e))&&"function"!=typeof e?t:e}},function(t,e,n){var r=n(87),i=n(6)("toStringTag"),o="Arguments"==r(function(){return arguments}());t.exports=function(t){var e,n,s;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=Object(t),i))?n:o?r(e):"Object"==(s=r(e))&&"function"==typeof e.callee?"Arguments":s}},function(t,e,n){var r=n(239);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)}}return function(){return t.apply(e,arguments)}}},function(t,e,n){var r=n(27),i=n(9).document,o=r(i)&&r(i.createElement);t.exports=function(t){return o?i.createElement(t):{}}},function(t,e,n){t.exports=!n(14)&&!n(25)(function(){return 7!=Object.defineProperty(n(136)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(87);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e,n){"use strict";var r=n(54),i=n(15),o=n(145),s=n(26),a=n(38),u=n(245),c=n(92),l=n(142),h=n(6)("iterator"),f=!([].keys&&"next"in[].keys()),p=function(){return this};t.exports=function(t,e,n,d,m,v,y){u(n,e,d);var g,x,b,D=function(t){if(!f&&t in S)return S[t];switch(t){case"keys":case"values":return function(){return new n(this,t)}}return function(){return new n(this,t)}},E=e+" Iterator",w="values"==m,_=!1,S=t.prototype,A=S[h]||S["@@iterator"]||m&&S[m],C=A||D(m),k=m?w?D("entries"):C:void 0,F="Array"==e&&S.entries||A;if(F&&(b=l(F.call(new t)))!==Object.prototype&&b.next&&(c(b,E,!0),r||"function"==typeof b[h]||s(b,h,p)),w&&A&&"values"!==A.name&&(_=!0,C=function(){return A.call(this)}),r&&!y||!f&&!_&&S[h]||s(S,h,C),a[e]=C,a[E]=p,m)if(g={values:w?C:D("values"),keys:v?C:D("keys"),entries:k},y)for(x in g)x in S||o(S,x,g[x]);else i(i.P+i.F*(f||_),e,g);return g}},function(t,e,n){var r=n(55),i=n(56),o=n(28),s=n(96),a=n(16),u=n(137),c=Object.getOwnPropertyDescriptor;e.f=n(14)?c:function(t,e){if(t=o(t),e=s(e,!0),u)try{return c(t,e)}catch(t){}if(a(t,e))return i(!r.f.call(t,e),t[e])}},function(t,e,n){var r=n(143),i=n(89).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,i)}},function(t,e,n){var r=n(16),i=n(57),o=n(93)("IE_PROTO"),s=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=i(t),r(t,o)?t[o]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?s:null}},function(t,e,n){var r=n(16),i=n(28),o=n(241)(!1),s=n(93)("IE_PROTO");t.exports=function(t,e){var n,a=i(t),u=0,c=[];for(n in a)n!=s&&r(a,n)&&c.push(n);for(;e.length>u;)r(a,n=e[u++])&&(~o(c,n)||c.push(n));return c}},function(t,e,n){var r=n(15),i=n(2),o=n(25);t.exports=function(t,e){var n=(i.Object||{})[t]||Object[t],s={};s[t]=e(n),r(r.S+r.F*o(function(){n(1)}),"Object",s)}},function(t,e,n){t.exports=n(26)},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,n){var r=n(4).document;t.exports=r&&r.documentElement},function(t,e,n){var r=n(29),i=n(40),o=n(1)("match");t.exports=function(t){var e;return r(t)&&(void 0!==(e=t[o])?!!e:"RegExp"==i(t))}},function(t,e,n){"use strict";var r=n(104),i=n(3),o=n(30),s=n(19),a=n(43),u=n(278),c=n(106),l=n(284),h=n(1)("iterator"),f=!([].keys&&"next"in[].keys()),p=function(){return this};t.exports=function(t,e,n,d,m,v,y){u(n,e,d);var g,x,b,D=function(t){if(!f&&t in S)return S[t];switch(t){case"keys":case"values":return function(){return new n(this,t)}}return function(){return new n(this,t)}},E=e+" Iterator",w="values"==m,_=!1,S=t.prototype,A=S[h]||S["@@iterator"]||m&&S[m],C=A||D(m),k=m?w?D("entries"):C:void 0,F="Array"==e&&S.entries||A;if(F&&(b=l(F.call(new t)))!==Object.prototype&&b.next&&(c(b,E,!0),r||"function"==typeof b[h]||s(b,h,p)),w&&A&&"values"!==A.name&&(_=!0,C=function(){return A.call(this)}),r&&!y||!f&&!_&&S[h]||s(S,h,C),a[e]=C,a[E]=p,m)if(g={values:w?C:D("values"),keys:v?C:D("keys"),entries:k},y)for(x in g)x in S||o(S,x,g[x]);else i(i.P+i.F*(f||_),e,g);return g}},function(t,e,n){var r=n(285),i=n(146);t.exports=Object.keys||function(t){return r(t,i)}},function(t,e){t.exports=function(t){try{return{e:!1,v:t()}}catch(t){return{e:!0,v:t}}}},function(t,e,n){var r=n(18),i=n(29),o=n(105);t.exports=function(t,e){if(r(t),i(e)&&e.constructor===t)return e;var n=o.f(t);return(0,n.resolve)(e),n.promise}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var r=n(10),i=n(4),o=i["__core-js_shared__"]||(i["__core-js_shared__"]={});(t.exports=function(t,e){return o[t]||(o[t]=void 0!==e?e:{})})("versions",[]).push({version:r.version,mode:n(104)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"})},function(t,e,n){var r=n(18),i=n(59),o=n(1)("species");t.exports=function(t,e){var n,s=r(t).constructor;return void 0===s||void 0==(n=r(s)[o])?e:i(n)}},function(t,e,n){var r=n(64),i=n(11);t.exports=function(t){return function(e,n){var o,s,a=String(i(e)),u=r(n),c=a.length;return u<0||u>=c?t?"":void 0:(o=a.charCodeAt(u))<55296||o>56319||u+1===c||(s=a.charCodeAt(u+1))<56320||s>57343?t?a.charAt(u):o:t?a.slice(u,u+2):s-56320+(o-55296<<10)+65536}}},function(t,e,n){var r,i,o,s=n(60),a=n(274),u=n(147),c=n(102),l=n(4),h=l.process,f=l.setImmediate,p=l.clearImmediate,d=l.MessageChannel,m=l.Dispatch,v=0,y={},g=function(){var t=+this;if(y.hasOwnProperty(t)){var e=y[t];delete y[t],e()}},x=function(t){g.call(t.data)};f&&p||(f=function(t){for(var e=[],n=1;arguments.length>n;)e.push(arguments[n++]);return y[++v]=function(){a("function"==typeof t?t:Function(t),e)},r(v),v},p=function(t){delete y[t]},"process"==n(40)(h)?r=function(t){h.nextTick(s(g,t,1))}:m&&m.now?r=function(t){m.now(s(g,t,1))}:d?(o=(i=new d).port2,i.port1.onmessage=x,r=s(o.postMessage,o,1)):l.addEventListener&&"function"==typeof postMessage&&!l.importScripts?(r=function(t){l.postMessage(t+"","*")},l.addEventListener("message",x,!1)):r="onreadystatechange"in c("script")?function(t){u.appendChild(c("script")).onreadystatechange=function(){u.removeChild(this),g.call(t)}}:function(t){setTimeout(s(g,t,1),0)}),t.exports={set:f,clear:p}},function(t,e,n){var r=n(64),i=Math.max,o=Math.min;t.exports=function(t,e){return(t=r(t))<0?i(t+e,0):o(t,e)}},function(t,e,n){"use strict";var r=n(156)(!0);n(149)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=r(e,n),this._i+=t.length,{value:t,done:!1})})},function(t,e,n){"use strict";var r,i,o,s,a,u=n(20),c=function(t,e){return e};try{Object.defineProperty(c,"length",{configurable:!0,writable:!1,enumerable:!1,value:1})}catch(t){}1===c.length?(r={configurable:!0,writable:!1,enumerable:!1},i=Object.defineProperty,t.exports=function(t,e){return e=u(e),t.length===e?t:(r.value=e,i(t,"length",r))}):(s=n(164),a=[],o=function(t){var e,n=0;if(a[t])return a[t];for(e=[];t--;)e.push("a"+(++n).toString(36));return new Function("fn","return function ("+e.join(", ")+") { return fn.apply(this, arguments); };")},t.exports=function(t,e){var n;if(e=u(e),t.length===e)return t;n=o(e)(t);try{s(n,t)}catch(t){}return n})},function(t,e,n){"use strict";t.exports=function(){}},function(t,e,n){"use strict";t.exports=n(342)()?Object.assign:n(343)},function(t,e,n){"use strict";var r=n(12),i=n(67),o=Function.prototype.call;t.exports=function(t,e){var n={},s=arguments[2];return r(e),i(t,function(t,r,i,a){n[r]=o.call(e,s,t,r,i,a)}),n}},function(t,e,n){"use strict";var r=n(46),i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,a=Object.getOwnPropertySymbols;t.exports=function(t,e){var n,u=Object(r(e));if(t=Object(r(t)),s(u).forEach(function(r){try{i(t,r,o(e,r))}catch(t){n=t}}),"function"==typeof a&&a(u).forEach(function(r){try{i(t,r,o(e,r))}catch(t){n=t}}),void 0!==n)throw n;return t}},function(t,e,n){"use strict";var r=n(31),i=Array.prototype.forEach,o=Object.create;t.exports=function(t){var e=o(null);return i.call(arguments,function(t){r(t)&&function(t,e){var n;for(n in t)e[n]=t[n]}(Object(t),e)}),e}},function(t,e,n){"use strict";var r={};t.exports=r},function(t,e,n){var r;r=function(){"use strict";var t=Array.prototype.slice;function e(t,e){e&&(t.prototype=Object.create(e.prototype)),t.prototype.constructor=t}function n(t){return s(t)?t:W(t)}function r(t){return a(t)?t:Y(t)}function i(t){return u(t)?t:H(t)}function o(t){return s(t)&&!c(t)?t:V(t)}function s(t){return!(!t||!t[h])}function a(t){return!(!t||!t[f])}function u(t){return!(!t||!t[p])}function c(t){return a(t)||u(t)}function l(t){return!(!t||!t[d])}e(r,n),e(i,n),e(o,n),n.isIterable=s,n.isKeyed=a,n.isIndexed=u,n.isAssociative=c,n.isOrdered=l,n.Keyed=r,n.Indexed=i,n.Set=o;var h="@@__IMMUTABLE_ITERABLE__@@",f="@@__IMMUTABLE_KEYED__@@",p="@@__IMMUTABLE_INDEXED__@@",d="@@__IMMUTABLE_ORDERED__@@",m=5,v=1<<m,y=v-1,g={},x={value:!1},b={value:!1};function D(t){return t.value=!1,t}function E(t){t&&(t.value=!0)}function w(){}function _(t,e){e=e||0;for(var n=Math.max(0,t.length-e),r=new Array(n),i=0;i<n;i++)r[i]=t[i+e];return r}function S(t){return void 0===t.size&&(t.size=t.__iterate(C)),t.size}function A(t,e){if("number"!=typeof e){var n=e>>>0;if(""+n!==e||4294967295===n)return NaN;e=n}return e<0?S(t)+e:e}function C(){return!0}function k(t,e,n){return(0===t||void 0!==n&&t<=-n)&&(void 0===e||void 0!==n&&e>=n)}function F(t,e){return I(t,e,0)}function T(t,e){return I(t,e,e)}function I(t,e,n){return void 0===t?n:t<0?Math.max(0,e+t):void 0===e?t:Math.min(e,t)}var O=0,M=1,B=2,P="function"==typeof Symbol&&Symbol.iterator,j="@@iterator",N=P||j;function L(t){this.next=t}function R(t,e,n,r){var i=0===t?e:1===t?n:[e,n];return r?r.value=i:r={value:i,done:!1},r}function z(){return{value:void 0,done:!0}}function U(t){return!!q(t)}function J(t){return t&&"function"==typeof t.next}function X(t){var e=q(t);return e&&e.call(t)}function q(t){var e=t&&(P&&t[P]||t[j]);if("function"==typeof e)return e}function K(t){return t&&"number"==typeof t.length}function W(t){return null===t||void 0===t?ot():s(t)?t.toSeq():function(t){var e=ut(t)||"object"==typeof t&&new et(t);if(!e)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+t);return e}(t)}function Y(t){return null===t||void 0===t?ot().toKeyedSeq():s(t)?a(t)?t.toSeq():t.fromEntrySeq():st(t)}function H(t){return null===t||void 0===t?ot():s(t)?a(t)?t.entrySeq():t.toIndexedSeq():at(t)}function V(t){return(null===t||void 0===t?ot():s(t)?a(t)?t.entrySeq():t:at(t)).toSetSeq()}L.prototype.toString=function(){return"[Iterator]"},L.KEYS=O,L.VALUES=M,L.ENTRIES=B,L.prototype.inspect=L.prototype.toSource=function(){return this.toString()},L.prototype[N]=function(){return this},e(W,n),W.of=function(){return W(arguments)},W.prototype.toSeq=function(){return this},W.prototype.toString=function(){return this.__toString("Seq {","}")},W.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},W.prototype.__iterate=function(t,e){return ct(this,t,e,!0)},W.prototype.__iterator=function(t,e){return lt(this,t,e,!0)},e(Y,W),Y.prototype.toKeyedSeq=function(){return this},e(H,W),H.of=function(){return H(arguments)},H.prototype.toIndexedSeq=function(){return this},H.prototype.toString=function(){return this.__toString("Seq [","]")},H.prototype.__iterate=function(t,e){return ct(this,t,e,!1)},H.prototype.__iterator=function(t,e){return lt(this,t,e,!1)},e(V,W),V.of=function(){return V(arguments)},V.prototype.toSetSeq=function(){return this},W.isSeq=it,W.Keyed=Y,W.Set=V,W.Indexed=H;var G,$,Z,Q="@@__IMMUTABLE_SEQ__@@";function tt(t){this._array=t,this.size=t.length}function et(t){var e=Object.keys(t);this._object=t,this._keys=e,this.size=e.length}function nt(t){this._iterable=t,this.size=t.length||t.size}function rt(t){this._iterator=t,this._iteratorCache=[]}function it(t){return!(!t||!t[Q])}function ot(){return G||(G=new tt([]))}function st(t){var e=Array.isArray(t)?new tt(t).fromEntrySeq():J(t)?new rt(t).fromEntrySeq():U(t)?new nt(t).fromEntrySeq():"object"==typeof t?new et(t):void 0;if(!e)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+t);return e}function at(t){var e=ut(t);if(!e)throw new TypeError("Expected Array or iterable object of values: "+t);return e}function ut(t){return K(t)?new tt(t):J(t)?new rt(t):U(t)?new nt(t):void 0}function ct(t,e,n,r){var i=t._cache;if(i){for(var o=i.length-1,s=0;s<=o;s++){var a=i[n?o-s:s];if(!1===e(a[1],r?a[0]:s,t))return s+1}return s}return t.__iterateUncached(e,n)}function lt(t,e,n,r){var i=t._cache;if(i){var o=i.length-1,s=0;return new L(function(){var t=i[n?o-s:s];return s++>o?{value:void 0,done:!0}:R(e,r?t[0]:s-1,t[1])})}return t.__iteratorUncached(e,n)}function ht(t,e){return e?function t(e,n,r,i){if(Array.isArray(n))return e.call(i,r,H(n).map(function(r,i){return t(e,r,i,n)}));if(pt(n))return e.call(i,r,Y(n).map(function(r,i){return t(e,r,i,n)}));return n}(e,t,"",{"":t}):ft(t)}function ft(t){return Array.isArray(t)?H(t).map(ft).toList():pt(t)?Y(t).map(ft).toMap():t}function pt(t){return t&&(t.constructor===Object||void 0===t.constructor)}function dt(t,e){if(t===e||t!=t&&e!=e)return!0;if(!t||!e)return!1;if("function"==typeof t.valueOf&&"function"==typeof e.valueOf){if((t=t.valueOf())===(e=e.valueOf())||t!=t&&e!=e)return!0;if(!t||!e)return!1}return!("function"!=typeof t.equals||"function"!=typeof e.equals||!t.equals(e))}function mt(t,e){if(t===e)return!0;if(!s(e)||void 0!==t.size&&void 0!==e.size&&t.size!==e.size||void 0!==t.__hash&&void 0!==e.__hash&&t.__hash!==e.__hash||a(t)!==a(e)||u(t)!==u(e)||l(t)!==l(e))return!1;if(0===t.size&&0===e.size)return!0;var n=!c(t);if(l(t)){var r=t.entries();return e.every(function(t,e){var i=r.next().value;return i&&dt(i[1],t)&&(n||dt(i[0],e))})&&r.next().done}var i=!1;if(void 0===t.size)if(void 0===e.size)"function"==typeof t.cacheResult&&t.cacheResult();else{i=!0;var o=t;t=e,e=o}var h=!0,f=e.__iterate(function(e,r){if(n?!t.has(e):i?!dt(e,t.get(r,g)):!dt(t.get(r,g),e))return h=!1,!1});return h&&t.size===f}function vt(t,e){if(!(this instanceof vt))return new vt(t,e);if(this._value=t,this.size=void 0===e?1/0:Math.max(0,e),0===this.size){if($)return $;$=this}}function yt(t,e){if(!t)throw new Error(e)}function gt(t,e,n){if(!(this instanceof gt))return new gt(t,e,n);if(yt(0!==n,"Cannot step a Range by 0"),t=t||0,void 0===e&&(e=1/0),n=void 0===n?1:Math.abs(n),e<t&&(n=-n),this._start=t,this._end=e,this._step=n,this.size=Math.max(0,Math.ceil((e-t)/n-1)+1),0===this.size){if(Z)return Z;Z=this}}function xt(){throw TypeError("Abstract")}function bt(){}function Dt(){}function Et(){}W.prototype[Q]=!0,e(tt,H),tt.prototype.get=function(t,e){return this.has(t)?this._array[A(this,t)]:e},tt.prototype.__iterate=function(t,e){for(var n=this._array,r=n.length-1,i=0;i<=r;i++)if(!1===t(n[e?r-i:i],i,this))return i+1;return i},tt.prototype.__iterator=function(t,e){var n=this._array,r=n.length-1,i=0;return new L(function(){return i>r?{value:void 0,done:!0}:R(t,i,n[e?r-i++:i++])})},e(et,Y),et.prototype.get=function(t,e){return void 0===e||this.has(t)?this._object[t]:e},et.prototype.has=function(t){return this._object.hasOwnProperty(t)},et.prototype.__iterate=function(t,e){for(var n=this._object,r=this._keys,i=r.length-1,o=0;o<=i;o++){var s=r[e?i-o:o];if(!1===t(n[s],s,this))return o+1}return o},et.prototype.__iterator=function(t,e){var n=this._object,r=this._keys,i=r.length-1,o=0;return new L(function(){var s=r[e?i-o:o];return o++>i?{value:void 0,done:!0}:R(t,s,n[s])})},et.prototype[d]=!0,e(nt,H),nt.prototype.__iterateUncached=function(t,e){if(e)return this.cacheResult().__iterate(t,e);var n=X(this._iterable),r=0;if(J(n))for(var i;!(i=n.next()).done&&!1!==t(i.value,r++,this););return r},nt.prototype.__iteratorUncached=function(t,e){if(e)return this.cacheResult().__iterator(t,e);var n=X(this._iterable);if(!J(n))return new L(z);var r=0;return new L(function(){var e=n.next();return e.done?e:R(t,r++,e.value)})},e(rt,H),rt.prototype.__iterateUncached=function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var n,r=this._iterator,i=this._iteratorCache,o=0;o<i.length;)if(!1===t(i[o],o++,this))return o;for(;!(n=r.next()).done;){var s=n.value;if(i[o]=s,!1===t(s,o++,this))break}return o},rt.prototype.__iteratorUncached=function(t,e){if(e)return this.cacheResult().__iterator(t,e);var n=this._iterator,r=this._iteratorCache,i=0;return new L(function(){if(i>=r.length){var e=n.next();if(e.done)return e;r[i]=e.value}return R(t,i,r[i++])})},e(vt,H),vt.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},vt.prototype.get=function(t,e){return this.has(t)?this._value:e},vt.prototype.includes=function(t){return dt(this._value,t)},vt.prototype.slice=function(t,e){var n=this.size;return k(t,e,n)?this:new vt(this._value,T(e,n)-F(t,n))},vt.prototype.reverse=function(){return this},vt.prototype.indexOf=function(t){return dt(this._value,t)?0:-1},vt.prototype.lastIndexOf=function(t){return dt(this._value,t)?this.size:-1},vt.prototype.__iterate=function(t,e){for(var n=0;n<this.size;n++)if(!1===t(this._value,n,this))return n+1;return n},vt.prototype.__iterator=function(t,e){var n=this,r=0;return new L(function(){return r<n.size?R(t,r++,n._value):{value:void 0,done:!0}})},vt.prototype.equals=function(t){return t instanceof vt?dt(this._value,t._value):mt(t)},e(gt,H),gt.prototype.toString=function(){return 0===this.size?"Range []":"Range [ "+this._start+"..."+this._end+(1!==this._step?" by "+this._step:"")+" ]"},gt.prototype.get=function(t,e){return this.has(t)?this._start+A(this,t)*this._step:e},gt.prototype.includes=function(t){var e=(t-this._start)/this._step;return e>=0&&e<this.size&&e===Math.floor(e)},gt.prototype.slice=function(t,e){return k(t,e,this.size)?this:(t=F(t,this.size),(e=T(e,this.size))<=t?new gt(0,0):new gt(this.get(t,this._end),this.get(e,this._end),this._step))},gt.prototype.indexOf=function(t){var e=t-this._start;if(e%this._step==0){var n=e/this._step;if(n>=0&&n<this.size)return n}return-1},gt.prototype.lastIndexOf=function(t){return this.indexOf(t)},gt.prototype.__iterate=function(t,e){for(var n=this.size-1,r=this._step,i=e?this._start+n*r:this._start,o=0;o<=n;o++){if(!1===t(i,o,this))return o+1;i+=e?-r:r}return o},gt.prototype.__iterator=function(t,e){var n=this.size-1,r=this._step,i=e?this._start+n*r:this._start,o=0;return new L(function(){var s=i;return i+=e?-r:r,o>n?{value:void 0,done:!0}:R(t,o++,s)})},gt.prototype.equals=function(t){return t instanceof gt?this._start===t._start&&this._end===t._end&&this._step===t._step:mt(this,t)},e(xt,n),e(bt,xt),e(Dt,xt),e(Et,xt),xt.Keyed=bt,xt.Indexed=Dt,xt.Set=Et;var wt="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function(t,e){var n=65535&(t|=0),r=65535&(e|=0);return n*r+((t>>>16)*r+n*(e>>>16)<<16>>>0)|0};function _t(t){return t>>>1&1073741824|3221225471&t}function St(t){if(!1===t||null===t||void 0===t)return 0;if("function"==typeof t.valueOf&&(!1===(t=t.valueOf())||null===t||void 0===t))return 0;if(!0===t)return 1;var e=typeof t;if("number"===e){if(t!=t||t===1/0)return 0;var n=0|t;for(n!==t&&(n^=4294967295*t);t>4294967295;)n^=t/=4294967295;return _t(n)}if("string"===e)return t.length>Mt?function(t){var e=jt[t];void 0===e&&(e=At(t),Pt===Bt&&(Pt=0,jt={}),Pt++,jt[t]=e);return e}(t):At(t);if("function"==typeof t.hashCode)return t.hashCode();if("object"===e)return function(t){var e;if(Tt&&void 0!==(e=Ft.get(t)))return e;if(void 0!==(e=t[Ot]))return e;if(!kt){if(void 0!==(e=t.propertyIsEnumerable&&t.propertyIsEnumerable[Ot]))return e;if(void 0!==(e=function(t){if(t&&t.nodeType>0)switch(t.nodeType){case 1:return t.uniqueID;case 9:return t.documentElement&&t.documentElement.uniqueID}}(t)))return e}e=++It,1073741824&It&&(It=0);if(Tt)Ft.set(t,e);else{if(void 0!==Ct&&!1===Ct(t))throw new Error("Non-extensible objects are not allowed as keys.");if(kt)Object.defineProperty(t,Ot,{enumerable:!1,configurable:!1,writable:!1,value:e});else if(void 0!==t.propertyIsEnumerable&&t.propertyIsEnumerable===t.constructor.prototype.propertyIsEnumerable)t.propertyIsEnumerable=function(){return this.constructor.prototype.propertyIsEnumerable.apply(this,arguments)},t.propertyIsEnumerable[Ot]=e;else{if(void 0===t.nodeType)throw new Error("Unable to set a non-enumerable property on object.");t[Ot]=e}}return e}(t);if("function"==typeof t.toString)return At(t.toString());throw new Error("Value type "+e+" cannot be hashed.")}function At(t){for(var e=0,n=0;n<t.length;n++)e=31*e+t.charCodeAt(n)|0;return _t(e)}var Ct=Object.isExtensible,kt=function(){try{return Object.defineProperty({},"@",{}),!0}catch(t){return!1}}();var Ft,Tt="function"==typeof WeakMap;Tt&&(Ft=new WeakMap);var It=0,Ot="__immutablehash__";"function"==typeof Symbol&&(Ot=Symbol(Ot));var Mt=16,Bt=255,Pt=0,jt={};function Nt(t){yt(t!==1/0,"Cannot perform this action with an infinite size.")}function Lt(t){return null===t||void 0===t?Zt():Rt(t)&&!l(t)?t:Zt().withMutations(function(e){var n=r(t);Nt(n.size),n.forEach(function(t,n){return e.set(n,t)})})}function Rt(t){return!(!t||!t[Ut])}e(Lt,bt),Lt.of=function(){var e=t.call(arguments,0);return Zt().withMutations(function(t){for(var n=0;n<e.length;n+=2){if(n+1>=e.length)throw new Error("Missing value for key: "+e[n]);t.set(e[n],e[n+1])}})},Lt.prototype.toString=function(){return this.__toString("Map {","}")},Lt.prototype.get=function(t,e){return this._root?this._root.get(0,void 0,t,e):e},Lt.prototype.set=function(t,e){return Qt(this,t,e)},Lt.prototype.setIn=function(t,e){return this.updateIn(t,g,function(){return e})},Lt.prototype.remove=function(t){return Qt(this,t,g)},Lt.prototype.deleteIn=function(t){return this.updateIn(t,function(){return g})},Lt.prototype.update=function(t,e,n){return 1===arguments.length?t(this):this.updateIn([t],e,n)},Lt.prototype.updateIn=function(t,e,n){n||(n=e,e=void 0);var r=function t(e,n,r,i){var o=e===g;var s=n.next();if(s.done){var a=o?r:e,u=i(a);return u===a?e:u}yt(o||e&&e.set,"invalid keyPath");var c=s.value;var l=o?g:e.get(c,g);var h=t(l,n,r,i);return h===l?e:h===g?e.remove(c):(o?Zt():e).set(c,h)}(this,nn(t),e,n);return r===g?void 0:r},Lt.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):Zt()},Lt.prototype.merge=function(){return re(this,void 0,arguments)},Lt.prototype.mergeWith=function(e){return re(this,e,t.call(arguments,1))},Lt.prototype.mergeIn=function(e){var n=t.call(arguments,1);return this.updateIn(e,Zt(),function(t){return"function"==typeof t.merge?t.merge.apply(t,n):n[n.length-1]})},Lt.prototype.mergeDeep=function(){return re(this,ie,arguments)},Lt.prototype.mergeDeepWith=function(e){var n=t.call(arguments,1);return re(this,oe(e),n)},Lt.prototype.mergeDeepIn=function(e){var n=t.call(arguments,1);return this.updateIn(e,Zt(),function(t){return"function"==typeof t.mergeDeep?t.mergeDeep.apply(t,n):n[n.length-1]})},Lt.prototype.sort=function(t){return Fe(Ke(this,t))},Lt.prototype.sortBy=function(t,e){return Fe(Ke(this,e,t))},Lt.prototype.withMutations=function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},Lt.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new w)},Lt.prototype.asImmutable=function(){return this.__ensureOwner()},Lt.prototype.wasAltered=function(){return this.__altered},Lt.prototype.__iterator=function(t,e){return new Ht(this,t,e)},Lt.prototype.__iterate=function(t,e){var n=this,r=0;return this._root&&this._root.iterate(function(e){return r++,t(e[1],e[0],n)},e),r},Lt.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?$t(this.size,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},Lt.isMap=Rt;var zt,Ut="@@__IMMUTABLE_MAP__@@",Jt=Lt.prototype;function Xt(t,e){this.ownerID=t,this.entries=e}function qt(t,e,n){this.ownerID=t,this.bitmap=e,this.nodes=n}function Kt(t,e,n){this.ownerID=t,this.count=e,this.nodes=n}function Wt(t,e,n){this.ownerID=t,this.keyHash=e,this.entries=n}function Yt(t,e,n){this.ownerID=t,this.keyHash=e,this.entry=n}function Ht(t,e,n){this._type=e,this._reverse=n,this._stack=t._root&&Gt(t._root)}function Vt(t,e){return R(t,e[0],e[1])}function Gt(t,e){return{node:t,index:0,__prev:e}}function $t(t,e,n,r){var i=Object.create(Jt);return i.size=t,i._root=e,i.__ownerID=n,i.__hash=r,i.__altered=!1,i}function Zt(){return zt||(zt=$t(0))}function Qt(t,e,n){var r,i;if(t._root){var o=D(x),s=D(b);if(r=te(t._root,t.__ownerID,0,void 0,e,n,o,s),!s.value)return t;i=t.size+(o.value?n===g?-1:1:0)}else{if(n===g)return t;i=1,r=new Xt(t.__ownerID,[[e,n]])}return t.__ownerID?(t.size=i,t._root=r,t.__hash=void 0,t.__altered=!0,t):r?$t(i,r):Zt()}function te(t,e,n,r,i,o,s,a){return t?t.update(e,n,r,i,o,s,a):o===g?t:(E(a),E(s),new Yt(e,r,[i,o]))}function ee(t){return t.constructor===Yt||t.constructor===Wt}function ne(t,e,n,r,i){if(t.keyHash===r)return new Wt(e,r,[t.entry,i]);var o,s=(0===n?t.keyHash:t.keyHash>>>n)&y,a=(0===n?r:r>>>n)&y;return new qt(e,1<<s|1<<a,s===a?[ne(t,e,n+m,r,i)]:(o=new Yt(e,r,i),s<a?[t,o]:[o,t]))}function re(t,e,n){for(var i=[],o=0;o<n.length;o++){var a=n[o],u=r(a);s(a)||(u=u.map(function(t){return ht(t)})),i.push(u)}return se(t,e,i)}function ie(t,e,n){return t&&t.mergeDeep&&s(e)?t.mergeDeep(e):dt(t,e)?t:e}function oe(t){return function(e,n,r){if(e&&e.mergeDeepWith&&s(n))return e.mergeDeepWith(t,n);var i=t(e,n,r);return dt(e,i)?e:i}}function se(t,e,n){return 0===(n=n.filter(function(t){return 0!==t.size})).length?t:0!==t.size||t.__ownerID||1!==n.length?t.withMutations(function(t){for(var r=e?function(n,r){t.update(r,g,function(t){return t===g?n:e(t,n,r)})}:function(e,n){t.set(n,e)},i=0;i<n.length;i++)n[i].forEach(r)}):t.constructor(n[0])}function ae(t){return t=(t=(858993459&(t-=t>>1&1431655765))+(t>>2&858993459))+(t>>4)&252645135,t+=t>>8,127&(t+=t>>16)}function ue(t,e,n,r){var i=r?t:_(t);return i[e]=n,i}Jt[Ut]=!0,Jt.delete=Jt.remove,Jt.removeIn=Jt.deleteIn,Xt.prototype.get=function(t,e,n,r){for(var i=this.entries,o=0,s=i.length;o<s;o++)if(dt(n,i[o][0]))return i[o][1];return r},Xt.prototype.update=function(t,e,n,r,i,o,s){for(var a=i===g,u=this.entries,c=0,l=u.length;c<l&&!dt(r,u[c][0]);c++);var h=c<l;if(h?u[c][1]===i:a)return this;if(E(s),(a||!h)&&E(o),!a||1!==u.length){if(!h&&!a&&u.length>=ce)return function(t,e,n,r){t||(t=new w);for(var i=new Yt(t,St(n),[n,r]),o=0;o<e.length;o++){var s=e[o];i=i.update(t,0,void 0,s[0],s[1])}return i}(t,u,r,i);var f=t&&t===this.ownerID,p=f?u:_(u);return h?a?c===l-1?p.pop():p[c]=p.pop():p[c]=[r,i]:p.push([r,i]),f?(this.entries=p,this):new Xt(t,p)}},qt.prototype.get=function(t,e,n,r){void 0===e&&(e=St(n));var i=1<<((0===t?e:e>>>t)&y),o=this.bitmap;return 0==(o&i)?r:this.nodes[ae(o&i-1)].get(t+m,e,n,r)},qt.prototype.update=function(t,e,n,r,i,o,s){void 0===n&&(n=St(r));var a=(0===e?n:n>>>e)&y,u=1<<a,c=this.bitmap,l=0!=(c&u);if(!l&&i===g)return this;var h=ae(c&u-1),f=this.nodes,p=l?f[h]:void 0,d=te(p,t,e+m,n,r,i,o,s);if(d===p)return this;if(!l&&d&&f.length>=le)return function(t,e,n,r,i){for(var o=0,s=new Array(v),a=0;0!==n;a++,n>>>=1)s[a]=1&n?e[o++]:void 0;return s[r]=i,new Kt(t,o+1,s)}(t,f,c,a,d);if(l&&!d&&2===f.length&&ee(f[1^h]))return f[1^h];if(l&&d&&1===f.length&&ee(d))return d;var x=t&&t===this.ownerID,b=l?d?c:c^u:c|u,D=l?d?ue(f,h,d,x):function(t,e,n){var r=t.length-1;if(n&&e===r)return t.pop(),t;for(var i=new Array(r),o=0,s=0;s<r;s++)s===e&&(o=1),i[s]=t[s+o];return i}(f,h,x):function(t,e,n,r){var i=t.length+1;if(r&&e+1===i)return t[e]=n,t;for(var o=new Array(i),s=0,a=0;a<i;a++)a===e?(o[a]=n,s=-1):o[a]=t[a+s];return o}(f,h,d,x);return x?(this.bitmap=b,this.nodes=D,this):new qt(t,b,D)},Kt.prototype.get=function(t,e,n,r){void 0===e&&(e=St(n));var i=(0===t?e:e>>>t)&y,o=this.nodes[i];return o?o.get(t+m,e,n,r):r},Kt.prototype.update=function(t,e,n,r,i,o,s){void 0===n&&(n=St(r));var a=(0===e?n:n>>>e)&y,u=i===g,c=this.nodes,l=c[a];if(u&&!l)return this;var h=te(l,t,e+m,n,r,i,o,s);if(h===l)return this;var f=this.count;if(l){if(!h&&--f<he)return function(t,e,n,r){for(var i=0,o=0,s=new Array(n),a=0,u=1,c=e.length;a<c;a++,u<<=1){var l=e[a];void 0!==l&&a!==r&&(i|=u,s[o++]=l)}return new qt(t,i,s)}(t,c,f,a)}else f++;var p=t&&t===this.ownerID,d=ue(c,a,h,p);return p?(this.count=f,this.nodes=d,this):new Kt(t,f,d)},Wt.prototype.get=function(t,e,n,r){for(var i=this.entries,o=0,s=i.length;o<s;o++)if(dt(n,i[o][0]))return i[o][1];return r},Wt.prototype.update=function(t,e,n,r,i,o,s){void 0===n&&(n=St(r));var a=i===g;if(n!==this.keyHash)return a?this:(E(s),E(o),ne(this,t,e,n,[r,i]));for(var u=this.entries,c=0,l=u.length;c<l&&!dt(r,u[c][0]);c++);var h=c<l;if(h?u[c][1]===i:a)return this;if(E(s),(a||!h)&&E(o),a&&2===l)return new Yt(t,this.keyHash,u[1^c]);var f=t&&t===this.ownerID,p=f?u:_(u);return h?a?c===l-1?p.pop():p[c]=p.pop():p[c]=[r,i]:p.push([r,i]),f?(this.entries=p,this):new Wt(t,this.keyHash,p)},Yt.prototype.get=function(t,e,n,r){return dt(n,this.entry[0])?this.entry[1]:r},Yt.prototype.update=function(t,e,n,r,i,o,s){var a=i===g,u=dt(r,this.entry[0]);return(u?i===this.entry[1]:a)?this:(E(s),a?void E(o):u?t&&t===this.ownerID?(this.entry[1]=i,this):new Yt(t,this.keyHash,[r,i]):(E(o),ne(this,t,e,St(r),[r,i])))},Xt.prototype.iterate=Wt.prototype.iterate=function(t,e){for(var n=this.entries,r=0,i=n.length-1;r<=i;r++)if(!1===t(n[e?i-r:r]))return!1},qt.prototype.iterate=Kt.prototype.iterate=function(t,e){for(var n=this.nodes,r=0,i=n.length-1;r<=i;r++){var o=n[e?i-r:r];if(o&&!1===o.iterate(t,e))return!1}},Yt.prototype.iterate=function(t,e){return t(this.entry)},e(Ht,L),Ht.prototype.next=function(){for(var t=this._type,e=this._stack;e;){var n,r=e.node,i=e.index++;if(r.entry){if(0===i)return Vt(t,r.entry)}else if(r.entries){if(i<=(n=r.entries.length-1))return Vt(t,r.entries[this._reverse?n-i:i])}else if(i<=(n=r.nodes.length-1)){var o=r.nodes[this._reverse?n-i:i];if(o){if(o.entry)return Vt(t,o.entry);e=this._stack=Gt(o,e)}continue}e=this._stack=this._stack.__prev}return{value:void 0,done:!0}};var ce=v/4,le=v/2,he=v/4;function fe(t){var e=Ee();if(null===t||void 0===t)return e;if(pe(t))return t;var n=i(t),r=n.size;return 0===r?e:(Nt(r),r>0&&r<v?De(0,r,m,null,new ve(n.toArray())):e.withMutations(function(t){t.setSize(r),n.forEach(function(e,n){return t.set(n,e)})}))}function pe(t){return!(!t||!t[de])}e(fe,Dt),fe.of=function(){return this(arguments)},fe.prototype.toString=function(){return this.__toString("List [","]")},fe.prototype.get=function(t,e){if((t=A(this,t))>=0&&t<this.size){var n=Se(this,t+=this._origin);return n&&n.array[t&y]}return e},fe.prototype.set=function(t,e){return function(t,e,n){if((e=A(t,e))!=e)return t;if(e>=t.size||e<0)return t.withMutations(function(t){e<0?Ae(t,e).set(0,n):Ae(t,0,e+1).set(e,n)});e+=t._origin;var r=t._tail,i=t._root,o=D(b);e>=ke(t._capacity)?r=we(r,t.__ownerID,0,e,n,o):i=we(i,t.__ownerID,t._level,e,n,o);if(!o.value)return t;if(t.__ownerID)return t._root=i,t._tail=r,t.__hash=void 0,t.__altered=!0,t;return De(t._origin,t._capacity,t._level,i,r)}(this,t,e)},fe.prototype.remove=function(t){return this.has(t)?0===t?this.shift():t===this.size-1?this.pop():this.splice(t,1):this},fe.prototype.insert=function(t,e){return this.splice(t,0,e)},fe.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=m,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):Ee()},fe.prototype.push=function(){var t=arguments,e=this.size;return this.withMutations(function(n){Ae(n,0,e+t.length);for(var r=0;r<t.length;r++)n.set(e+r,t[r])})},fe.prototype.pop=function(){return Ae(this,0,-1)},fe.prototype.unshift=function(){var t=arguments;return this.withMutations(function(e){Ae(e,-t.length);for(var n=0;n<t.length;n++)e.set(n,t[n])})},fe.prototype.shift=function(){return Ae(this,1)},fe.prototype.merge=function(){return Ce(this,void 0,arguments)},fe.prototype.mergeWith=function(e){return Ce(this,e,t.call(arguments,1))},fe.prototype.mergeDeep=function(){return Ce(this,ie,arguments)},fe.prototype.mergeDeepWith=function(e){var n=t.call(arguments,1);return Ce(this,oe(e),n)},fe.prototype.setSize=function(t){return Ae(this,0,t)},fe.prototype.slice=function(t,e){var n=this.size;return k(t,e,n)?this:Ae(this,F(t,n),T(e,n))},fe.prototype.__iterator=function(t,e){var n=0,r=be(this,e);return new L(function(){var e=r();return e===xe?{value:void 0,done:!0}:R(t,n++,e)})},fe.prototype.__iterate=function(t,e){for(var n,r=0,i=be(this,e);(n=i())!==xe&&!1!==t(n,r++,this););return r},fe.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?De(this._origin,this._capacity,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)},fe.isList=pe;var de="@@__IMMUTABLE_LIST__@@",me=fe.prototype;function ve(t,e){this.array=t,this.ownerID=e}me[de]=!0,me.delete=me.remove,me.setIn=Jt.setIn,me.deleteIn=me.removeIn=Jt.removeIn,me.update=Jt.update,me.updateIn=Jt.updateIn,me.mergeIn=Jt.mergeIn,me.mergeDeepIn=Jt.mergeDeepIn,me.withMutations=Jt.withMutations,me.asMutable=Jt.asMutable,me.asImmutable=Jt.asImmutable,me.wasAltered=Jt.wasAltered,ve.prototype.removeBefore=function(t,e,n){if(n===e?1<<e:0===this.array.length)return this;var r=n>>>e&y;if(r>=this.array.length)return new ve([],t);var i,o=0===r;if(e>0){var s=this.array[r];if((i=s&&s.removeBefore(t,e-m,n))===s&&o)return this}if(o&&!i)return this;var a=_e(this,t);if(!o)for(var u=0;u<r;u++)a.array[u]=void 0;return i&&(a.array[r]=i),a},ve.prototype.removeAfter=function(t,e,n){if(n===(e?1<<e:0)||0===this.array.length)return this;var r,i=n-1>>>e&y;if(i>=this.array.length)return this;if(e>0){var o=this.array[i];if((r=o&&o.removeAfter(t,e-m,n))===o&&i===this.array.length-1)return this}var s=_e(this,t);return s.array.splice(i+1),r&&(s.array[i]=r),s};var ye,ge,xe={};function be(t,e){var n=t._origin,r=t._capacity,i=ke(r),o=t._tail;return s(t._root,t._level,0);function s(t,a,u){return 0===a?function(t,s){var a=s===i?o&&o.array:t&&t.array,u=s>n?0:n-s,c=r-s;c>v&&(c=v);return function(){if(u===c)return xe;var t=e?--c:u++;return a&&a[t]}}(t,u):function(t,i,o){var a,u=t&&t.array,c=o>n?0:n-o>>i,l=1+(r-o>>i);l>v&&(l=v);return function(){for(;;){if(a){var t=a();if(t!==xe)return t;a=null}if(c===l)return xe;var n=e?--l:c++;a=s(u&&u[n],i-m,o+(n<<i))}}}(t,a,u)}}function De(t,e,n,r,i,o,s){var a=Object.create(me);return a.size=e-t,a._origin=t,a._capacity=e,a._level=n,a._root=r,a._tail=i,a.__ownerID=o,a.__hash=s,a.__altered=!1,a}function Ee(){return ye||(ye=De(0,0,m))}function we(t,e,n,r,i,o){var s,a=r>>>n&y,u=t&&a<t.array.length;if(!u&&void 0===i)return t;if(n>0){var c=t&&t.array[a],l=we(c,e,n-m,r,i,o);return l===c?t:((s=_e(t,e)).array[a]=l,s)}return u&&t.array[a]===i?t:(E(o),s=_e(t,e),void 0===i&&a===s.array.length-1?s.array.pop():s.array[a]=i,s)}function _e(t,e){return e&&t&&e===t.ownerID?t:new ve(t?t.array.slice():[],e)}function Se(t,e){if(e>=ke(t._capacity))return t._tail;if(e<1<<t._level+m){for(var n=t._root,r=t._level;n&&r>0;)n=n.array[e>>>r&y],r-=m;return n}}function Ae(t,e,n){void 0!==e&&(e|=0),void 0!==n&&(n|=0);var r=t.__ownerID||new w,i=t._origin,o=t._capacity,s=i+e,a=void 0===n?o:n<0?o+n:i+n;if(s===i&&a===o)return t;if(s>=a)return t.clear();for(var u=t._level,c=t._root,l=0;s+l<0;)c=new ve(c&&c.array.length?[void 0,c]:[],r),l+=1<<(u+=m);l&&(s+=l,i+=l,a+=l,o+=l);for(var h=ke(o),f=ke(a);f>=1<<u+m;)c=new ve(c&&c.array.length?[c]:[],r),u+=m;var p=t._tail,d=f<h?Se(t,a-1):f>h?new ve([],r):p;if(p&&f>h&&s<o&&p.array.length){for(var v=c=_e(c,r),g=u;g>m;g-=m){var x=h>>>g&y;v=v.array[x]=_e(v.array[x],r)}v.array[h>>>m&y]=p}if(a<o&&(d=d&&d.removeAfter(r,0,a)),s>=f)s-=f,a-=f,u=m,c=null,d=d&&d.removeBefore(r,0,s);else if(s>i||f<h){for(l=0;c;){var b=s>>>u&y;if(b!==f>>>u&y)break;b&&(l+=(1<<u)*b),u-=m,c=c.array[b]}c&&s>i&&(c=c.removeBefore(r,u,s-l)),c&&f<h&&(c=c.removeAfter(r,u,f-l)),l&&(s-=l,a-=l)}return t.__ownerID?(t.size=a-s,t._origin=s,t._capacity=a,t._level=u,t._root=c,t._tail=d,t.__hash=void 0,t.__altered=!0,t):De(s,a,u,c,d)}function Ce(t,e,n){for(var r=[],o=0,a=0;a<n.length;a++){var u=n[a],c=i(u);c.size>o&&(o=c.size),s(u)||(c=c.map(function(t){return ht(t)})),r.push(c)}return o>t.size&&(t=t.setSize(o)),se(t,e,r)}function ke(t){return t<v?0:t-1>>>m<<m}function Fe(t){return null===t||void 0===t?Oe():Te(t)?t:Oe().withMutations(function(e){var n=r(t);Nt(n.size),n.forEach(function(t,n){return e.set(n,t)})})}function Te(t){return Rt(t)&&l(t)}function Ie(t,e,n,r){var i=Object.create(Fe.prototype);return i.size=t?t.size:0,i._map=t,i._list=e,i.__ownerID=n,i.__hash=r,i}function Oe(){return ge||(ge=Ie(Zt(),Ee()))}function Me(t,e,n){var r,i,o=t._map,s=t._list,a=o.get(e),u=void 0!==a;if(n===g){if(!u)return t;s.size>=v&&s.size>=2*o.size?(r=(i=s.filter(function(t,e){return void 0!==t&&a!==e})).toKeyedSeq().map(function(t){return t[0]}).flip().toMap(),t.__ownerID&&(r.__ownerID=i.__ownerID=t.__ownerID)):(r=o.remove(e),i=a===s.size-1?s.pop():s.set(a,void 0))}else if(u){if(n===s.get(a)[1])return t;r=o,i=s.set(a,[e,n])}else r=o.set(e,s.size),i=s.set(s.size,[e,n]);return t.__ownerID?(t.size=r.size,t._map=r,t._list=i,t.__hash=void 0,t):Ie(r,i)}function Be(t,e){this._iter=t,this._useKeys=e,this.size=t.size}function Pe(t){this._iter=t,this.size=t.size}function je(t){this._iter=t,this.size=t.size}function Ne(t){this._iter=t,this.size=t.size}function Le(t){var e=Qe(t);return e._iter=t,e.size=t.size,e.flip=function(){return t},e.reverse=function(){var e=t.reverse.apply(this);return e.flip=function(){return t.reverse()},e},e.has=function(e){return t.includes(e)},e.includes=function(e){return t.has(e)},e.cacheResult=tn,e.__iterateUncached=function(e,n){var r=this;return t.__iterate(function(t,n){return!1!==e(n,t,r)},n)},e.__iteratorUncached=function(e,n){if(e===B){var r=t.__iterator(e,n);return new L(function(){var t=r.next();if(!t.done){var e=t.value[0];t.value[0]=t.value[1],t.value[1]=e}return t})}return t.__iterator(e===M?O:M,n)},e}function Re(t,e,n){var r=Qe(t);return r.size=t.size,r.has=function(e){return t.has(e)},r.get=function(r,i){var o=t.get(r,g);return o===g?i:e.call(n,o,r,t)},r.__iterateUncached=function(r,i){var o=this;return t.__iterate(function(t,i,s){return!1!==r(e.call(n,t,i,s),i,o)},i)},r.__iteratorUncached=function(r,i){var o=t.__iterator(B,i);return new L(function(){var i=o.next();if(i.done)return i;var s=i.value,a=s[0];return R(r,a,e.call(n,s[1],a,t),i)})},r}function ze(t,e){var n=Qe(t);return n._iter=t,n.size=t.size,n.reverse=function(){return t},t.flip&&(n.flip=function(){var e=Le(t);return e.reverse=function(){return t.flip()},e}),n.get=function(n,r){return t.get(e?n:-1-n,r)},n.has=function(n){return t.has(e?n:-1-n)},n.includes=function(e){return t.includes(e)},n.cacheResult=tn,n.__iterate=function(e,n){var r=this;return t.__iterate(function(t,n){return e(t,n,r)},!n)},n.__iterator=function(e,n){return t.__iterator(e,!n)},n}function Ue(t,e,n,r){var i=Qe(t);return r&&(i.has=function(r){var i=t.get(r,g);return i!==g&&!!e.call(n,i,r,t)},i.get=function(r,i){var o=t.get(r,g);return o!==g&&e.call(n,o,r,t)?o:i}),i.__iterateUncached=function(i,o){var s=this,a=0;return t.__iterate(function(t,o,u){if(e.call(n,t,o,u))return a++,i(t,r?o:a-1,s)},o),a},i.__iteratorUncached=function(i,o){var s=t.__iterator(B,o),a=0;return new L(function(){for(;;){var o=s.next();if(o.done)return o;var u=o.value,c=u[0],l=u[1];if(e.call(n,l,c,t))return R(i,r?c:a++,l,o)}})},i}function Je(t,e,n,r){var i=t.size;if(void 0!==e&&(e|=0),void 0!==n&&(n===1/0?n=i:n|=0),k(e,n,i))return t;var o=F(e,i),s=T(n,i);if(o!=o||s!=s)return Je(t.toSeq().cacheResult(),e,n,r);var a,u=s-o;u==u&&(a=u<0?0:u);var c=Qe(t);return c.size=0===a?a:t.size&&a||void 0,!r&&it(t)&&a>=0&&(c.get=function(e,n){return(e=A(this,e))>=0&&e<a?t.get(e+o,n):n}),c.__iterateUncached=function(e,n){var i=this;if(0===a)return 0;if(n)return this.cacheResult().__iterate(e,n);var s=0,u=!0,c=0;return t.__iterate(function(t,n){if(!u||!(u=s++<o))return c++,!1!==e(t,r?n:c-1,i)&&c!==a}),c},c.__iteratorUncached=function(e,n){if(0!==a&&n)return this.cacheResult().__iterator(e,n);var i=0!==a&&t.__iterator(e,n),s=0,u=0;return new L(function(){for(;s++<o;)i.next();if(++u>a)return{value:void 0,done:!0};var t=i.next();return r||e===M?t:R(e,u-1,e===O?void 0:t.value[1],t)})},c}function Xe(t,e,n,r){var i=Qe(t);return i.__iterateUncached=function(i,o){var s=this;if(o)return this.cacheResult().__iterate(i,o);var a=!0,u=0;return t.__iterate(function(t,o,c){if(!a||!(a=e.call(n,t,o,c)))return u++,i(t,r?o:u-1,s)}),u},i.__iteratorUncached=function(i,o){var s=this;if(o)return this.cacheResult().__iterator(i,o);var a=t.__iterator(B,o),u=!0,c=0;return new L(function(){var t,o,l;do{if((t=a.next()).done)return r||i===M?t:R(i,c++,i===O?void 0:t.value[1],t);var h=t.value;o=h[0],l=h[1],u&&(u=e.call(n,l,o,s))}while(u);return i===B?t:R(i,o,l,t)})},i}function qe(t,e,n){var r=Qe(t);return r.__iterateUncached=function(r,i){var o=0,a=!1;return function t(u,c){var l=this;u.__iterate(function(i,u){return(!e||c<e)&&s(i)?t(i,c+1):!1===r(i,n?u:o++,l)&&(a=!0),!a},i)}(t,0),o},r.__iteratorUncached=function(r,i){var o=t.__iterator(r,i),a=[],u=0;return new L(function(){for(;o;){var t=o.next();if(!1===t.done){var c=t.value;if(r===B&&(c=c[1]),e&&!(a.length<e)||!s(c))return n?t:R(r,u++,c,t);a.push(o),o=c.__iterator(r,i)}else o=a.pop()}return{value:void 0,done:!0}})},r}function Ke(t,e,n){e||(e=en);var r=a(t),i=0,o=t.toSeq().map(function(e,r){return[r,e,i++,n?n(e,r,t):e]}).toArray();return o.sort(function(t,n){return e(t[3],n[3])||t[2]-n[2]}).forEach(r?function(t,e){o[e].length=2}:function(t,e){o[e]=t[1]}),r?Y(o):u(t)?H(o):V(o)}function We(t,e,n){if(e||(e=en),n){var r=t.toSeq().map(function(e,r){return[e,n(e,r,t)]}).reduce(function(t,n){return Ye(e,t[1],n[1])?n:t});return r&&r[0]}return t.reduce(function(t,n){return Ye(e,t,n)?n:t})}function Ye(t,e,n){var r=t(n,e);return 0===r&&n!==e&&(void 0===n||null===n||n!=n)||r>0}function He(t,e,r){var i=Qe(t);return i.size=new tt(r).map(function(t){return t.size}).min(),i.__iterate=function(t,e){for(var n,r=this.__iterator(M,e),i=0;!(n=r.next()).done&&!1!==t(n.value,i++,this););return i},i.__iteratorUncached=function(t,i){var o=r.map(function(t){return t=n(t),X(i?t.reverse():t)}),s=0,a=!1;return new L(function(){var n;return a||(n=o.map(function(t){return t.next()}),a=n.some(function(t){return t.done})),a?{value:void 0,done:!0}:R(t,s++,e.apply(null,n.map(function(t){return t.value})))})},i}function Ve(t,e){return it(t)?e:t.constructor(e)}function Ge(t){if(t!==Object(t))throw new TypeError("Expected [K, V] tuple: "+t)}function $e(t){return Nt(t.size),S(t)}function Ze(t){return a(t)?r:u(t)?i:o}function Qe(t){return Object.create((a(t)?Y:u(t)?H:V).prototype)}function tn(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):W.prototype.cacheResult.call(this)}function en(t,e){return t>e?1:t<e?-1:0}function nn(t){var e=X(t);if(!e){if(!K(t))throw new TypeError("Expected iterable or array-like: "+t);e=X(n(t))}return e}function rn(t,e){var n,r=function(o){if(o instanceof r)return o;if(!(this instanceof r))return new r(o);if(!n){n=!0;var s=Object.keys(t);!function(t,e){try{e.forEach(function(t,e){Object.defineProperty(t,e,{get:function(){return this.get(e)},set:function(t){yt(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}.bind(void 0,t))}catch(t){}}(i,s),i.size=s.length,i._name=e,i._keys=s,i._defaultValues=t}this._map=Lt(o)},i=r.prototype=Object.create(on);return i.constructor=r,r}e(Fe,Lt),Fe.of=function(){return this(arguments)},Fe.prototype.toString=function(){return this.__toString("OrderedMap {","}")},Fe.prototype.get=function(t,e){var n=this._map.get(t);return void 0!==n?this._list.get(n)[1]:e},Fe.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this):Oe()},Fe.prototype.set=function(t,e){return Me(this,t,e)},Fe.prototype.remove=function(t){return Me(this,t,g)},Fe.prototype.wasAltered=function(){return this._map.wasAltered()||this._list.wasAltered()},Fe.prototype.__iterate=function(t,e){var n=this;return this._list.__iterate(function(e){return e&&t(e[1],e[0],n)},e)},Fe.prototype.__iterator=function(t,e){return this._list.fromEntrySeq().__iterator(t,e)},Fe.prototype.__ensureOwner=function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),n=this._list.__ensureOwner(t);return t?Ie(e,n,t,this.__hash):(this.__ownerID=t,this._map=e,this._list=n,this)},Fe.isOrderedMap=Te,Fe.prototype[d]=!0,Fe.prototype.delete=Fe.prototype.remove,e(Be,Y),Be.prototype.get=function(t,e){return this._iter.get(t,e)},Be.prototype.has=function(t){return this._iter.has(t)},Be.prototype.valueSeq=function(){return this._iter.valueSeq()},Be.prototype.reverse=function(){var t=this,e=ze(this,!0);return this._useKeys||(e.valueSeq=function(){return t._iter.toSeq().reverse()}),e},Be.prototype.map=function(t,e){var n=this,r=Re(this,t,e);return this._useKeys||(r.valueSeq=function(){return n._iter.toSeq().map(t,e)}),r},Be.prototype.__iterate=function(t,e){var n,r=this;return this._iter.__iterate(this._useKeys?function(e,n){return t(e,n,r)}:(n=e?$e(this):0,function(i){return t(i,e?--n:n++,r)}),e)},Be.prototype.__iterator=function(t,e){if(this._useKeys)return this._iter.__iterator(t,e);var n=this._iter.__iterator(M,e),r=e?$e(this):0;return new L(function(){var i=n.next();return i.done?i:R(t,e?--r:r++,i.value,i)})},Be.prototype[d]=!0,e(Pe,H),Pe.prototype.includes=function(t){return this._iter.includes(t)},Pe.prototype.__iterate=function(t,e){var n=this,r=0;return this._iter.__iterate(function(e){return t(e,r++,n)},e)},Pe.prototype.__iterator=function(t,e){var n=this._iter.__iterator(M,e),r=0;return new L(function(){var e=n.next();return e.done?e:R(t,r++,e.value,e)})},e(je,V),je.prototype.has=function(t){return this._iter.includes(t)},je.prototype.__iterate=function(t,e){var n=this;return this._iter.__iterate(function(e){return t(e,e,n)},e)},je.prototype.__iterator=function(t,e){var n=this._iter.__iterator(M,e);return new L(function(){var e=n.next();return e.done?e:R(t,e.value,e.value,e)})},e(Ne,Y),Ne.prototype.entrySeq=function(){return this._iter.toSeq()},Ne.prototype.__iterate=function(t,e){var n=this;return this._iter.__iterate(function(e){if(e){Ge(e);var r=s(e);return t(r?e.get(1):e[1],r?e.get(0):e[0],n)}},e)},Ne.prototype.__iterator=function(t,e){var n=this._iter.__iterator(M,e);return new L(function(){for(;;){var e=n.next();if(e.done)return e;var r=e.value;if(r){Ge(r);var i=s(r);return R(t,i?r.get(0):r[0],i?r.get(1):r[1],e)}}})},Pe.prototype.cacheResult=Be.prototype.cacheResult=je.prototype.cacheResult=Ne.prototype.cacheResult=tn,e(rn,bt),rn.prototype.toString=function(){return this.__toString(an(this)+" {","}")},rn.prototype.has=function(t){return this._defaultValues.hasOwnProperty(t)},rn.prototype.get=function(t,e){if(!this.has(t))return e;var n=this._defaultValues[t];return this._map?this._map.get(t,n):n},rn.prototype.clear=function(){if(this.__ownerID)return this._map&&this._map.clear(),this;var t=this.constructor;return t._empty||(t._empty=sn(this,Zt()))},rn.prototype.set=function(t,e){if(!this.has(t))throw new Error('Cannot set unknown key "'+t+'" on '+an(this));if(this._map&&!this._map.has(t)&&e===this._defaultValues[t])return this;var n=this._map&&this._map.set(t,e);return this.__ownerID||n===this._map?this:sn(this,n)},rn.prototype.remove=function(t){if(!this.has(t))return this;var e=this._map&&this._map.remove(t);return this.__ownerID||e===this._map?this:sn(this,e)},rn.prototype.wasAltered=function(){return this._map.wasAltered()},rn.prototype.__iterator=function(t,e){var n=this;return r(this._defaultValues).map(function(t,e){return n.get(e)}).__iterator(t,e)},rn.prototype.__iterate=function(t,e){var n=this;return r(this._defaultValues).map(function(t,e){return n.get(e)}).__iterate(t,e)},rn.prototype.__ensureOwner=function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?sn(this,e,t):(this.__ownerID=t,this._map=e,this)};var on=rn.prototype;function sn(t,e,n){var r=Object.create(Object.getPrototypeOf(t));return r._map=e,r.__ownerID=n,r}function an(t){return t._name||t.constructor.name||"Record"}function un(t){return null===t||void 0===t?mn():cn(t)&&!l(t)?t:mn().withMutations(function(e){var n=o(t);Nt(n.size),n.forEach(function(t){return e.add(t)})})}function cn(t){return!(!t||!t[hn])}on.delete=on.remove,on.deleteIn=on.removeIn=Jt.removeIn,on.merge=Jt.merge,on.mergeWith=Jt.mergeWith,on.mergeIn=Jt.mergeIn,on.mergeDeep=Jt.mergeDeep,on.mergeDeepWith=Jt.mergeDeepWith,on.mergeDeepIn=Jt.mergeDeepIn,on.setIn=Jt.setIn,on.update=Jt.update,on.updateIn=Jt.updateIn,on.withMutations=Jt.withMutations,on.asMutable=Jt.asMutable,on.asImmutable=Jt.asImmutable,e(un,Et),un.of=function(){return this(arguments)},un.fromKeys=function(t){return this(r(t).keySeq())},un.prototype.toString=function(){return this.__toString("Set {","}")},un.prototype.has=function(t){return this._map.has(t)},un.prototype.add=function(t){return pn(this,this._map.set(t,!0))},un.prototype.remove=function(t){return pn(this,this._map.remove(t))},un.prototype.clear=function(){return pn(this,this._map.clear())},un.prototype.union=function(){var e=t.call(arguments,0);return 0===(e=e.filter(function(t){return 0!==t.size})).length?this:0!==this.size||this.__ownerID||1!==e.length?this.withMutations(function(t){for(var n=0;n<e.length;n++)o(e[n]).forEach(function(e){return t.add(e)})}):this.constructor(e[0])},un.prototype.intersect=function(){var e=t.call(arguments,0);if(0===e.length)return this;e=e.map(function(t){return o(t)});var n=this;return this.withMutations(function(t){n.forEach(function(n){e.every(function(t){return t.includes(n)})||t.remove(n)})})},un.prototype.subtract=function(){var e=t.call(arguments,0);if(0===e.length)return this;e=e.map(function(t){return o(t)});var n=this;return this.withMutations(function(t){n.forEach(function(n){e.some(function(t){return t.includes(n)})&&t.remove(n)})})},un.prototype.merge=function(){return this.union.apply(this,arguments)},un.prototype.mergeWith=function(e){var n=t.call(arguments,1);return this.union.apply(this,n)},un.prototype.sort=function(t){return vn(Ke(this,t))},un.prototype.sortBy=function(t,e){return vn(Ke(this,e,t))},un.prototype.wasAltered=function(){return this._map.wasAltered()},un.prototype.__iterate=function(t,e){var n=this;return this._map.__iterate(function(e,r){return t(r,r,n)},e)},un.prototype.__iterator=function(t,e){return this._map.map(function(t,e){return e}).__iterator(t,e)},un.prototype.__ensureOwner=function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?this.__make(e,t):(this.__ownerID=t,this._map=e,this)},un.isSet=cn;var ln,hn="@@__IMMUTABLE_SET__@@",fn=un.prototype;function pn(t,e){return t.__ownerID?(t.size=e.size,t._map=e,t):e===t._map?t:0===e.size?t.__empty():t.__make(e)}function dn(t,e){var n=Object.create(fn);return n.size=t?t.size:0,n._map=t,n.__ownerID=e,n}function mn(){return ln||(ln=dn(Zt()))}function vn(t){return null===t||void 0===t?Dn():yn(t)?t:Dn().withMutations(function(e){var n=o(t);Nt(n.size),n.forEach(function(t){return e.add(t)})})}function yn(t){return cn(t)&&l(t)}fn[hn]=!0,fn.delete=fn.remove,fn.mergeDeep=fn.merge,fn.mergeDeepWith=fn.mergeWith,fn.withMutations=Jt.withMutations,fn.asMutable=Jt.asMutable,fn.asImmutable=Jt.asImmutable,fn.__empty=mn,fn.__make=dn,e(vn,un),vn.of=function(){return this(arguments)},vn.fromKeys=function(t){return this(r(t).keySeq())},vn.prototype.toString=function(){return this.__toString("OrderedSet {","}")},vn.isOrderedSet=yn;var gn,xn=vn.prototype;function bn(t,e){var n=Object.create(xn);return n.size=t?t.size:0,n._map=t,n.__ownerID=e,n}function Dn(){return gn||(gn=bn(Oe()))}function En(t){return null===t||void 0===t?kn():wn(t)?t:kn().unshiftAll(t)}function wn(t){return!(!t||!t[Sn])}xn[d]=!0,xn.__empty=Dn,xn.__make=bn,e(En,Dt),En.of=function(){return this(arguments)},En.prototype.toString=function(){return this.__toString("Stack [","]")},En.prototype.get=function(t,e){var n=this._head;for(t=A(this,t);n&&t--;)n=n.next;return n?n.value:e},En.prototype.peek=function(){return this._head&&this._head.value},En.prototype.push=function(){if(0===arguments.length)return this;for(var t=this.size+arguments.length,e=this._head,n=arguments.length-1;n>=0;n--)e={value:arguments[n],next:e};return this.__ownerID?(this.size=t,this._head=e,this.__hash=void 0,this.__altered=!0,this):Cn(t,e)},En.prototype.pushAll=function(t){if(0===(t=i(t)).size)return this;Nt(t.size);var e=this.size,n=this._head;return t.reverse().forEach(function(t){e++,n={value:t,next:n}}),this.__ownerID?(this.size=e,this._head=n,this.__hash=void 0,this.__altered=!0,this):Cn(e,n)},En.prototype.pop=function(){return this.slice(1)},En.prototype.unshift=function(){return this.push.apply(this,arguments)},En.prototype.unshiftAll=function(t){return this.pushAll(t)},En.prototype.shift=function(){return this.pop.apply(this,arguments)},En.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):kn()},En.prototype.slice=function(t,e){if(k(t,e,this.size))return this;var n=F(t,this.size);if(T(e,this.size)!==this.size)return Dt.prototype.slice.call(this,t,e);for(var r=this.size-n,i=this._head;n--;)i=i.next;return this.__ownerID?(this.size=r,this._head=i,this.__hash=void 0,this.__altered=!0,this):Cn(r,i)},En.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?Cn(this.size,this._head,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},En.prototype.__iterate=function(t,e){if(e)return this.reverse().__iterate(t);for(var n=0,r=this._head;r&&!1!==t(r.value,n++,this);)r=r.next;return n},En.prototype.__iterator=function(t,e){if(e)return this.reverse().__iterator(t);var n=0,r=this._head;return new L(function(){if(r){var e=r.value;return r=r.next,R(t,n++,e)}return{value:void 0,done:!0}})},En.isStack=wn;var _n,Sn="@@__IMMUTABLE_STACK__@@",An=En.prototype;function Cn(t,e,n,r){var i=Object.create(An);return i.size=t,i._head=e,i.__ownerID=n,i.__hash=r,i.__altered=!1,i}function kn(){return _n||(_n=Cn(0))}function Fn(t,e){var n=function(n){t.prototype[n]=e[n]};return Object.keys(e).forEach(n),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(e).forEach(n),t}An[Sn]=!0,An.withMutations=Jt.withMutations,An.asMutable=Jt.asMutable,An.asImmutable=Jt.asImmutable,An.wasAltered=Jt.wasAltered,n.Iterator=L,Fn(n,{toArray:function(){Nt(this.size);var t=new Array(this.size||0);return this.valueSeq().__iterate(function(e,n){t[n]=e}),t},toIndexedSeq:function(){return new Pe(this)},toJS:function(){return this.toSeq().map(function(t){return t&&"function"==typeof t.toJS?t.toJS():t}).__toJS()},toJSON:function(){return this.toSeq().map(function(t){return t&&"function"==typeof t.toJSON?t.toJSON():t}).__toJS()},toKeyedSeq:function(){return new Be(this,!0)},toMap:function(){return Lt(this.toKeyedSeq())},toObject:function(){Nt(this.size);var t={};return this.__iterate(function(e,n){t[n]=e}),t},toOrderedMap:function(){return Fe(this.toKeyedSeq())},toOrderedSet:function(){return vn(a(this)?this.valueSeq():this)},toSet:function(){return un(a(this)?this.valueSeq():this)},toSetSeq:function(){return new je(this)},toSeq:function(){return u(this)?this.toIndexedSeq():a(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return En(a(this)?this.valueSeq():this)},toList:function(){return fe(a(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(t,e){return 0===this.size?t+e:t+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+e},concat:function(){return Ve(this,function(t,e){var n=a(t),i=[t].concat(e).map(function(t){return s(t)?n&&(t=r(t)):t=n?st(t):at(Array.isArray(t)?t:[t]),t}).filter(function(t){return 0!==t.size});if(0===i.length)return t;if(1===i.length){var o=i[0];if(o===t||n&&a(o)||u(t)&&u(o))return o}var c=new tt(i);return n?c=c.toKeyedSeq():u(t)||(c=c.toSetSeq()),(c=c.flatten(!0)).size=i.reduce(function(t,e){if(void 0!==t){var n=e.size;if(void 0!==n)return t+n}},0),c}(this,t.call(arguments,0)))},includes:function(t){return this.some(function(e){return dt(e,t)})},entries:function(){return this.__iterator(B)},every:function(t,e){Nt(this.size);var n=!0;return this.__iterate(function(r,i,o){if(!t.call(e,r,i,o))return n=!1,!1}),n},filter:function(t,e){return Ve(this,Ue(this,t,e,!0))},find:function(t,e,n){var r=this.findEntry(t,e);return r?r[1]:n},forEach:function(t,e){return Nt(this.size),this.__iterate(e?t.bind(e):t)},join:function(t){Nt(this.size),t=void 0!==t?""+t:",";var e="",n=!0;return this.__iterate(function(r){n?n=!1:e+=t,e+=null!==r&&void 0!==r?r.toString():""}),e},keys:function(){return this.__iterator(O)},map:function(t,e){return Ve(this,Re(this,t,e))},reduce:function(t,e,n){var r,i;return Nt(this.size),arguments.length<2?i=!0:r=e,this.__iterate(function(e,o,s){i?(i=!1,r=e):r=t.call(n,r,e,o,s)}),r},reduceRight:function(t,e,n){var r=this.toKeyedSeq().reverse();return r.reduce.apply(r,arguments)},reverse:function(){return Ve(this,ze(this,!0))},slice:function(t,e){return Ve(this,Je(this,t,e,!0))},some:function(t,e){return!this.every(Bn(t),e)},sort:function(t){return Ve(this,Ke(this,t))},values:function(){return this.__iterator(M)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some(function(){return!0})},count:function(t,e){return S(t?this.toSeq().filter(t,e):this)},countBy:function(t,e){return function(t,e,n){var r=Lt().asMutable();return t.__iterate(function(i,o){r.update(e.call(n,i,o,t),0,function(t){return t+1})}),r.asImmutable()}(this,t,e)},equals:function(t){return mt(this,t)},entrySeq:function(){var t=this;if(t._cache)return new tt(t._cache);var e=t.toSeq().map(Mn).toIndexedSeq();return e.fromEntrySeq=function(){return t.toSeq()},e},filterNot:function(t,e){return this.filter(Bn(t),e)},findEntry:function(t,e,n){var r=n;return this.__iterate(function(n,i,o){if(t.call(e,n,i,o))return r=[i,n],!1}),r},findKey:function(t,e){var n=this.findEntry(t,e);return n&&n[0]},findLast:function(t,e,n){return this.toKeyedSeq().reverse().find(t,e,n)},findLastEntry:function(t,e,n){return this.toKeyedSeq().reverse().findEntry(t,e,n)},findLastKey:function(t,e){return this.toKeyedSeq().reverse().findKey(t,e)},first:function(){return this.find(C)},flatMap:function(t,e){return Ve(this,function(t,e,n){var r=Ze(t);return t.toSeq().map(function(i,o){return r(e.call(n,i,o,t))}).flatten(!0)}(this,t,e))},flatten:function(t){return Ve(this,qe(this,t,!0))},fromEntrySeq:function(){return new Ne(this)},get:function(t,e){return this.find(function(e,n){return dt(n,t)},void 0,e)},getIn:function(t,e){for(var n,r=this,i=nn(t);!(n=i.next()).done;){var o=n.value;if((r=r&&r.get?r.get(o,g):g)===g)return e}return r},groupBy:function(t,e){return function(t,e,n){var r=a(t),i=(l(t)?Fe():Lt()).asMutable();t.__iterate(function(o,s){i.update(e.call(n,o,s,t),function(t){return(t=t||[]).push(r?[s,o]:o),t})});var o=Ze(t);return i.map(function(e){return Ve(t,o(e))})}(this,t,e)},has:function(t){return this.get(t,g)!==g},hasIn:function(t){return this.getIn(t,g)!==g},isSubset:function(t){return t="function"==typeof t.includes?t:n(t),this.every(function(e){return t.includes(e)})},isSuperset:function(t){return(t="function"==typeof t.isSubset?t:n(t)).isSubset(this)},keyOf:function(t){return this.findKey(function(e){return dt(e,t)})},keySeq:function(){return this.toSeq().map(On).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(t){return this.toKeyedSeq().reverse().keyOf(t)},max:function(t){return We(this,t)},maxBy:function(t,e){return We(this,e,t)},min:function(t){return We(this,t?Pn(t):Ln)},minBy:function(t,e){return We(this,e?Pn(e):Ln,t)},rest:function(){return this.slice(1)},skip:function(t){return this.slice(Math.max(0,t))},skipLast:function(t){return Ve(this,this.toSeq().reverse().skip(t).reverse())},skipWhile:function(t,e){return Ve(this,Xe(this,t,e,!0))},skipUntil:function(t,e){return this.skipWhile(Bn(t),e)},sortBy:function(t,e){return Ve(this,Ke(this,e,t))},take:function(t){return this.slice(0,Math.max(0,t))},takeLast:function(t){return Ve(this,this.toSeq().reverse().take(t).reverse())},takeWhile:function(t,e){return Ve(this,function(t,e,n){var r=Qe(t);return r.__iterateUncached=function(r,i){var o=this;if(i)return this.cacheResult().__iterate(r,i);var s=0;return t.__iterate(function(t,i,a){return e.call(n,t,i,a)&&++s&&r(t,i,o)}),s},r.__iteratorUncached=function(r,i){var o=this;if(i)return this.cacheResult().__iterator(r,i);var s=t.__iterator(B,i),a=!0;return new L(function(){if(!a)return{value:void 0,done:!0};var t=s.next();if(t.done)return t;var i=t.value,u=i[0],c=i[1];return e.call(n,c,u,o)?r===B?t:R(r,u,c,t):(a=!1,{value:void 0,done:!0})})},r}(this,t,e))},takeUntil:function(t,e){return this.takeWhile(Bn(t),e)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=function(t){if(t.size===1/0)return 0;var e=l(t),n=a(t),r=e?1:0;return function(t,e){return e=wt(e,3432918353),e=wt(e<<15|e>>>-15,461845907),e=wt(e<<13|e>>>-13,5),e=wt((e=(e+3864292196|0)^t)^e>>>16,2246822507),e=_t((e=wt(e^e>>>13,3266489909))^e>>>16)}(t.__iterate(n?e?function(t,e){r=31*r+Rn(St(t),St(e))|0}:function(t,e){r=r+Rn(St(t),St(e))|0}:e?function(t){r=31*r+St(t)|0}:function(t){r=r+St(t)|0}),r)}(this))}});var Tn=n.prototype;Tn[h]=!0,Tn[N]=Tn.values,Tn.__toJS=Tn.toArray,Tn.__toStringMapper=jn,Tn.inspect=Tn.toSource=function(){return this.toString()},Tn.chain=Tn.flatMap,Tn.contains=Tn.includes,Fn(r,{flip:function(){return Ve(this,Le(this))},mapEntries:function(t,e){var n=this,r=0;return Ve(this,this.toSeq().map(function(i,o){return t.call(e,[o,i],r++,n)}).fromEntrySeq())},mapKeys:function(t,e){var n=this;return Ve(this,this.toSeq().flip().map(function(r,i){return t.call(e,r,i,n)}).flip())}});var In=r.prototype;function On(t,e){return e}function Mn(t,e){return[e,t]}function Bn(t){return function(){return!t.apply(this,arguments)}}function Pn(t){return function(){return-t.apply(this,arguments)}}function jn(t){return"string"==typeof t?JSON.stringify(t):String(t)}function Nn(){return _(arguments)}function Ln(t,e){return t<e?1:t>e?-1:0}function Rn(t,e){return t^e+2654435769+(t<<6)+(t>>2)|0}return In[f]=!0,In[N]=Tn.entries,In.__toJS=Tn.toObject,In.__toStringMapper=function(t,e){return JSON.stringify(e)+": "+jn(t)},Fn(i,{toKeyedSeq:function(){return new Be(this,!1)},filter:function(t,e){return Ve(this,Ue(this,t,e,!1))},findIndex:function(t,e){var n=this.findEntry(t,e);return n?n[0]:-1},indexOf:function(t){var e=this.keyOf(t);return void 0===e?-1:e},lastIndexOf:function(t){var e=this.lastKeyOf(t);return void 0===e?-1:e},reverse:function(){return Ve(this,ze(this,!1))},slice:function(t,e){return Ve(this,Je(this,t,e,!1))},splice:function(t,e){var n=arguments.length;if(e=Math.max(0|e,0),0===n||2===n&&!e)return this;t=F(t,t<0?this.count():this.size);var r=this.slice(0,t);return Ve(this,1===n?r:r.concat(_(arguments,2),this.slice(t+e)))},findLastIndex:function(t,e){var n=this.findLastEntry(t,e);return n?n[0]:-1},first:function(){return this.get(0)},flatten:function(t){return Ve(this,qe(this,t,!1))},get:function(t,e){return(t=A(this,t))<0||this.size===1/0||void 0!==this.size&&t>this.size?e:this.find(function(e,n){return n===t},void 0,e)},has:function(t){return(t=A(this,t))>=0&&(void 0!==this.size?this.size===1/0||t<this.size:-1!==this.indexOf(t))},interpose:function(t){return Ve(this,function(t,e){var n=Qe(t);return n.size=t.size&&2*t.size-1,n.__iterateUncached=function(n,r){var i=this,o=0;return t.__iterate(function(t,r){return(!o||!1!==n(e,o++,i))&&!1!==n(t,o++,i)},r),o},n.__iteratorUncached=function(n,r){var i,o=t.__iterator(M,r),s=0;return new L(function(){return(!i||s%2)&&(i=o.next()).done?i:s%2?R(n,s++,e):R(n,s++,i.value,i)})},n}(this,t))},interleave:function(){var t=[this].concat(_(arguments)),e=He(this.toSeq(),H.of,t),n=e.flatten(!0);return e.size&&(n.size=e.size*t.length),Ve(this,n)},keySeq:function(){return gt(0,this.size)},last:function(){return this.get(-1)},skipWhile:function(t,e){return Ve(this,Xe(this,t,e,!1))},zip:function(){return Ve(this,He(this,Nn,[this].concat(_(arguments))))},zipWith:function(t){var e=_(arguments);return e[0]=this,Ve(this,He(this,t,e))}}),i.prototype[p]=!0,i.prototype[d]=!0,Fn(o,{get:function(t,e){return this.has(t)?t:e},includes:function(t){return this.has(t)},keySeq:function(){return this.valueSeq()}}),o.prototype.has=Tn.includes,o.prototype.contains=o.prototype.includes,Fn(Y,r.prototype),Fn(H,i.prototype),Fn(V,o.prototype),Fn(bt,r.prototype),Fn(Dt,i.prototype),Fn(Et,o.prototype),{Iterable:n,Seq:W,Collection:xt,Map:Lt,OrderedMap:Fe,List:fe,Stack:En,Set:un,OrderedSet:vn,Record:rn,Range:gt,Repeat:vt,is:dt,fromJS:ht}},t.exports=r()},function(t,e){t.exports=function(t){return!!t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e,n){"use strict";var r=n(34);t.exports=new r({include:[n(171)]})},function(t,e,n){"use strict";var r=n(34);t.exports=new r({include:[n(113)],implicit:[n(375),n(367),n(369),n(368)]})},function(t,e,n){var r=n(71),i=n(465),o=n(466),s=n(467),a=n(468),u=n(469);function c(t){var e=this.__data__=new r(t);this.size=e.size}c.prototype.clear=i,c.prototype.delete=o,c.prototype.get=s,c.prototype.has=a,c.prototype.set=u,t.exports=c},function(t,e){t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}},function(t,e,n){var r=n(176),i=n(76);t.exports=function(t,e){for(var n=0,o=(e=r(e,t)).length;null!=t&&n<o;)t=t[i(e[n++])];return n&&n==o?t:void 0}},function(t,e,n){var r=n(403),i=n(51);t.exports=function t(e,n,o,s,a){return e===n||(null==e||null==n||!i(e)&&!i(n)?e!=e&&n!=n:r(e,n,o,s,t,a))}},function(t,e,n){var r=n(8),i=n(118),o=n(471),s=n(52);t.exports=function(t,e){return r(t)?t:i(t,e)?[t]:o(s(t))}},function(t,e,n){var r=n(386),i=n(173),o=n(418),s=1,a=2;t.exports=function(t,e,n,u,c,l){var h=n&s,f=t.length,p=e.length;if(f!=p&&!(h&&p>f))return!1;var d=l.get(t);if(d&&l.get(e))return d==e;var m=-1,v=!0,y=n&a?new r:void 0;for(l.set(t,e),l.set(e,t);++m<f;){var g=t[m],x=e[m];if(u)var b=h?u(x,g,m,e,t,l):u(g,x,m,t,e,l);if(void 0!==b){if(b)continue;v=!1;break}if(y){if(!i(e,function(t,e){if(!o(y,e)&&(g===t||c(g,t,n,u,l)))return y.push(e)})){v=!1;break}}else if(g!==x&&!c(g,x,n,u,l)){v=!1;break}}return l.delete(t),l.delete(e),v}},function(t,e,n){(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.exports=n}).call(e,n(13))},function(t,e){var n=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");t.exports=function(t){return n.test(t)}},function(t,e,n){var r=n(50);t.exports=function(t){return t==t&&!r(t)}},function(t,e){t.exports=function(t,e){return function(n){return null!=n&&n[t]===e&&(void 0!==e||t in Object(n))}}},function(t,e){var n=Function.prototype.toString;t.exports=function(t){if(null!=t){try{return n.call(t)}catch(t){}try{return t+""}catch(t){}}return""}},function(t,e,n){var r=n(402),i=n(51),o=Object.prototype,s=o.hasOwnProperty,a=o.propertyIsEnumerable,u=r(function(){return arguments}())?r:function(t){return i(t)&&s.call(t,"callee")&&!a.call(t,"callee")};t.exports=u},function(t,e,n){(function(t){var r=n(7),i=n(485),o="object"==typeof e&&e&&!e.nodeType&&e,s=o&&"object"==typeof t&&t&&!t.nodeType&&t,a=s&&s.exports===o?r.Buffer:void 0,u=(a?a.isBuffer:void 0)||i;t.exports=u}).call(e,n(204)(t))},function(t,e,n){var r=n(49),i=n(50),o="[object AsyncFunction]",s="[object Function]",a="[object GeneratorFunction]",u="[object Proxy]";t.exports=function(t){if(!i(t))return!1;var e=r(t);return e==s||e==a||e==o||e==u}},function(t,e,n){var r=n(406),i=n(417),o=n(459),s=o&&o.isTypedArray,a=s?i(s):r;t.exports=a},function(t,e,n){var r=n(115),i="Expected a function";function o(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new TypeError(i);var n=function(){var r=arguments,i=e?e.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var s=t.apply(this,r);return n.cache=o.set(i,s)||o,s};return n.cache=new(o.Cache||r),n}o.Cache=r,t.exports=o},function(t,e,n){var r=n(423)("toUpperCase");t.exports=r},function(t,e,n){"use strict";var r=n(20);t.exports=function(t,e,n){var i;return isNaN(t)?(i=e)>=0?n&&i?i-1:i:1:!1!==t&&r(t)}},function(t,e,n){t.exports=n(509)()},function(t,e,n){"use strict";t.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(t,e,n){"use strict";var r=n(83),i=n(53),o=n(195),s=(n(196),n(166));n(21),n(521);function a(t,e,n){this.props=t,this.context=e,this.refs=s,this.updater=n||o}function u(t,e,n){this.props=t,this.context=e,this.refs=s,this.updater=n||o}function c(){}a.prototype.isReactComponent={},a.prototype.setState=function(t,e){"object"!=typeof t&&"function"!=typeof t&&null!=t&&r("85"),this.updater.enqueueSetState(this,t),e&&this.updater.enqueueCallback(this,e,"setState")},a.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this),t&&this.updater.enqueueCallback(this,t,"forceUpdate")},c.prototype=a.prototype,u.prototype=new c,u.prototype.constructor=u,i(u.prototype,a.prototype),u.prototype.isPureReactComponent=!0,t.exports={Component:a,PureComponent:u}},function(t,e,n){"use strict";t.exports={current:null}},function(t,e,n){"use strict";var r="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;t.exports=r},function(t,e,n){"use strict";n(69);var r={isMounted:function(t){return!1},enqueueCallback:function(t,e){},enqueueForceUpdate:function(t){},enqueueReplaceState:function(t,e){},enqueueSetState:function(t,e){}};t.exports=r},function(t,e,n){"use strict";var r=!1;t.exports=r},function(t,e,n){"use strict";t.exports=n(514)},function(t,e,n){"use strict";(function(e,r){var i=n(82);t.exports=x;var o,s=n(169);x.ReadableState=g;n(112).EventEmitter;var a=function(t,e){return t.listeners(e).length},u=n(201),c=n(84).Buffer,l=e.Uint8Array||function(){};var h=n(45);h.inherits=n(32);var f=n(538),p=void 0;p=f&&f.debuglog?f.debuglog("stream"):function(){};var d,m=n(526),v=n(200);h.inherits(x,u);var y=["error","close","destroy","pause","resume"];function g(t,e){o=o||n(23),t=t||{};var r=e instanceof o;this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var i=t.highWaterMark,s=t.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:r&&(s||0===s)?s:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new m,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(d||(d=n(202).StringDecoder),this.decoder=new d(t.encoding),this.encoding=t.encoding)}function x(t){if(o=o||n(23),!(this instanceof x))return new x(t);this._readableState=new g(t,this),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),u.call(this)}function b(t,e,n,r,i){var o,s=t._readableState;null===e?(s.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var n=e.decoder.end();n&&n.length&&(e.buffer.push(n),e.length+=e.objectMode?1:n.length)}e.ended=!0,_(t)}(t,s)):(i||(o=function(t,e){var n;r=e,c.isBuffer(r)||r instanceof l||"string"==typeof e||void 0===e||t.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var r;return n}(s,e)),o?t.emit("error",o):s.objectMode||e&&e.length>0?("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===c.prototype||(e=function(t){return c.from(t)}(e)),r?s.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):D(t,s,e,!0):s.ended?t.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!n?(e=s.decoder.write(e),s.objectMode||0!==e.length?D(t,s,e,!1):A(t,s)):D(t,s,e,!1))):r||(s.reading=!1));return function(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}(s)}function D(t,e,n,r){e.flowing&&0===e.length&&!e.sync?(t.emit("data",n),t.read(0)):(e.length+=e.objectMode?1:n.length,r?e.buffer.unshift(n):e.buffer.push(n),e.needReadable&&_(t)),A(t,e)}Object.defineProperty(x.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t)}}),x.prototype.destroy=v.destroy,x.prototype._undestroy=v.undestroy,x.prototype._destroy=function(t,e){this.push(null),e(t)},x.prototype.push=function(t,e){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof t&&((e=e||r.defaultEncoding)!==r.encoding&&(t=c.from(t,e),e=""),n=!0),b(this,t,e,!1,n)},x.prototype.unshift=function(t){return b(this,t,null,!0,!1)},x.prototype.isPaused=function(){return!1===this._readableState.flowing},x.prototype.setEncoding=function(t){return d||(d=n(202).StringDecoder),this._readableState.decoder=new d(t),this._readableState.encoding=t,this};var E=8388608;function w(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!=t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=function(t){return t>=E?t=E:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function _(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(p("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?i.nextTick(S,t):S(t))}function S(t){p("emit readable"),t.emit("readable"),T(t)}function A(t,e){e.readingMore||(e.readingMore=!0,i.nextTick(C,t,e))}function C(t,e){for(var n=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(p("maybeReadMore read 0"),t.read(0),n!==e.length);)n=e.length;e.readingMore=!1}function k(t){p("readable nexttick read 0"),t.read(0)}function F(t,e){e.reading||(p("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),T(t),e.flowing&&!e.reading&&t.read(0)}function T(t){var e=t._readableState;for(p("flow",e.flowing);e.flowing&&null!==t.read(););}function I(t,e){return 0===e.length?null:(e.objectMode?n=e.buffer.shift():!t||t>=e.length?(n=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):n=function(t,e,n){var r;t<e.head.data.length?(r=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):r=t===e.head.data.length?e.shift():n?function(t,e){var n=e.head,r=1,i=n.data;t-=i.length;for(;n=n.next;){var o=n.data,s=t>o.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++r,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++r}return e.length-=r,i}(t,e):function(t,e){var n=c.allocUnsafe(t),r=e.head,i=1;r.data.copy(n),t-=r.data.length;for(;r=r.next;){var o=r.data,s=t>o.length?o.length:t;if(o.copy(n,n.length-t,0,s),0===(t-=s)){s===o.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++i}return e.length-=i,n}(t,e);return r}(t,e.buffer,e.decoder),n);var n}function O(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,i.nextTick(M,e,t))}function M(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function B(t,e){for(var n=0,r=t.length;n<r;n++)if(t[n]===e)return n;return-1}x.prototype.read=function(t){p("read",t),t=parseInt(t,10);var e=this._readableState,n=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return p("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?O(this):_(this),null;if(0===(t=w(t,e))&&e.ended)return 0===e.length&&O(this),null;var r,i=e.needReadable;return p("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&p("length less than watermark",i=!0),e.ended||e.reading?p("reading or ended",i=!1):i&&(p("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=w(n,e))),null===(r=t>0?I(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),n!==t&&e.ended&&O(this)),null!==r&&this.emit("data",r),r},x.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},x.prototype.pipe=function(t,e){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=t;break;case 1:o.pipes=[o.pipes,t];break;default:o.pipes.push(t)}o.pipesCount+=1,p("pipe count=%d opts=%j",o.pipesCount,e);var u=(!e||!1!==e.end)&&t!==r.stdout&&t!==r.stderr?l:x;function c(e,r){p("onunpipe"),e===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,p("cleanup"),t.removeListener("close",y),t.removeListener("finish",g),t.removeListener("drain",h),t.removeListener("error",v),t.removeListener("unpipe",c),n.removeListener("end",l),n.removeListener("end",x),n.removeListener("data",m),f=!0,!o.awaitDrain||t._writableState&&!t._writableState.needDrain||h())}function l(){p("onend"),t.end()}o.endEmitted?i.nextTick(u):n.once("end",u),t.on("unpipe",c);var h=function(t){return function(){var e=t._readableState;p("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&a(t,"data")&&(e.flowing=!0,T(t))}}(n);t.on("drain",h);var f=!1;var d=!1;function m(e){p("ondata"),d=!1,!1!==t.write(e)||d||((1===o.pipesCount&&o.pipes===t||o.pipesCount>1&&-1!==B(o.pipes,t))&&!f&&(p("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,d=!0),n.pause())}function v(e){p("onerror",e),x(),t.removeListener("error",v),0===a(t,"error")&&t.emit("error",e)}function y(){t.removeListener("finish",g),x()}function g(){p("onfinish"),t.removeListener("close",y),x()}function x(){p("unpipe"),n.unpipe(t)}return n.on("data",m),function(t,e,n){if("function"==typeof t.prependListener)return t.prependListener(e,n);t._events&&t._events[e]?s(t._events[e])?t._events[e].unshift(n):t._events[e]=[n,t._events[e]]:t.on(e,n)}(t,"error",v),t.once("close",y),t.once("finish",g),t.emit("pipe",n),o.flowing||(p("pipe resume"),n.resume()),t},x.prototype.unpipe=function(t){var e=this._readableState,n={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,n),this);if(!t){var r=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o<i;o++)r[o].emit("unpipe",this,n);return this}var s=B(e.pipes,t);return-1===s?this:(e.pipes.splice(s,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this,n),this)},x.prototype.on=function(t,e){var n=u.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var r=this._readableState;r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.emittedReadable=!1,r.reading?r.length&&_(this):i.nextTick(k,this))}return n},x.prototype.addListener=x.prototype.on,x.prototype.resume=function(){var t=this._readableState;return t.flowing||(p("resume"),t.flowing=!0,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,i.nextTick(F,t,e))}(this,t)),this},x.prototype.pause=function(){return p("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(p("pause"),this._readableState.flowing=!1,this.emit("pause")),this},x.prototype.wrap=function(t){var e=this,n=this._readableState,r=!1;for(var i in t.on("end",function(){if(p("wrapped end"),n.decoder&&!n.ended){var t=n.decoder.end();t&&t.length&&e.push(t)}e.push(null)}),t.on("data",function(i){(p("wrapped data"),n.decoder&&(i=n.decoder.write(i)),!n.objectMode||null!==i&&void 0!==i)&&((n.objectMode||i&&i.length)&&(e.push(i)||(r=!0,t.pause())))}),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o<y.length;o++)t.on(y[o],this.emit.bind(this,y[o]));return this._read=function(e){p("wrapped _read",e),r&&(r=!1,t.resume())},this},Object.defineProperty(x.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),x._fromList=I}).call(e,n(13),n(36))},function(t,e,n){"use strict";t.exports=o;var r=n(23),i=n(45);function o(t){if(!(this instanceof o))return new o(t);r.call(this,t),this._transformState={afterTransform:function(t,e){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(!r)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=e&&this.push(e),r(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.on("prefinish",s)}function s(){var t=this;"function"==typeof this._flush?this._flush(function(e,n){a(t,e,n)}):a(this,null,null)}function a(t,e,n){if(e)return t.emit("error",e);if(null!=n&&t.push(n),t._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(t._transformState.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}i.inherits=n(32),i.inherits(o,r),o.prototype.push=function(t,e){return this._transformState.needTransform=!1,r.prototype.push.call(this,t,e)},o.prototype._transform=function(t,e,n){throw new Error("_transform() is not implemented")},o.prototype._write=function(t,e,n){var r=this._transformState;if(r.writecb=n,r.writechunk=t,r.writeencoding=e,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},o.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},o.prototype._destroy=function(t,e){var n=this;r.prototype._destroy.call(this,t,function(t){e(t),n.emit("close")})}},function(t,e,n){"use strict";var r=n(82);function i(t,e){t.emit("error",e)}t.exports={destroy:function(t,e){var n=this,o=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return o||s?(e?e(t):!t||this._writableState&&this._writableState.errorEmitted||r.nextTick(i,this,t),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!e&&t?(r.nextTick(i,n,t),n._writableState&&(n._writableState.errorEmitted=!0)):e&&e(t)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},function(t,e,n){t.exports=n(112).EventEmitter},function(t,e,n){"use strict";var r=n(84).Buffer,i=r.isEncoding||function(t){switch((t=""+t)&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(t){var e;switch(this.encoding=function(t){var e=function(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(t);if("string"!=typeof e&&(r.isEncoding===i||!i(t)))throw new Error("Unknown encoding: "+t);return e||t}(t),this.encoding){case"utf16le":this.text=u,this.end=c,e=4;break;case"utf8":this.fillLast=a,e=4;break;case"base64":this.text=l,this.end=h,e=3;break;default:return this.write=f,void(this.end=p)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(e)}function s(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function a(t){var e=this.lastTotal-this.lastNeed,n=function(t,e,n){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==n?n:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function u(t,e){if((t.length-e)%2==0){var n=t.toString("utf16le",e);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function c(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,n)}return e}function l(t,e){var n=(t.length-e)%3;return 0===n?t.toString("base64",e):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-n))}function h(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function f(t){return t.toString(this.encoding)}function p(t){return t&&t.length?this.write(t):""}e.StringDecoder=o,o.prototype.write=function(t){if(0===t.length)return"";var e,n;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<t.length?e?e+this.text(t,n):this.text(t,n):e||""},o.prototype.end=function(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"�":e},o.prototype.text=function(t,e){var n=function(t,e,n){var r=e.length-1;if(r<n)return 0;var i=s(e[r]);if(i>=0)return i>0&&(t.lastNeed=i-1),i;if(--r<n||-2===i)return 0;if((i=s(e[r]))>=0)return i>0&&(t.lastNeed=i-2),i;if(--r<n||-2===i)return 0;if((i=s(e[r]))>=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=n;var r=t.length-(n-this.lastNeed);return t.copy(this.lastChar,0,r),t.toString("utf8",e,r)},o.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length}},function(t,e,n){(function(t){var r=void 0!==t&&t||"undefined"!=typeof self&&self||window,i=Function.prototype.apply;function o(t,e){this._id=t,this._clearFn=e}e.setTimeout=function(){return new o(i.call(setTimeout,r,arguments),clearTimeout)},e.setInterval=function(){return new o(i.call(setInterval,r,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(r,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},n(530),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(e,n(13))},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){"use strict";var r,i=n(126);void 0===((r=i)&&r.__esModule?r:{default:r}).default.Promise&&n(227),String.prototype.startsWith||n(226)},function(t,e,n){"use strict";var r=s(n(215)),i=s(n(213)),o=s(n(208));function s(t){return t&&t.__esModule?t:{default:t}}var a=[i.default,o.default,function(){return{components:{StandaloneLayout:r.default}}}];t.exports=a},function(t,e,n){"use strict";var r=/^(%20|\s)*(javascript|data)/im,i=/[^\x20-\x7E]/gim,o=/^([^:]+):/gm,s=[".","/"];t.exports={sanitizeUrl:function(t){var e,n,a=t.replace(i,"");return function(t){return s.indexOf(t[0])>-1}(a)?a:(n=a.match(o))?(e=n[0],r.test(e)?"about:blank":a):"about:blank"}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(){return{statePlugins:{spec:{actions:s,selectors:h},configs:{reducers:u.default,actions:o,selectors:a}}}};var r=l(n(511)),i=n(124),o=c(n(123)),s=c(n(211)),a=c(n(210)),u=l(n(209));function c(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function l(t){return t&&t.__esModule?t:{default:t}}var h={getLocalConfig:function(){return(0,i.parseYamlConfig)(r.default)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i,o=n(131),s=(r=o)&&r.__esModule?r:{default:r},a=n(167),u=n(123);e.default=(i={},(0,s.default)(i,u.UPDATE_CONFIGS,function(t,e){return t.merge((0,a.fromJS)(e.payload))}),(0,s.default)(i,u.TOGGLE_CONFIGS,function(t,e){var n=e.payload,r=t.get(n);return t.set(n,!r)}),i)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.get=function(t,e){return t.getIn(Array.isArray(e)?e:[e])}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getConfigByUrl=e.downloadConfig=void 0;var r=n(124);e.downloadConfig=function(t){return function(e){return(0,e.fn.fetch)(t)}},e.getConfigByUrl=function(t,e){return function(n){var i=n.specActions;if(t)return i.downloadConfig(t).then(o,o);function o(n){n instanceof Error||n.status>=400?(i.updateLoadingStatus("failedConfig"),i.updateLoadingStatus("failedConfig"),i.updateUrl(""),console.error(n.statusText+" "+t.url),e(null)):e((0,r.parseYamlConfig)(n.text))}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.memoizedSampleFromSchema=e.memoizedCreateXMLExample=e.sampleXmlFromSchema=e.inferSchema=e.sampleFromSchema=void 0,e.createXMLExample=h;var r=n(125),i=s(n(537)),o=s(n(497));function s(t){return t&&t.__esModule?t:{default:t}}var a={string:function(){return"string"},string_email:function(){return"user@example.com"},"string_date-time":function(){return(new Date).toISOString()},number:function(){return 0},number_float:function(){return 0},integer:function(){return 0},boolean:function(t){return"boolean"!=typeof t.default||t.default}},u=function(t){var e=t=(0,r.objectify)(t),n=e.type,i=e.format,o=a[n+"_"+i]||a[n];return(0,r.isFunc)(o)?o(t):"Unknown Type: "+t.type},c=e.sampleFromSchema=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=(0,r.objectify)(e),o=i.type,s=i.example,a=i.properties,c=i.additionalProperties,l=i.items,h=n.includeReadOnly,f=n.includeWriteOnly;if(void 0!==s)return(0,r.deeplyStripKey)(s,"$$ref",function(t){return"string"==typeof t&&t.indexOf("#")>-1});if(!o)if(a)o="object";else{if(!l)return;o="array"}if("object"===o){var p=(0,r.objectify)(a),d={};for(var m in p)p[m].readOnly&&!h||p[m].writeOnly&&!f||(d[m]=t(p[m],n));if(!0===c)d.additionalProp1={};else if(c)for(var v=(0,r.objectify)(c),y=t(v,n),g=1;g<4;g++)d["additionalProp"+g]=y;return d}return"array"===o?Array.isArray(l.anyOf)?l.anyOf.map(function(e){return t(e,n)}):Array.isArray(l.oneOf)?l.oneOf.map(function(e){return t(e,n)}):[t(l,n)]:e.enum?e.default?e.default:(0,r.normalizeArray)(e.enum)[0]:"file"!==o?u(e):void 0},l=(e.inferSchema=function(t){return t.schema&&(t=t.schema),t.properties&&(t.type="object"),t},e.sampleXmlFromSchema=function t(e){var n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=(0,r.objectify)(e),s=o.type,a=o.properties,c=o.additionalProperties,l=o.items,h=o.example,f=i.includeReadOnly,p=i.includeWriteOnly,d=o.default,m={},v={},y=e.xml,g=y.name,x=y.prefix,b=y.namespace,D=o.enum,E=void 0;if(!s)if(a||c)s="object";else{if(!l)return;s="array"}(g=g||"notagname",n=(x?x+":":"")+g,b)&&(v[x?"xmlns:"+x:"xmlns"]=b);if("array"===s&&l){if(l.xml=l.xml||y||{},l.xml.name=l.xml.name||y.name,y.wrapped)return m[n]=[],Array.isArray(h)?h.forEach(function(e){l.example=e,m[n].push(t(l,i))}):Array.isArray(d)?d.forEach(function(e){l.default=e,m[n].push(t(l,i))}):m[n]=[t(l,i)],v&&m[n].push({_attr:v}),m;var w=[];return Array.isArray(h)?(h.forEach(function(e){l.example=e,w.push(t(l,i))}),w):Array.isArray(d)?(d.forEach(function(e){l.default=e,w.push(t(l,i))}),w):t(l,i)}if("object"===s){var _=(0,r.objectify)(a);for(var S in m[n]=[],h=h||{},_)if(_.hasOwnProperty(S)&&(!_[S].readOnly||f)&&(!_[S].writeOnly||p))if(_[S].xml=_[S].xml||{},_[S].xml.attribute){var A=Array.isArray(_[S].enum)&&_[S].enum[0],C=_[S].example,k=_[S].default;v[_[S].xml.name||S]=void 0!==C&&C||void 0!==h[S]&&h[S]||void 0!==k&&k||A||u(_[S])}else{_[S].xml.name=_[S].xml.name||S,void 0===_[S].example&&void 0!==h[S]&&(_[S].example=h[S]);var F=t(_[S]);Array.isArray(F)?m[n]=m[n].concat(F):m[n].push(F)}return!0===c?m[n].push({additionalProp:"Anything can be here"}):c&&m[n].push({additionalProp:u(c)}),v&&m[n].push({_attr:v}),m}return E=void 0!==h?h:void 0!==d?d:Array.isArray(D)?D[0]:u(e),m[n]=v?[{_attr:v},E]:E,m});function h(t,e){var n=l(t,e);if(n)return(0,i.default)(n,{declaration:!0,indent:"\t"})}e.memoizedCreateXMLExample=(0,o.default)(h),e.memoizedSampleFromSchema=(0,o.default)(c)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(){return{components:{Topbar:o.default}}};var r,i=n(214),o=(r=i)&&r.__esModule?r:{default:r}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=p(n(128)),i=p(n(129)),o=p(n(130)),s=p(n(133)),a=p(n(132)),u=n(197),c=p(u),l=p(n(190)),h=p(n(534)),f=n(125);function p(t){return t&&t.__esModule?t:{default:t}}var d=function(t){function e(t,n){(0,i.default)(this,e);var o=(0,s.default)(this,(e.__proto__||(0,r.default)(e)).call(this,t,n));return o.onUrlChange=function(t){var e=t.target.value;o.setState({url:e})},o.loadSpec=function(t){o.props.specActions.updateUrl(t),o.props.specActions.download(t)},o.onUrlSelect=function(t){var e=t.target.value||t.target.href;o.loadSpec(e),o.setSelectedUrl(e),t.preventDefault()},o.downloadUrl=function(t){o.loadSpec(o.state.url),t.preventDefault()},o.setSearch=function(t){var e=(0,f.parseSearch)();e["urls.primaryName"]=t.name;var n=window.location.protocol+"//"+window.location.host+window.location.pathname;window&&window.history&&window.history.pushState&&window.history.replaceState(null,"",n+"?"+(0,f.serializeSearch)(e))},o.setSelectedUrl=function(t){var e=o.props.getConfigs().urls||[];e&&e.length&&t&&e.forEach(function(e,n){e.url===t&&(o.setState({selectedIndex:n}),o.setSearch(e))})},o.onFilterChange=function(t){var e=t.target.value;o.props.layoutActions.updateFilter(e)},o.state={url:t.specSelectors.url(),selectedIndex:0},o}return(0,a.default)(e,t),(0,o.default)(e,[{key:"componentWillReceiveProps",value:function(t){this.setState({url:t.specSelectors.url()})}},{key:"componentWillMount",value:function(){var t=this,e=this.props.getConfigs(),n=e.urls||[];if(n&&n.length){var r=e["urls.primaryName"];r&&n.forEach(function(e,n){e.name===r&&t.setState({selectedIndex:n})})}}},{key:"componentDidMount",value:function(){var t=this.props.getConfigs().urls||[];t&&t.length&&this.loadSpec(t[this.state.selectedIndex].url)}},{key:"render",value:function(){var t=this.props,e=t.getComponent,n=t.specSelectors,r=t.getConfigs,i=e("Button"),o=e("Link"),s="loading"===n.loadingStatus(),a={};"failed"===n.loadingStatus()&&(a.color="red"),s&&(a.color="#aaa");var l=r().urls,f=[],p=null;if(l){var d=[];l.forEach(function(t,e){d.push(c.default.createElement("option",{key:e,value:t.url},t.name))}),f.push(c.default.createElement("label",{className:"select-label",htmlFor:"select"},c.default.createElement("span",null,"Select a spec"),c.default.createElement("select",{id:"select",disabled:s,onChange:this.onUrlSelect,value:l[this.state.selectedIndex].url},d)))}else p=this.downloadUrl,f.push(c.default.createElement("input",{className:"download-url-input",type:"text",onChange:this.onUrlChange,value:this.state.url,disabled:s,style:a})),f.push(c.default.createElement(i,{className:"download-url-button",onClick:this.downloadUrl},"Explore"));return c.default.createElement("div",{className:"topbar"},c.default.createElement("div",{className:"wrapper"},c.default.createElement("div",{className:"topbar-wrapper"},c.default.createElement(o,null,c.default.createElement("img",{height:"30",width:"30",src:h.default,alt:"Swagger UI"}),c.default.createElement("span",null,"swagger")),c.default.createElement("form",{className:"download-url-wrapper",onSubmit:p},f.map(function(t,e){return(0,u.cloneElement)(t,{key:e})})))))}}]),e}(c.default.Component);d.propTypes={layoutActions:l.default.object.isRequired},e.default=d,d.propTypes={specSelectors:l.default.object.isRequired,specActions:l.default.object.isRequired,getComponent:l.default.func.isRequired,getConfigs:l.default.func.isRequired}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=l(n(128)),i=l(n(129)),o=l(n(130)),s=l(n(133)),a=l(n(132)),u=l(n(197)),c=l(n(190));function l(t){return t&&t.__esModule?t:{default:t}}var h=function(t){function e(){return(0,i.default)(this,e),(0,s.default)(this,(e.__proto__||(0,r.default)(e)).apply(this,arguments))}return(0,a.default)(e,t),(0,o.default)(e,[{key:"render",value:function(){var t=this.props,e=t.getComponent,n=t.specSelectors,r=t.errSelectors,i=e("Container"),o=e("Row"),s=e("Col"),a=e("errors",!0),c=e("Topbar",!0),l=e("BaseLayout",!0),h=e("onlineValidatorBadge",!0),f=n.loadingStatus(),p=r.lastError(),d=p?p.get("message"):"";return u.default.createElement(i,{className:"swagger-ui"},c?u.default.createElement(c,null):null,"loading"===f&&u.default.createElement("div",{className:"info"},u.default.createElement("div",{className:"loading-container"},u.default.createElement("div",{className:"loading"}))),"failed"===f&&u.default.createElement("div",{className:"info"},u.default.createElement("div",{className:"loading-container"},u.default.createElement("h4",{className:"title"},"Failed to load API definition."),u.default.createElement(a,null))),"failedConfig"===f&&u.default.createElement("div",{className:"info",style:{maxWidth:"880px",marginLeft:"auto",marginRight:"auto",textAlign:"center"}},u.default.createElement("div",{className:"loading-container"},u.default.createElement("h4",{className:"title"},"Failed to load remote configuration."),u.default.createElement("p",null,d))),!f||"success"===f&&u.default.createElement(l,null),u.default.createElement(o,null,u.default.createElement(s,null,u.default.createElement(h,null))))}}]),e}(u.default.Component);h.propTypes={errSelectors:c.default.object.isRequired,errActions:c.default.object.isRequired,specActions:c.default.object.isRequired,specSelectors:c.default.object.isRequired,layoutSelectors:c.default.object.isRequired,layoutActions:c.default.object.isRequired,getComponent:c.default.func.isRequired},e.default=h},function(t,e,n){t.exports={default:n(229),__esModule:!0}},function(t,e,n){t.exports={default:n(230),__esModule:!0}},function(t,e,n){t.exports={default:n(231),__esModule:!0}},function(t,e,n){t.exports={default:n(232),__esModule:!0}},function(t,e,n){t.exports={default:n(235),__esModule:!0}},function(t,e,n){t.exports={default:n(236),__esModule:!0}},function(t,e,n){t.exports={default:n(237),__esModule:!0}},function(t,e,n){t.exports={default:n(238),__esModule:!0}},function(t,e,n){"use strict";e.__esModule=!0;var r=o(n(216)),i=o(n(85));function o(t){return t&&t.__esModule?t:{default:t}}e.default=function(){return function(t,e){if(Array.isArray(t))return t;if((0,r.default)(Object(t)))return function(t,e){var n=[],r=!0,o=!1,s=void 0;try{for(var a,u=(0,i.default)(t);!(r=(a=u.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){o=!0,s=t}finally{try{!r&&u.return&&u.return()}finally{if(o)throw s}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()},function(t,e,n){"use strict";e.byteLength=function(t){var e=c(t),n=e[0],r=e[1];return 3*(n+r)/4-r},e.toByteArray=function(t){for(var e,n=c(t),r=n[0],s=n[1],a=new o(function(t,e,n){return 3*(e+n)/4-n}(0,r,s)),u=0,l=s>0?r-4:r,h=0;h<l;h+=4)e=i[t.charCodeAt(h)]<<18|i[t.charCodeAt(h+1)]<<12|i[t.charCodeAt(h+2)]<<6|i[t.charCodeAt(h+3)],a[u++]=e>>16&255,a[u++]=e>>8&255,a[u++]=255&e;2===s&&(e=i[t.charCodeAt(h)]<<2|i[t.charCodeAt(h+1)]>>4,a[u++]=255&e);1===s&&(e=i[t.charCodeAt(h)]<<10|i[t.charCodeAt(h+1)]<<4|i[t.charCodeAt(h+2)]>>2,a[u++]=e>>8&255,a[u++]=255&e);return a},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,o=[],s=0,a=n-i;s<a;s+=16383)o.push(l(t,s,s+16383>a?a:s+16383));1===i?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return o.join("")};for(var r=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a<u;++a)r[a]=s[a],i[s.charCodeAt(a)]=a;function c(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");return-1===n&&(n=e),[n,n===e?0:4-n%4]}function l(t,e,n){for(var i,o,s=[],a=e;a<n;a+=3)i=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(255&t[a+2]),s.push(r[(o=i)>>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(t,e,n){n(311),n(315),n(322),n(159),n(306),n(307),n(312),n(316),n(318),n(302),n(303),n(304),n(305),n(308),n(309),n(310),n(313),n(314),n(317),n(319),n(320),n(321),n(298),n(299),n(300),n(301),t.exports=n(10).String},function(t,e,n){n(296),n(159),n(325),n(297),n(323),n(324),t.exports=n(10).Promise},function(t,e,n){n(100),n(99),t.exports=n(256)},function(t,e,n){n(100),n(99),t.exports=n(257)},function(t,e,n){var r=n(2),i=r.JSON||(r.JSON={stringify:JSON.stringify});t.exports=function(t){return i.stringify.apply(i,arguments)}},function(t,e,n){n(259),t.exports=n(2).Object.assign},function(t,e,n){n(260);var r=n(2).Object;t.exports=function(t,e){return r.create(t,e)}},function(t,e,n){n(261);var r=n(2).Object;t.exports=function(t,e,n){return r.defineProperty(t,e,n)}},function(t,e,n){n(262),t.exports=n(2).Object.getPrototypeOf},function(t,e,n){n(263),t.exports=n(2).Object.keys},function(t,e,n){n(264),t.exports=n(2).Object.setPrototypeOf},function(t,e,n){n(266),n(265),n(267),n(268),t.exports=n(2).Symbol},function(t,e,n){n(99),n(100),t.exports=n(98).f("iterator")},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e){t.exports=function(){}},function(t,e,n){var r=n(28),i=n(254),o=n(253);t.exports=function(t){return function(e,n,s){var a,u=r(e),c=i(u.length),l=o(s,c);if(t&&n!=n){for(;c>l;)if((a=u[l++])!=a)return!0}else for(;c>l;l++)if((t||l in u)&&u[l]===n)return t||l||0;return!t&&-1}}},function(t,e,n){var r=n(39),i=n(91),o=n(55);t.exports=function(t){var e=r(t),n=i.f;if(n)for(var s,a=n(t),u=o.f,c=0;a.length>c;)u.call(t,s=a[c++])&&e.push(s);return e}},function(t,e,n){var r=n(9).document;t.exports=r&&r.documentElement},function(t,e,n){var r=n(87);t.exports=Array.isArray||function(t){return"Array"==r(t)}},function(t,e,n){"use strict";var r=n(90),i=n(56),o=n(92),s={};n(26)(s,n(6)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(s,{next:i(1,n)}),o(t,e+" Iterator")}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,n){var r=n(58)("meta"),i=n(27),o=n(16),s=n(17).f,a=0,u=Object.isExtensible||function(){return!0},c=!n(25)(function(){return u(Object.preventExtensions({}))}),l=function(t){s(t,r,{value:{i:"O"+ ++a,w:{}}})},h=t.exports={KEY:r,NEED:!1,fastKey:function(t,e){if(!i(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!o(t,r)){if(!u(t))return"F";if(!e)return"E";l(t)}return t[r].i},getWeak:function(t,e){if(!o(t,r)){if(!u(t))return!0;if(!e)return!1;l(t)}return t[r].w},onFreeze:function(t){return c&&h.NEED&&u(t)&&!o(t,r)&&l(t),t}}},function(t,e,n){"use strict";var r=n(39),i=n(91),o=n(55),s=n(57),a=n(138),u=Object.assign;t.exports=!u||n(25)(function(){var t={},e={},n=Symbol(),r="abcdefghijklmnopqrst";return t[n]=7,r.split("").forEach(function(t){e[t]=t}),7!=u({},t)[n]||Object.keys(u({},e)).join("")!=r})?function(t,e){for(var n=s(t),u=arguments.length,c=1,l=i.f,h=o.f;u>c;)for(var f,p=a(arguments[c++]),d=l?r(p).concat(l(p)):r(p),m=d.length,v=0;m>v;)h.call(p,f=d[v++])&&(n[f]=p[f]);return n}:u},function(t,e,n){var r=n(17),i=n(24),o=n(39);t.exports=n(14)?Object.defineProperties:function(t,e){i(t);for(var n,s=o(e),a=s.length,u=0;a>u;)r.f(t,n=s[u++],e[n]);return t}},function(t,e,n){var r=n(28),i=n(141).f,o={}.toString,s="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return s&&"[object Window]"==o.call(t)?function(t){try{return i(t)}catch(t){return s.slice()}}(t):i(r(t))}},function(t,e,n){var r=n(27),i=n(24),o=function(t,e){if(i(t),!r(e)&&null!==e)throw TypeError(e+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(t,e,r){try{(r=n(135)(Function.call,n(140).f(Object.prototype,"__proto__").set,2))(t,[]),e=!(t instanceof Array)}catch(t){e=!0}return function(t,n){return o(t,n),e?t.__proto__=n:r(t,n),t}}({},!1):void 0),check:o}},function(t,e,n){var r=n(95),i=n(88);t.exports=function(t){return function(e,n){var o,s,a=String(i(e)),u=r(n),c=a.length;return u<0||u>=c?t?"":void 0:(o=a.charCodeAt(u))<55296||o>56319||u+1===c||(s=a.charCodeAt(u+1))<56320||s>57343?t?a.charAt(u):o:t?a.slice(u,u+2):s-56320+(o-55296<<10)+65536}}},function(t,e,n){var r=n(95),i=Math.max,o=Math.min;t.exports=function(t,e){return(t=r(t))<0?i(t+e,0):o(t,e)}},function(t,e,n){var r=n(95),i=Math.min;t.exports=function(t){return t>0?i(r(t),9007199254740991):0}},function(t,e,n){var r=n(134),i=n(6)("iterator"),o=n(38);t.exports=n(2).getIteratorMethod=function(t){if(void 0!=t)return t[i]||t["@@iterator"]||o[r(t)]}},function(t,e,n){var r=n(24),i=n(255);t.exports=n(2).getIterator=function(t){var e=i(t);if("function"!=typeof e)throw TypeError(t+" is not iterable!");return r(e.call(t))}},function(t,e,n){var r=n(134),i=n(6)("iterator"),o=n(38);t.exports=n(2).isIterable=function(t){var e=Object(t);return void 0!==e[i]||"@@iterator"in e||o.hasOwnProperty(r(e))}},function(t,e,n){"use strict";var r=n(240),i=n(246),o=n(38),s=n(28);t.exports=n(139)(Array,"Array",function(t,e){this._t=s(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,n=this._i++;return!t||n>=t.length?(this._t=void 0,i(1)):i(0,"keys"==e?n:"values"==e?t[n]:[n,t[n]])},"values"),o.Arguments=o.Array,r("keys"),r("values"),r("entries")},function(t,e,n){var r=n(15);r(r.S+r.F,"Object",{assign:n(248)})},function(t,e,n){var r=n(15);r(r.S,"Object",{create:n(90)})},function(t,e,n){var r=n(15);r(r.S+r.F*!n(14),"Object",{defineProperty:n(17).f})},function(t,e,n){var r=n(57),i=n(142);n(144)("getPrototypeOf",function(){return function(t){return i(r(t))}})},function(t,e,n){var r=n(57),i=n(39);n(144)("keys",function(){return function(t){return i(r(t))}})},function(t,e,n){var r=n(15);r(r.S,"Object",{setPrototypeOf:n(251).set})},function(t,e){},function(t,e,n){"use strict";var r=n(9),i=n(16),o=n(14),s=n(15),a=n(145),u=n(247).KEY,c=n(25),l=n(94),h=n(92),f=n(58),p=n(6),d=n(98),m=n(97),v=n(242),y=n(244),g=n(24),x=n(27),b=n(28),D=n(96),E=n(56),w=n(90),_=n(250),S=n(140),A=n(17),C=n(39),k=S.f,F=A.f,T=_.f,I=r.Symbol,O=r.JSON,M=O&&O.stringify,B=p("_hidden"),P=p("toPrimitive"),j={}.propertyIsEnumerable,N=l("symbol-registry"),L=l("symbols"),R=l("op-symbols"),z=Object.prototype,U="function"==typeof I,J=r.QObject,X=!J||!J.prototype||!J.prototype.findChild,q=o&&c(function(){return 7!=w(F({},"a",{get:function(){return F(this,"a",{value:7}).a}})).a})?function(t,e,n){var r=k(z,e);r&&delete z[e],F(t,e,n),r&&t!==z&&F(z,e,r)}:F,K=function(t){var e=L[t]=w(I.prototype);return e._k=t,e},W=U&&"symbol"==typeof I.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof I},Y=function(t,e,n){return t===z&&Y(R,e,n),g(t),e=D(e,!0),g(n),i(L,e)?(n.enumerable?(i(t,B)&&t[B][e]&&(t[B][e]=!1),n=w(n,{enumerable:E(0,!1)})):(i(t,B)||F(t,B,E(1,{})),t[B][e]=!0),q(t,e,n)):F(t,e,n)},H=function(t,e){g(t);for(var n,r=v(e=b(e)),i=0,o=r.length;o>i;)Y(t,n=r[i++],e[n]);return t},V=function(t){var e=j.call(this,t=D(t,!0));return!(this===z&&i(L,t)&&!i(R,t))&&(!(e||!i(this,t)||!i(L,t)||i(this,B)&&this[B][t])||e)},G=function(t,e){if(t=b(t),e=D(e,!0),t!==z||!i(L,e)||i(R,e)){var n=k(t,e);return!n||!i(L,e)||i(t,B)&&t[B][e]||(n.enumerable=!0),n}},$=function(t){for(var e,n=T(b(t)),r=[],o=0;n.length>o;)i(L,e=n[o++])||e==B||e==u||r.push(e);return r},Z=function(t){for(var e,n=t===z,r=T(n?R:b(t)),o=[],s=0;r.length>s;)!i(L,e=r[s++])||n&&!i(z,e)||o.push(L[e]);return o};U||(a((I=function(){if(this instanceof I)throw TypeError("Symbol is not a constructor!");var t=f(arguments.length>0?arguments[0]:void 0),e=function(n){this===z&&e.call(R,n),i(this,B)&&i(this[B],t)&&(this[B][t]=!1),q(this,t,E(1,n))};return o&&X&&q(z,t,{configurable:!0,set:e}),K(t)}).prototype,"toString",function(){return this._k}),S.f=G,A.f=Y,n(141).f=_.f=$,n(55).f=V,n(91).f=Z,o&&!n(54)&&a(z,"propertyIsEnumerable",V,!0),d.f=function(t){return K(p(t))}),s(s.G+s.W+s.F*!U,{Symbol:I});for(var Q="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),tt=0;Q.length>tt;)p(Q[tt++]);for(var et=C(p.store),nt=0;et.length>nt;)m(et[nt++]);s(s.S+s.F*!U,"Symbol",{for:function(t){return i(N,t+="")?N[t]:N[t]=I(t)},keyFor:function(t){if(!W(t))throw TypeError(t+" is not a symbol!");for(var e in N)if(N[e]===t)return e},useSetter:function(){X=!0},useSimple:function(){X=!1}}),s(s.S+s.F*!U,"Object",{create:function(t,e){return void 0===e?w(t):H(w(t),e)},defineProperty:Y,defineProperties:H,getOwnPropertyDescriptor:G,getOwnPropertyNames:$,getOwnPropertySymbols:Z}),O&&s(s.S+s.F*(!U||c(function(){var t=I();return"[null]"!=M([t])||"{}"!=M({a:t})||"{}"!=M(Object(t))})),"JSON",{stringify:function(t){for(var e,n,r=[t],i=1;arguments.length>i;)r.push(arguments[i++]);if(n=e=r[1],(x(e)||void 0!==t)&&!W(t))return y(e)||(e=function(t,e){if("function"==typeof n&&(e=n.call(this,t,e)),!W(e))return e}),r[1]=e,M.apply(O,r)}}),I.prototype[P]||n(26)(I.prototype,P,I.prototype.valueOf),h(I,"Symbol"),h(Math,"Math",!0),h(r.JSON,"JSON",!0)},function(t,e,n){n(97)("asyncIterator")},function(t,e,n){n(97)("observable")},function(t,e,n){var r=n(1)("unscopables"),i=Array.prototype;void 0==i[r]&&n(19)(i,r,{}),t.exports=function(t){i[r][t]=!0}},function(t,e){t.exports=function(t,e,n,r){if(!(t instanceof e)||void 0!==r&&r in t)throw TypeError(n+": incorrect invocation!");return t}},function(t,e,n){var r=n(65),i=n(44),o=n(158);t.exports=function(t){return function(e,n,s){var a,u=r(e),c=i(u.length),l=o(s,c);if(t&&n!=n){for(;c>l;)if((a=u[l++])!=a)return!0}else for(;c>l;l++)if((t||l in u)&&u[l]===n)return t||l||0;return!t&&-1}}},function(t,e,n){var r=n(60),i=n(277),o=n(276),s=n(18),a=n(44),u=n(294),c={},l={};(e=t.exports=function(t,e,n,h,f){var p,d,m,v,y=f?function(){return t}:u(t),g=r(n,h,e?2:1),x=0;if("function"!=typeof y)throw TypeError(t+" is not iterable!");if(o(y)){for(p=a(t.length);p>x;x++)if((v=e?g(s(d=t[x])[0],d[1]):g(t[x]))===c||v===l)return v}else for(m=y.call(t);!(d=m.next()).done;)if((v=i(m,g,d.value,e))===c||v===l)return v}).BREAK=c,e.RETURN=l},function(t,e,n){t.exports=!n(41)&&!n(42)(function(){return 7!=Object.defineProperty(n(102)("div"),"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t,e,n){var r=void 0===n;switch(e.length){case 0:return r?t():t.call(n);case 1:return r?t(e[0]):t.call(n,e[0]);case 2:return r?t(e[0],e[1]):t.call(n,e[0],e[1]);case 3:return r?t(e[0],e[1],e[2]):t.call(n,e[0],e[1],e[2]);case 4:return r?t(e[0],e[1],e[2],e[3]):t.call(n,e[0],e[1],e[2],e[3])}return t.apply(n,e)}},function(t,e,n){var r=n(40);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e,n){var r=n(43),i=n(1)("iterator"),o=Array.prototype;t.exports=function(t){return void 0!==t&&(r.Array===t||o[i]===t)}},function(t,e,n){var r=n(18);t.exports=function(t,e,n,i){try{return i?e(r(n)[0],n[1]):e(n)}catch(e){var o=t.return;throw void 0!==o&&r(o.call(t)),e}}},function(t,e,n){"use strict";var r=n(282),i=n(153),o=n(106),s={};n(19)(s,n(1)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(s,{next:i(1,n)}),o(t,e+" Iterator")}},function(t,e,n){var r=n(1)("iterator"),i=!1;try{var o=[7][r]();o.return=function(){i=!0},Array.from(o,function(){throw 2})}catch(t){}t.exports=function(t,e){if(!e&&!i)return!1;var n=!1;try{var o=[7],s=o[r]();s.next=function(){return{done:n=!0}},o[r]=function(){return s},t(o)}catch(t){}return n}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,n){var r=n(4),i=n(157).set,o=r.MutationObserver||r.WebKitMutationObserver,s=r.process,a=r.Promise,u="process"==n(40)(s);t.exports=function(){var t,e,n,c=function(){var r,i;for(u&&(r=s.domain)&&r.exit();t;){i=t.fn,t=t.next;try{i()}catch(r){throw t?n():e=void 0,r}}e=void 0,r&&r.enter()};if(u)n=function(){s.nextTick(c)};else if(!o||r.navigator&&r.navigator.standalone)if(a&&a.resolve){var l=a.resolve(void 0);n=function(){l.then(c)}}else n=function(){i.call(r,c)};else{var h=!0,f=document.createTextNode("");new o(c).observe(f,{characterData:!0}),n=function(){f.data=h=!h}}return function(r){var i={fn:r,next:void 0};e&&(e.next=i),t||(t=i,n()),e=i}}},function(t,e,n){var r=n(18),i=n(283),o=n(146),s=n(107)("IE_PROTO"),a=function(){},u=function(){var t,e=n(102)("iframe"),r=o.length;for(e.style.display="none",n(147).appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),u=t.F;r--;)delete u.prototype[o[r]];return u()};t.exports=Object.create||function(t,e){var n;return null!==t?(a.prototype=r(t),n=new a,a.prototype=null,n[s]=t):n=u(),void 0===e?n:i(n,e)}},function(t,e,n){var r=n(63),i=n(18),o=n(150);t.exports=n(41)?Object.defineProperties:function(t,e){i(t);for(var n,s=o(e),a=s.length,u=0;a>u;)r.f(t,n=s[u++],e[n]);return t}},function(t,e,n){var r=n(62),i=n(291),o=n(107)("IE_PROTO"),s=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=i(t),r(t,o)?t[o]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?s:null}},function(t,e,n){var r=n(62),i=n(65),o=n(271)(!1),s=n(107)("IE_PROTO");t.exports=function(t,e){var n,a=i(t),u=0,c=[];for(n in a)n!=s&&r(a,n)&&c.push(n);for(;e.length>u;)r(a,n=e[u++])&&(~o(c,n)||c.push(n));return c}},function(t,e,n){var r=n(30);t.exports=function(t,e,n){for(var i in e)r(t,i,e[i],n);return t}},function(t,e,n){"use strict";var r=n(4),i=n(63),o=n(41),s=n(1)("species");t.exports=function(t){var e=r[t];o&&e&&!e[s]&&i.f(e,s,{configurable:!0,get:function(){return this}})}},function(t,e,n){"use strict";var r=n(64),i=n(11);t.exports=function(t){var e=String(i(this)),n="",o=r(t);if(o<0||o==1/0)throw RangeError("Count can't be negative");for(;o>0;(o>>>=1)&&(e+=e))1&o&&(n+=e);return n}},function(t,e,n){var r=n(3),i=n(11),o=n(42),s=n(290),a="["+s+"]",u=RegExp("^"+a+a+"*"),c=RegExp(a+a+"*$"),l=function(t,e,n){var i={},a=o(function(){return!!s[t]()||"
"!="
"[t]()}),u=i[t]=a?e(h):s[t];n&&(i[n]=u),r(r.P+r.F*a,"String",i)},h=l.trim=function(t,e){return t=String(i(t)),1&e&&(t=t.replace(u,"")),2&e&&(t=t.replace(c,"")),t};t.exports=l},function(t,e){t.exports="\t\n\v\f\r \u2028\u2029\ufeff"},function(t,e,n){var r=n(11);t.exports=function(t){return Object(r(t))}},function(t,e,n){var r=n(29);t.exports=function(t,e){if(!r(t))return t;var n,i;if(e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;if("function"==typeof(n=t.valueOf)&&!r(i=n.call(t)))return i;if(!e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;throw TypeError("Can't convert object to primitive value")}},function(t,e,n){var r=n(4).navigator;t.exports=r&&r.userAgent||""},function(t,e,n){var r=n(101),i=n(1)("iterator"),o=n(43);t.exports=n(10).getIteratorMethod=function(t){if(void 0!=t)return t[i]||t["@@iterator"]||o[r(t)]}},function(t,e,n){"use strict";var r=n(269),i=n(280),o=n(43),s=n(65);t.exports=n(149)(Array,"Array",function(t,e){this._t=s(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,n=this._i++;return!t||n>=t.length?(this._t=void 0,i(1)):i(0,"keys"==e?n:"values"==e?t[n]:[n,t[n]])},"values"),o.Arguments=o.Array,r("keys"),r("values"),r("entries")},function(t,e,n){"use strict";var r=n(101),i={};i[n(1)("toStringTag")]="z",i+""!="[object z]"&&n(30)(Object.prototype,"toString",function(){return"[object "+r(this)+"]"},!0)},function(t,e,n){"use strict";var r,i,o,s,a=n(104),u=n(4),c=n(60),l=n(101),h=n(3),f=n(29),p=n(59),d=n(270),m=n(272),v=n(155),y=n(157).set,g=n(281)(),x=n(105),b=n(151),D=n(293),E=n(152),w=u.TypeError,_=u.process,S=_&&_.versions,A=S&&S.v8||"",C=u.Promise,k="process"==l(_),F=function(){},T=i=x.f,I=!!function(){try{var t=C.resolve(1),e=(t.constructor={})[n(1)("species")]=function(t){t(F,F)};return(k||"function"==typeof PromiseRejectionEvent)&&t.then(F)instanceof e&&0!==A.indexOf("6.6")&&-1===D.indexOf("Chrome/66")}catch(t){}}(),O=function(t){var e;return!(!f(t)||"function"!=typeof(e=t.then))&&e},M=function(t,e){if(!t._n){t._n=!0;var n=t._c;g(function(){for(var r=t._v,i=1==t._s,o=0,s=function(e){var n,o,s,a=i?e.ok:e.fail,u=e.resolve,c=e.reject,l=e.domain;try{a?(i||(2==t._h&&j(t),t._h=1),!0===a?n=r:(l&&l.enter(),n=a(r),l&&(l.exit(),s=!0)),n===e.promise?c(w("Promise-chain cycle")):(o=O(n))?o.call(n,u,c):u(n)):c(r)}catch(t){l&&!s&&l.exit(),c(t)}};n.length>o;)s(n[o++]);t._c=[],t._n=!1,e&&!t._h&&B(t)})}},B=function(t){y.call(u,function(){var e,n,r,i=t._v,o=P(t);if(o&&(e=b(function(){k?_.emit("unhandledRejection",i,t):(n=u.onunhandledrejection)?n({promise:t,reason:i}):(r=u.console)&&r.error&&r.error("Unhandled promise rejection",i)}),t._h=k||P(t)?2:1),t._a=void 0,o&&e.e)throw e.v})},P=function(t){return 1!==t._h&&0===(t._a||t._c).length},j=function(t){y.call(u,function(){var e;k?_.emit("rejectionHandled",t):(e=u.onrejectionhandled)&&e({promise:t,reason:t._v})})},N=function(t){var e=this;e._d||(e._d=!0,(e=e._w||e)._v=t,e._s=2,e._a||(e._a=e._c.slice()),M(e,!0))},L=function(t){var e,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===t)throw w("Promise can't be resolved itself");(e=O(t))?g(function(){var r={_w:n,_d:!1};try{e.call(t,c(L,r,1),c(N,r,1))}catch(t){N.call(r,t)}}):(n._v=t,n._s=1,M(n,!1))}catch(t){N.call({_w:n,_d:!1},t)}}};I||(C=function(t){d(this,C,"Promise","_h"),p(t),r.call(this);try{t(c(L,this,1),c(N,this,1))}catch(t){N.call(this,t)}},(r=function(t){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=n(286)(C.prototype,{then:function(t,e){var n=T(v(this,C));return n.ok="function"!=typeof t||t,n.fail="function"==typeof e&&e,n.domain=k?_.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&M(this,!1),n.promise},catch:function(t){return this.then(void 0,t)}}),o=function(){var t=new r;this.promise=t,this.resolve=c(L,t,1),this.reject=c(N,t,1)},x.f=T=function(t){return t===C||t===s?new o(t):i(t)}),h(h.G+h.W+h.F*!I,{Promise:C}),n(106)(C,"Promise"),n(287)("Promise"),s=n(10).Promise,h(h.S+h.F*!I,"Promise",{reject:function(t){var e=T(this);return(0,e.reject)(t),e.promise}}),h(h.S+h.F*(a||!I),"Promise",{resolve:function(t){return E(a&&this===s?C:this,t)}}),h(h.S+h.F*!(I&&n(279)(function(t){C.all(t).catch(F)})),"Promise",{all:function(t){var e=this,n=T(e),r=n.resolve,i=n.reject,o=b(function(){var n=[],o=0,s=1;m(t,!1,function(t){var a=o++,u=!1;n.push(void 0),s++,e.resolve(t).then(function(t){u||(u=!0,n[a]=t,--s||r(n))},i)}),--s||r(n)});return o.e&&i(o.v),n.promise},race:function(t){var e=this,n=T(e),r=n.reject,i=b(function(){m(t,!1,function(t){e.resolve(t).then(n.resolve,r)})});return i.e&&r(i.v),n.promise}})},function(t,e,n){n(61)("match",1,function(t,e,n){return[function(n){"use strict";var r=t(this),i=void 0==n?void 0:n[e];return void 0!==i?i.call(n,r):new RegExp(n)[e](String(r))},n]})},function(t,e,n){n(61)("replace",2,function(t,e,n){return[function(r,i){"use strict";var o=t(this),s=void 0==r?void 0:r[e];return void 0!==s?s.call(r,o,i):n.call(String(o),r,i)},n]})},function(t,e,n){n(61)("search",1,function(t,e,n){return[function(n){"use strict";var r=t(this),i=void 0==n?void 0:n[e];return void 0!==i?i.call(n,r):new RegExp(n)[e](String(r))},n]})},function(t,e,n){n(61)("split",2,function(t,e,r){"use strict";var i=n(148),o=r,s=[].push;if("c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length){var a=void 0===/()??/.exec("")[1];r=function(t,e){var n=String(this);if(void 0===t&&0===e)return[];if(!i(t))return o.call(n,t,e);var r,u,c,l,h,f=[],p=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),d=0,m=void 0===e?4294967295:e>>>0,v=new RegExp(t.source,p+"g");for(a||(r=new RegExp("^"+v.source+"$(?!\\s)",p));(u=v.exec(n))&&!((c=u.index+u[0].length)>d&&(f.push(n.slice(d,u.index)),!a&&u.length>1&&u[0].replace(r,function(){for(h=1;h<arguments.length-2;h++)void 0===arguments[h]&&(u[h]=void 0)}),u.length>1&&u.index<n.length&&s.apply(f,u.slice(1)),l=u[0].length,d=c,f.length>=m));)v.lastIndex===u.index&&v.lastIndex++;return d===n.length?!l&&v.test("")||f.push(""):f.push(n.slice(d)),f.length>m?f.slice(0,m):f}}else"0".split(void 0,0).length&&(r=function(t,e){return void 0===t&&0===e?[]:o.call(this,t,e)});return[function(n,i){var o=t(this),s=void 0==n?void 0:n[e];return void 0!==s?s.call(n,o,i):r.call(String(o),n,i)},r]})},function(t,e,n){"use strict";n(5)("anchor",function(t){return function(e){return t(this,"a","name",e)}})},function(t,e,n){"use strict";n(5)("big",function(t){return function(){return t(this,"big","","")}})},function(t,e,n){"use strict";n(5)("blink",function(t){return function(){return t(this,"blink","","")}})},function(t,e,n){"use strict";n(5)("bold",function(t){return function(){return t(this,"b","","")}})},function(t,e,n){"use strict";var r=n(3),i=n(156)(!1);r(r.P,"String",{codePointAt:function(t){return i(this,t)}})},function(t,e,n){"use strict";var r=n(3),i=n(44),o=n(108),s="".endsWith;r(r.P+r.F*n(103)("endsWith"),"String",{endsWith:function(t){var e=o(this,t,"endsWith"),n=arguments.length>1?arguments[1]:void 0,r=i(e.length),a=void 0===n?r:Math.min(i(n),r),u=String(t);return s?s.call(e,u,a):e.slice(a-u.length,a)===u}})},function(t,e,n){"use strict";n(5)("fixed",function(t){return function(){return t(this,"tt","","")}})},function(t,e,n){"use strict";n(5)("fontcolor",function(t){return function(e){return t(this,"font","color",e)}})},function(t,e,n){"use strict";n(5)("fontsize",function(t){return function(e){return t(this,"font","size",e)}})},function(t,e,n){var r=n(3),i=n(158),o=String.fromCharCode,s=String.fromCodePoint;r(r.S+r.F*(!!s&&1!=s.length),"String",{fromCodePoint:function(t){for(var e,n=[],r=arguments.length,s=0;r>s;){if(e=+arguments[s++],i(e,1114111)!==e)throw RangeError(e+" is not a valid code point");n.push(e<65536?o(e):o(55296+((e-=65536)>>10),e%1024+56320))}return n.join("")}})},function(t,e,n){"use strict";var r=n(3),i=n(108);r(r.P+r.F*n(103)("includes"),"String",{includes:function(t){return!!~i(this,t,"includes").indexOf(t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){"use strict";n(5)("italics",function(t){return function(){return t(this,"i","","")}})},function(t,e,n){"use strict";n(5)("link",function(t){return function(e){return t(this,"a","href",e)}})},function(t,e,n){var r=n(3),i=n(65),o=n(44);r(r.S,"String",{raw:function(t){for(var e=i(t.raw),n=o(e.length),r=arguments.length,s=[],a=0;n>a;)s.push(String(e[a++])),a<r&&s.push(String(arguments[a]));return s.join("")}})},function(t,e,n){var r=n(3);r(r.P,"String",{repeat:n(288)})},function(t,e,n){"use strict";n(5)("small",function(t){return function(){return t(this,"small","","")}})},function(t,e,n){"use strict";var r=n(3),i=n(44),o=n(108),s="".startsWith;r(r.P+r.F*n(103)("startsWith"),"String",{startsWith:function(t){var e=o(this,t,"startsWith"),n=i(Math.min(arguments.length>1?arguments[1]:void 0,e.length)),r=String(t);return s?s.call(e,r,n):e.slice(n,n+r.length)===r}})},function(t,e,n){"use strict";n(5)("strike",function(t){return function(){return t(this,"strike","","")}})},function(t,e,n){"use strict";n(5)("sub",function(t){return function(){return t(this,"sub","","")}})},function(t,e,n){"use strict";n(5)("sup",function(t){return function(){return t(this,"sup","","")}})},function(t,e,n){"use strict";n(289)("trim",function(t){return function(){return t(this,3)}})},function(t,e,n){"use strict";var r=n(3),i=n(10),o=n(4),s=n(155),a=n(152);r(r.P+r.R,"Promise",{finally:function(t){var e=s(this,i.Promise||o.Promise),n="function"==typeof t;return this.then(n?function(n){return a(e,t()).then(function(){return n})}:t,n?function(n){return a(e,t()).then(function(){throw n})}:t)}})},function(t,e,n){"use strict";var r=n(3),i=n(105),o=n(151);r(r.S,"Promise",{try:function(t){var e=i.f(this),n=o(t);return(n.e?e.reject:e.resolve)(n.v),e.promise}})},function(t,e,n){for(var r=n(295),i=n(150),o=n(30),s=n(4),a=n(19),u=n(43),c=n(1),l=c("iterator"),h=c("toStringTag"),f=u.Array,p={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},d=i(p),m=0;m<d.length;m++){var v,y=d[m],g=p[y],x=s[y],b=x&&x.prototype;if(b&&(b[l]||a(b,l,f),b[h]||a(b,h,y),u[y]=f,g))for(v in r)b[v]||o(b,v,r[v],!0)}},function(t,e,n){"use strict";var r=n(53),i=n(166),o=n(21),s="mixins";t.exports=function(t,e,n){var a=[],u={mixins:"DEFINE_MANY",statics:"DEFINE_MANY",propTypes:"DEFINE_MANY",contextTypes:"DEFINE_MANY",childContextTypes:"DEFINE_MANY",getDefaultProps:"DEFINE_MANY_MERGED",getInitialState:"DEFINE_MANY_MERGED",getChildContext:"DEFINE_MANY_MERGED",render:"DEFINE_ONCE",componentWillMount:"DEFINE_MANY",componentDidMount:"DEFINE_MANY",componentWillReceiveProps:"DEFINE_MANY",shouldComponentUpdate:"DEFINE_ONCE",componentWillUpdate:"DEFINE_MANY",componentDidUpdate:"DEFINE_MANY",componentWillUnmount:"DEFINE_MANY",UNSAFE_componentWillMount:"DEFINE_MANY",UNSAFE_componentWillReceiveProps:"DEFINE_MANY",UNSAFE_componentWillUpdate:"DEFINE_MANY",updateComponent:"OVERRIDE_BASE"},c={getDerivedStateFromProps:"DEFINE_MANY_MERGED"},l={displayName:function(t,e){t.displayName=e},mixins:function(t,e){if(e)for(var n=0;n<e.length;n++)f(t,e[n])},childContextTypes:function(t,e){t.childContextTypes=r({},t.childContextTypes,e)},contextTypes:function(t,e){t.contextTypes=r({},t.contextTypes,e)},getDefaultProps:function(t,e){t.getDefaultProps?t.getDefaultProps=d(t.getDefaultProps,e):t.getDefaultProps=e},propTypes:function(t,e){t.propTypes=r({},t.propTypes,e)},statics:function(t,e){!function(t,e){if(e)for(var n in e){var r=e[n];if(e.hasOwnProperty(n)){var i=n in l;o(!i,'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.',n);var s=n in t;if(s){var a=c.hasOwnProperty(n)?c[n]:null;return o("DEFINE_MANY_MERGED"===a,"ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",n),void(t[n]=d(t[n],r))}t[n]=r}}}(t,e)},autobind:function(){}};function h(t,e){var n=u.hasOwnProperty(e)?u[e]:null;x.hasOwnProperty(e)&&o("OVERRIDE_BASE"===n,"ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.",e),t&&o("DEFINE_MANY"===n||"DEFINE_MANY_MERGED"===n,"ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",e)}function f(t,n){if(n){o("function"!=typeof n,"ReactClass: You're attempting to use a component class or function as a mixin. Instead, just use a regular object."),o(!e(n),"ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object.");var r=t.prototype,i=r.__reactAutoBindPairs;for(var a in n.hasOwnProperty(s)&&l.mixins(t,n.mixins),n)if(n.hasOwnProperty(a)&&a!==s){var c=n[a],f=r.hasOwnProperty(a);if(h(f,a),l.hasOwnProperty(a))l[a](t,c);else{var p=u.hasOwnProperty(a);if("function"!=typeof c||p||f||!1===n.autobind)if(f){var v=u[a];o(p&&("DEFINE_MANY_MERGED"===v||"DEFINE_MANY"===v),"ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.",v,a),"DEFINE_MANY_MERGED"===v?r[a]=d(r[a],c):"DEFINE_MANY"===v&&(r[a]=m(r[a],c))}else r[a]=c;else i.push(a,c),r[a]=c}}}}function p(t,e){for(var n in o(t&&e&&"object"==typeof t&&"object"==typeof e,"mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects."),e)e.hasOwnProperty(n)&&(o(void 0===t[n],"mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.",n),t[n]=e[n]);return t}function d(t,e){return function(){var n=t.apply(this,arguments),r=e.apply(this,arguments);if(null==n)return r;if(null==r)return n;var i={};return p(i,n),p(i,r),i}}function m(t,e){return function(){t.apply(this,arguments),e.apply(this,arguments)}}function v(t,e){var n=e.bind(t);return n}var y={componentDidMount:function(){this.__isMounted=!0}},g={componentWillUnmount:function(){this.__isMounted=!1}},x={replaceState:function(t,e){this.updater.enqueueReplaceState(this,t,e)},isMounted:function(){return!!this.__isMounted}},b=function(){};return r(b.prototype,t.prototype,x),function(t){var e=function(t,r,s){this.__reactAutoBindPairs.length&&function(t){for(var e=t.__reactAutoBindPairs,n=0;n<e.length;n+=2){var r=e[n],i=e[n+1];t[r]=v(t,i)}}(this),this.props=t,this.context=r,this.refs=i,this.updater=s||n,this.state=null;var a=this.getInitialState?this.getInitialState():null;o("object"==typeof a&&!Array.isArray(a),"%s.getInitialState(): must return an object or null",e.displayName||"ReactCompositeComponent"),this.state=a};for(var r in e.prototype=new b,e.prototype.constructor=e,e.prototype.__reactAutoBindPairs=[],a.forEach(f.bind(null,e)),f(e,y),f(e,t),f(e,g),e.getDefaultProps&&(e.defaultProps=e.getDefaultProps()),o(e.prototype.render,"createClass(...): Class specification must implement a `render` method."),u)e.prototype[r]||(e.prototype[r]=null);return e}}},function(t,e,n){(function(e){var n,r;n=void 0!==e?e:this,r=function(t){if(t.CSS&&t.CSS.escape)return t.CSS.escape;var e=function(t){if(0==arguments.length)throw new TypeError("`CSS.escape` requires an argument.");for(var e,n=String(t),r=n.length,i=-1,o="",s=n.charCodeAt(0);++i<r;)0!=(e=n.charCodeAt(i))?o+=e>=1&&e<=31||127==e||0==i&&e>=48&&e<=57||1==i&&e>=48&&e<=57&&45==s?"\\"+e.toString(16)+" ":(0!=i||1!=r||45!=e)&&(e>=128||45==e||95==e||e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)?n.charAt(i):"\\"+n.charAt(i):o+="�";return o};return t.CSS||(t.CSS={}),t.CSS.escape=e,e},t.exports=r(n)}).call(e,n(13))},function(t,e,n){"use strict";t.exports=function(){var t,e,n=Array.from;return"function"==typeof n&&(e=n(t=["raz","dwa"]),Boolean(e&&e!==t&&"dwa"===e[1]))}},function(t,e,n){"use strict";var r=n(353).iterator,i=n(332),o=n(333),s=n(20),a=n(12),u=n(46),c=n(31),l=n(352),h=Array.isArray,f=Function.prototype.call,p={configurable:!0,enumerable:!0,writable:!0,value:null},d=Object.defineProperty;t.exports=function(t){var e,n,m,v,y,g,x,b,D,E,w=arguments[1],_=arguments[2];if(t=Object(u(t)),c(w)&&a(w),this&&this!==Array&&o(this))e=this;else{if(!w){if(i(t))return 1!==(y=t.length)?Array.apply(null,t):((v=new Array(1))[0]=t[0],v);if(h(t)){for(v=new Array(y=t.length),n=0;n<y;++n)v[n]=t[n];return v}}v=[]}if(!h(t))if(void 0!==(D=t[r])){for(x=a(D).call(t),e&&(v=new e),b=x.next(),n=0;!b.done;)E=w?f.call(w,_,b.value,n):b.value,e?(p.value=E,d(v,n,p)):v[n]=E,b=x.next(),++n;y=n}else if(l(t)){for(y=t.length,e&&(v=new e),n=0,m=0;n<y;++n)E=t[n],n+1<y&&(g=E.charCodeAt(0))>=55296&&g<=56319&&(E+=t[++n]),E=w?f.call(w,_,E,m):E,e?(p.value=E,d(v,m,p)):v[m]=E,++m;y=m}if(void 0===y)for(y=s(t.length),e&&(v=new e(y)),n=0;n<y;++n)E=w?f.call(w,_,t[n],n):t[n],e?(p.value=E,d(v,n,p)):v[n]=E;return e&&(p.value=null,v.length=y),v}},function(t,e,n){"use strict";var r=n(111),i=Array.isArray;t.exports=function(t){return i(t)?t:r(t)}},function(t,e,n){"use strict";var r=n(162),i=n(345),o=n(31),s=Error.captureStackTrace;e=t.exports=function(t){var n=new Error(t),a=arguments[1],u=arguments[2];return o(u)||i(a)&&(u=a,a=null),o(u)&&r(n,u),o(a)&&(n.code=a),s&&s(n,e),n}},function(t,e,n){"use strict";var r=Object.prototype.toString,i=r.call(function(){return arguments}());t.exports=function(t){return r.call(t)===i}},function(t,e,n){"use strict";var r=Object.prototype.toString,i=r.call(n(161));t.exports=function(t){return"function"==typeof t&&r.call(t)===i}},function(t,e,n){"use strict";t.exports=n(335)()?Math.sign:n(336)},function(t,e,n){"use strict";t.exports=function(){var t=Math.sign;return"function"==typeof t&&(1===t(10)&&-1===t(-20))}},function(t,e,n){"use strict";t.exports=function(t){return t=Number(t),isNaN(t)||0===t?t:t>0?1:-1}},function(t,e,n){"use strict";t.exports=n(338)()?Number.isNaN:n(339)},function(t,e,n){"use strict";t.exports=function(){var t=Number.isNaN;return"function"==typeof t&&(!t({})&&t(NaN)&&!t(34))}},function(t,e,n){"use strict";t.exports=function(t){return t!=t}},function(t,e,n){"use strict";var r=n(334),i=Math.abs,o=Math.floor;t.exports=function(t){return isNaN(t)?0:0!==(t=Number(t))&&isFinite(t)?r(t)*o(i(t)):t}},function(t,e,n){"use strict";var r=n(12),i=n(46),o=Function.prototype.bind,s=Function.prototype.call,a=Object.keys,u=Object.prototype.propertyIsEnumerable;t.exports=function(t,e){return function(n,c){var l,h=arguments[2],f=arguments[3];return n=Object(i(n)),r(c),l=a(n),f&&l.sort("function"==typeof f?o.call(f,n):void 0),"function"!=typeof t&&(t=l[t]),s.call(t,l,function(t,r){return u.call(n,t)?s.call(c,h,n[t],t,n,r):e})}}},function(t,e,n){"use strict";t.exports=function(){var t,e=Object.assign;return"function"==typeof e&&(e(t={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),t.foo+t.bar+t.trzy==="razdwatrzy")}},function(t,e,n){"use strict";var r=n(346),i=n(46),o=Math.max;t.exports=function(t,e){var n,s,a,u=o(arguments.length,2);for(t=Object(i(t)),a=function(r){try{t[r]=e[r]}catch(t){n||(n=t)}},s=1;s<u;++s)e=arguments[s],r(e).forEach(a);if(void 0!==n)throw n;return t}},function(t,e,n){"use strict";t.exports=function(t){return"function"==typeof t}},function(t,e,n){"use strict";var r=n(31),i={function:!0,object:!0};t.exports=function(t){return r(t)&&i[typeof t]||!1}},function(t,e,n){"use strict";t.exports=n(347)()?Object.keys:n(348)},function(t,e,n){"use strict";t.exports=function(){try{return Object.keys("primitive"),!0}catch(t){return!1}}},function(t,e,n){"use strict";var r=n(31),i=Object.keys;t.exports=function(t){return i(r(t)?Object(t):t)}},function(t,e,n){"use strict";t.exports=n(350)()?String.prototype.contains:n(351)},function(t,e,n){"use strict";var r="razdwatrzy";t.exports=function(){return"function"==typeof r.contains&&(!0===r.contains("dwa")&&!1===r.contains("foo"))}},function(t,e,n){"use strict";var r=String.prototype.indexOf;t.exports=function(t){return r.call(this,t,arguments[1])>-1}},function(t,e,n){"use strict";var r=Object.prototype.toString,i=r.call("");t.exports=function(t){return"string"==typeof t||t&&"object"==typeof t&&(t instanceof String||r.call(t)===i)||!1}},function(t,e,n){"use strict";t.exports=n(354)()?Symbol:n(356)},function(t,e,n){"use strict";var r={object:!0,symbol:!0};t.exports=function(){var t;if("function"!=typeof Symbol)return!1;t=Symbol("test symbol");try{String(t)}catch(t){return!1}return!!r[typeof Symbol.iterator]&&(!!r[typeof Symbol.toPrimitive]&&!!r[typeof Symbol.toStringTag])}},function(t,e,n){"use strict";t.exports=function(t){return!!t&&("symbol"==typeof t||!!t.constructor&&("Symbol"===t.constructor.name&&"Symbol"===t[t.constructor.toStringTag]))}},function(t,e,n){"use strict";var r,i,o,s,a=n(66),u=n(357),c=Object.create,l=Object.defineProperties,h=Object.defineProperty,f=Object.prototype,p=c(null);if("function"==typeof Symbol){r=Symbol;try{String(r()),s=!0}catch(t){}}var d,m=(d=c(null),function(t){for(var e,n,r=0;d[t+(r||"")];)++r;return d[t+=r||""]=!0,h(f,e="@@"+t,a.gs(null,function(t){n||(n=!0,h(this,e,a(t)),n=!1)})),e});o=function(t){if(this instanceof o)throw new TypeError("Symbol is not a constructor");return i(t)},t.exports=i=function t(e){var n;if(this instanceof t)throw new TypeError("Symbol is not a constructor");return s?r(e):(n=c(o.prototype),e=void 0===e?"":String(e),l(n,{__description__:a("",e),__name__:a("",m(e))}))},l(i,{for:a(function(t){return p[t]?p[t]:p[t]=i(String(t))}),keyFor:a(function(t){var e;for(e in u(t),p)if(p[e]===t)return e}),hasInstance:a("",r&&r.hasInstance||i("hasInstance")),isConcatSpreadable:a("",r&&r.isConcatSpreadable||i("isConcatSpreadable")),iterator:a("",r&&r.iterator||i("iterator")),match:a("",r&&r.match||i("match")),replace:a("",r&&r.replace||i("replace")),search:a("",r&&r.search||i("search")),species:a("",r&&r.species||i("species")),split:a("",r&&r.split||i("split")),toPrimitive:a("",r&&r.toPrimitive||i("toPrimitive")),toStringTag:a("",r&&r.toStringTag||i("toStringTag")),unscopables:a("",r&&r.unscopables||i("unscopables"))}),l(o.prototype,{constructor:a(i),toString:a("",function(){return this.__name__})}),l(i.prototype,{toString:a(function(){return"Symbol ("+u(this).__description__+")"}),valueOf:a(function(){return u(this)})}),h(i.prototype,i.toPrimitive,a("",function(){var t=u(this);return"symbol"==typeof t?t:t.toString()})),h(i.prototype,i.toStringTag,a("c","Symbol")),h(o.prototype,i.toStringTag,a("c",i.prototype[i.toStringTag])),h(o.prototype,i.toPrimitive,a("c",i.prototype[i.toPrimitive]))},function(t,e,n){"use strict";var r=n(355);t.exports=function(t){if(!r(t))throw new TypeError(t+" is not a symbol");return t}},function(t,e,n){var r;r=function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={exports:{},id:r,loaded:!1};return t[r].call(i.exports,i,i.exports,n),i.loaded=!0,i.exports}return n.m=t,n.c=e,n.p="",n(0)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),i=n(3),o=n(8),s=n(15);function a(t,e,n){var s=null,a=function(t,e){n&&n(t,e),s&&s.visit(t,e)},u="function"==typeof n?a:null,c=!1;if(e){c="boolean"==typeof e.comment&&e.comment;var l="boolean"==typeof e.attachComment&&e.attachComment;(c||l)&&((s=new r.CommentHandler).attach=l,e.comment=!0,u=a)}var h,f=!1;e&&"string"==typeof e.sourceType&&(f="module"===e.sourceType),h=e&&"boolean"==typeof e.jsx&&e.jsx?new i.JSXParser(t,e,u):new o.Parser(t,e,u);var p=f?h.parseModule():h.parseScript();return c&&s&&(p.comments=s.comments),h.config.tokens&&(p.tokens=h.tokens),h.config.tolerant&&(p.errors=h.errorHandler.errors),p}e.parse=a,e.parseModule=function(t,e,n){var r=e||{};return r.sourceType="module",a(t,r,n)},e.parseScript=function(t,e,n){var r=e||{};return r.sourceType="script",a(t,r,n)},e.tokenize=function(t,e,n){var r,i=new s.Tokenizer(t,e);r=[];try{for(;;){var o=i.getNextToken();if(!o)break;n&&(o=n(o)),r.push(o)}}catch(t){i.errorHandler.tolerate(t)}return i.errorHandler.tolerant&&(r.errors=i.errors()),r};var u=n(2);e.Syntax=u.Syntax,e.version="4.0.0"},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(2),i=function(){function t(){this.attach=!1,this.comments=[],this.stack=[],this.leading=[],this.trailing=[]}return t.prototype.insertInnerComments=function(t,e){if(t.type===r.Syntax.BlockStatement&&0===t.body.length){for(var n=[],i=this.leading.length-1;i>=0;--i){var o=this.leading[i];e.end.offset>=o.start&&(n.unshift(o.comment),this.leading.splice(i,1),this.trailing.splice(i,1))}n.length&&(t.innerComments=n)}},t.prototype.findTrailingComments=function(t){var e=[];if(this.trailing.length>0){for(var n=this.trailing.length-1;n>=0;--n){var r=this.trailing[n];r.start>=t.end.offset&&e.unshift(r.comment)}return this.trailing.length=0,e}var i=this.stack[this.stack.length-1];if(i&&i.node.trailingComments){var o=i.node.trailingComments[0];o&&o.range[0]>=t.end.offset&&(e=i.node.trailingComments,delete i.node.trailingComments)}return e},t.prototype.findLeadingComments=function(t){for(var e,n=[];this.stack.length>0;){if(!((o=this.stack[this.stack.length-1])&&o.start>=t.start.offset))break;e=o.node,this.stack.pop()}if(e){for(var r=(e.leadingComments?e.leadingComments.length:0)-1;r>=0;--r){var i=e.leadingComments[r];i.range[1]<=t.start.offset&&(n.unshift(i),e.leadingComments.splice(r,1))}return e.leadingComments&&0===e.leadingComments.length&&delete e.leadingComments,n}for(r=this.leading.length-1;r>=0;--r){var o;(o=this.leading[r]).start<=t.start.offset&&(n.unshift(o.comment),this.leading.splice(r,1))}return n},t.prototype.visitNode=function(t,e){if(!(t.type===r.Syntax.Program&&t.body.length>0)){this.insertInnerComments(t,e);var n=this.findTrailingComments(e),i=this.findLeadingComments(e);i.length>0&&(t.leadingComments=i),n.length>0&&(t.trailingComments=n),this.stack.push({node:t,start:e.start.offset})}},t.prototype.visitComment=function(t,e){var n="L"===t.type[0]?"Line":"Block",r={type:n,value:t.value};if(t.range&&(r.range=t.range),t.loc&&(r.loc=t.loc),this.comments.push(r),this.attach){var i={comment:{type:n,value:t.value,range:[e.start.offset,e.end.offset]},start:e.start.offset};t.loc&&(i.comment.loc=t.loc),t.type=n,this.leading.push(i),this.trailing.push(i)}},t.prototype.visit=function(t,e){"LineComment"===t.type?this.visitComment(t,e):"BlockComment"===t.type?this.visitComment(t,e):this.attach&&this.visitNode(t,e)},t}();e.CommentHandler=i},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Syntax={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForOfStatement:"ForOfStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchCase:"SwitchCase",SwitchStatement:"SwitchStatement",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"}},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(4),s=n(5),a=n(6),u=n(7),c=n(8),l=n(13),h=n(14);function f(t){var e;switch(t.type){case a.JSXSyntax.JSXIdentifier:e=t.name;break;case a.JSXSyntax.JSXNamespacedName:var n=t;e=f(n.namespace)+":"+f(n.name);break;case a.JSXSyntax.JSXMemberExpression:var r=t;e=f(r.object)+"."+f(r.property)}return e}l.TokenName[100]="JSXIdentifier",l.TokenName[101]="JSXText";var p=function(t){function e(e,n,r){return t.call(this,e,n,r)||this}return i(e,t),e.prototype.parsePrimaryExpression=function(){return this.match("<")?this.parseJSXRoot():t.prototype.parsePrimaryExpression.call(this)},e.prototype.startJSX=function(){this.scanner.index=this.startMarker.index,this.scanner.lineNumber=this.startMarker.line,this.scanner.lineStart=this.startMarker.index-this.startMarker.column},e.prototype.finishJSX=function(){this.nextToken()},e.prototype.reenterJSX=function(){this.startJSX(),this.expectJSX("}"),this.config.tokens&&this.tokens.pop()},e.prototype.createJSXNode=function(){return this.collectComments(),{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},e.prototype.createJSXChildNode=function(){return{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},e.prototype.scanXHTMLEntity=function(t){for(var e="&",n=!0,r=!1,i=!1,s=!1;!this.scanner.eof()&&n&&!r;){var a=this.scanner.source[this.scanner.index];if(a===t)break;if(r=";"===a,e+=a,++this.scanner.index,!r)switch(e.length){case 2:i="#"===a;break;case 3:i&&(n=(s="x"===a)||o.Character.isDecimalDigit(a.charCodeAt(0)),i=i&&!s);break;default:n=(n=n&&!(i&&!o.Character.isDecimalDigit(a.charCodeAt(0))))&&!(s&&!o.Character.isHexDigit(a.charCodeAt(0)))}}if(n&&r&&e.length>2){var u=e.substr(1,e.length-2);i&&u.length>1?e=String.fromCharCode(parseInt(u.substr(1),10)):s&&u.length>2?e=String.fromCharCode(parseInt("0"+u.substr(1),16)):i||s||!h.XHTMLEntities[u]||(e=h.XHTMLEntities[u])}return e},e.prototype.lexJSX=function(){var t=this.scanner.source.charCodeAt(this.scanner.index);if(60===t||62===t||47===t||58===t||61===t||123===t||125===t)return{type:7,value:a=this.scanner.source[this.scanner.index++],lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index-1,end:this.scanner.index};if(34===t||39===t){for(var e=this.scanner.index,n=this.scanner.source[this.scanner.index++],r="";!this.scanner.eof();){if((u=this.scanner.source[this.scanner.index++])===n)break;r+="&"===u?this.scanXHTMLEntity(n):u}return{type:8,value:r,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:e,end:this.scanner.index}}if(46===t){var i=this.scanner.source.charCodeAt(this.scanner.index+1),s=this.scanner.source.charCodeAt(this.scanner.index+2),a=46===i&&46===s?"...":".";e=this.scanner.index;return this.scanner.index+=a.length,{type:7,value:a,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:e,end:this.scanner.index}}if(96===t)return{type:10,value:"",lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index,end:this.scanner.index};if(o.Character.isIdentifierStart(t)&&92!==t){e=this.scanner.index;for(++this.scanner.index;!this.scanner.eof();){var u=this.scanner.source.charCodeAt(this.scanner.index);if(o.Character.isIdentifierPart(u)&&92!==u)++this.scanner.index;else{if(45!==u)break;++this.scanner.index}}return{type:100,value:this.scanner.source.slice(e,this.scanner.index),lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:e,end:this.scanner.index}}return this.scanner.lex()},e.prototype.nextJSXToken=function(){this.collectComments(),this.startMarker.index=this.scanner.index,this.startMarker.line=this.scanner.lineNumber,this.startMarker.column=this.scanner.index-this.scanner.lineStart;var t=this.lexJSX();return this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart,this.config.tokens&&this.tokens.push(this.convertToken(t)),t},e.prototype.nextJSXText=function(){this.startMarker.index=this.scanner.index,this.startMarker.line=this.scanner.lineNumber,this.startMarker.column=this.scanner.index-this.scanner.lineStart;for(var t=this.scanner.index,e="";!this.scanner.eof();){var n=this.scanner.source[this.scanner.index];if("{"===n||"<"===n)break;++this.scanner.index,e+=n,o.Character.isLineTerminator(n.charCodeAt(0))&&(++this.scanner.lineNumber,"\r"===n&&"\n"===this.scanner.source[this.scanner.index]&&++this.scanner.index,this.scanner.lineStart=this.scanner.index)}this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart;var r={type:101,value:e,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:t,end:this.scanner.index};return e.length>0&&this.config.tokens&&this.tokens.push(this.convertToken(r)),r},e.prototype.peekJSXToken=function(){var t=this.scanner.saveState();this.scanner.scanComments();var e=this.lexJSX();return this.scanner.restoreState(t),e},e.prototype.expectJSX=function(t){var e=this.nextJSXToken();7===e.type&&e.value===t||this.throwUnexpectedToken(e)},e.prototype.matchJSX=function(t){var e=this.peekJSXToken();return 7===e.type&&e.value===t},e.prototype.parseJSXIdentifier=function(){var t=this.createJSXNode(),e=this.nextJSXToken();return 100!==e.type&&this.throwUnexpectedToken(e),this.finalize(t,new s.JSXIdentifier(e.value))},e.prototype.parseJSXElementName=function(){var t=this.createJSXNode(),e=this.parseJSXIdentifier();if(this.matchJSX(":")){var n=e;this.expectJSX(":");var r=this.parseJSXIdentifier();e=this.finalize(t,new s.JSXNamespacedName(n,r))}else if(this.matchJSX("."))for(;this.matchJSX(".");){var i=e;this.expectJSX(".");var o=this.parseJSXIdentifier();e=this.finalize(t,new s.JSXMemberExpression(i,o))}return e},e.prototype.parseJSXAttributeName=function(){var t,e=this.createJSXNode(),n=this.parseJSXIdentifier();if(this.matchJSX(":")){var r=n;this.expectJSX(":");var i=this.parseJSXIdentifier();t=this.finalize(e,new s.JSXNamespacedName(r,i))}else t=n;return t},e.prototype.parseJSXStringLiteralAttribute=function(){var t=this.createJSXNode(),e=this.nextJSXToken();8!==e.type&&this.throwUnexpectedToken(e);var n=this.getTokenRaw(e);return this.finalize(t,new u.Literal(e.value,n))},e.prototype.parseJSXExpressionAttribute=function(){var t=this.createJSXNode();this.expectJSX("{"),this.finishJSX(),this.match("}")&&this.tolerateError("JSX attributes must only be assigned a non-empty expression");var e=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(t,new s.JSXExpressionContainer(e))},e.prototype.parseJSXAttributeValue=function(){return this.matchJSX("{")?this.parseJSXExpressionAttribute():this.matchJSX("<")?this.parseJSXElement():this.parseJSXStringLiteralAttribute()},e.prototype.parseJSXNameValueAttribute=function(){var t=this.createJSXNode(),e=this.parseJSXAttributeName(),n=null;return this.matchJSX("=")&&(this.expectJSX("="),n=this.parseJSXAttributeValue()),this.finalize(t,new s.JSXAttribute(e,n))},e.prototype.parseJSXSpreadAttribute=function(){var t=this.createJSXNode();this.expectJSX("{"),this.expectJSX("..."),this.finishJSX();var e=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(t,new s.JSXSpreadAttribute(e))},e.prototype.parseJSXAttributes=function(){for(var t=[];!this.matchJSX("/")&&!this.matchJSX(">");){var e=this.matchJSX("{")?this.parseJSXSpreadAttribute():this.parseJSXNameValueAttribute();t.push(e)}return t},e.prototype.parseJSXOpeningElement=function(){var t=this.createJSXNode();this.expectJSX("<");var e=this.parseJSXElementName(),n=this.parseJSXAttributes(),r=this.matchJSX("/");return r&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(t,new s.JSXOpeningElement(e,r,n))},e.prototype.parseJSXBoundaryElement=function(){var t=this.createJSXNode();if(this.expectJSX("<"),this.matchJSX("/")){this.expectJSX("/");var e=this.parseJSXElementName();return this.expectJSX(">"),this.finalize(t,new s.JSXClosingElement(e))}var n=this.parseJSXElementName(),r=this.parseJSXAttributes(),i=this.matchJSX("/");return i&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(t,new s.JSXOpeningElement(n,i,r))},e.prototype.parseJSXEmptyExpression=function(){var t=this.createJSXChildNode();return this.collectComments(),this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart,this.finalize(t,new s.JSXEmptyExpression)},e.prototype.parseJSXExpressionContainer=function(){var t,e=this.createJSXNode();return this.expectJSX("{"),this.matchJSX("}")?(t=this.parseJSXEmptyExpression(),this.expectJSX("}")):(this.finishJSX(),t=this.parseAssignmentExpression(),this.reenterJSX()),this.finalize(e,new s.JSXExpressionContainer(t))},e.prototype.parseJSXChildren=function(){for(var t=[];!this.scanner.eof();){var e=this.createJSXChildNode(),n=this.nextJSXText();if(n.start<n.end){var r=this.getTokenRaw(n),i=this.finalize(e,new s.JSXText(n.value,r));t.push(i)}if("{"!==this.scanner.source[this.scanner.index])break;var o=this.parseJSXExpressionContainer();t.push(o)}return t},e.prototype.parseComplexJSXElement=function(t){for(var e=[];!this.scanner.eof();){t.children=t.children.concat(this.parseJSXChildren());var n=this.createJSXChildNode(),r=this.parseJSXBoundaryElement();if(r.type===a.JSXSyntax.JSXOpeningElement){var i=r;if(i.selfClosing){var o=this.finalize(n,new s.JSXElement(i,[],null));t.children.push(o)}else e.push(t),t={node:n,opening:i,closing:null,children:[]}}if(r.type===a.JSXSyntax.JSXClosingElement){t.closing=r;var u=f(t.opening.name);if(u!==f(t.closing.name)&&this.tolerateError("Expected corresponding JSX closing tag for %0",u),!(e.length>0))break;o=this.finalize(t.node,new s.JSXElement(t.opening,t.children,t.closing));(t=e[e.length-1]).children.push(o),e.pop()}}return t},e.prototype.parseJSXElement=function(){var t=this.createJSXNode(),e=this.parseJSXOpeningElement(),n=[],r=null;if(!e.selfClosing){var i=this.parseComplexJSXElement({node:t,opening:e,closing:r,children:n});n=i.children,r=i.closing}return this.finalize(t,new s.JSXElement(e,n,r))},e.prototype.parseJSXRoot=function(){this.config.tokens&&this.tokens.pop(),this.startJSX();var t=this.parseJSXElement();return this.finishJSX(),t},e.prototype.isStartOfExpression=function(){return t.prototype.isStartOfExpression.call(this)||this.match("<")},e}(c.Parser);e.JSXParser=p},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/};e.Character={fromCodePoint:function(t){return t<65536?String.fromCharCode(t):String.fromCharCode(55296+(t-65536>>10))+String.fromCharCode(56320+(t-65536&1023))},isWhiteSpace:function(t){return 32===t||9===t||11===t||12===t||160===t||t>=5760&&[5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(t)>=0},isLineTerminator:function(t){return 10===t||13===t||8232===t||8233===t},isIdentifierStart:function(t){return 36===t||95===t||t>=65&&t<=90||t>=97&&t<=122||92===t||t>=128&&n.NonAsciiIdentifierStart.test(e.Character.fromCodePoint(t))},isIdentifierPart:function(t){return 36===t||95===t||t>=65&&t<=90||t>=97&&t<=122||t>=48&&t<=57||92===t||t>=128&&n.NonAsciiIdentifierPart.test(e.Character.fromCodePoint(t))},isDecimalDigit:function(t){return t>=48&&t<=57},isHexDigit:function(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102},isOctalDigit:function(t){return t>=48&&t<=55}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(6),i=function(){return function(t){this.type=r.JSXSyntax.JSXClosingElement,this.name=t}}();e.JSXClosingElement=i;var o=function(){return function(t,e,n){this.type=r.JSXSyntax.JSXElement,this.openingElement=t,this.children=e,this.closingElement=n}}();e.JSXElement=o;var s=function(){return function(){this.type=r.JSXSyntax.JSXEmptyExpression}}();e.JSXEmptyExpression=s;var a=function(){return function(t){this.type=r.JSXSyntax.JSXExpressionContainer,this.expression=t}}();e.JSXExpressionContainer=a;var u=function(){return function(t){this.type=r.JSXSyntax.JSXIdentifier,this.name=t}}();e.JSXIdentifier=u;var c=function(){return function(t,e){this.type=r.JSXSyntax.JSXMemberExpression,this.object=t,this.property=e}}();e.JSXMemberExpression=c;var l=function(){return function(t,e){this.type=r.JSXSyntax.JSXAttribute,this.name=t,this.value=e}}();e.JSXAttribute=l;var h=function(){return function(t,e){this.type=r.JSXSyntax.JSXNamespacedName,this.namespace=t,this.name=e}}();e.JSXNamespacedName=h;var f=function(){return function(t,e,n){this.type=r.JSXSyntax.JSXOpeningElement,this.name=t,this.selfClosing=e,this.attributes=n}}();e.JSXOpeningElement=f;var p=function(){return function(t){this.type=r.JSXSyntax.JSXSpreadAttribute,this.argument=t}}();e.JSXSpreadAttribute=p;var d=function(){return function(t,e){this.type=r.JSXSyntax.JSXText,this.value=t,this.raw=e}}();e.JSXText=d},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.JSXSyntax={JSXAttribute:"JSXAttribute",JSXClosingElement:"JSXClosingElement",JSXElement:"JSXElement",JSXEmptyExpression:"JSXEmptyExpression",JSXExpressionContainer:"JSXExpressionContainer",JSXIdentifier:"JSXIdentifier",JSXMemberExpression:"JSXMemberExpression",JSXNamespacedName:"JSXNamespacedName",JSXOpeningElement:"JSXOpeningElement",JSXSpreadAttribute:"JSXSpreadAttribute",JSXText:"JSXText"}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(2),i=function(){return function(t){this.type=r.Syntax.ArrayExpression,this.elements=t}}();e.ArrayExpression=i;var o=function(){return function(t){this.type=r.Syntax.ArrayPattern,this.elements=t}}();e.ArrayPattern=o;var s=function(){return function(t,e,n){this.type=r.Syntax.ArrowFunctionExpression,this.id=null,this.params=t,this.body=e,this.generator=!1,this.expression=n,this.async=!1}}();e.ArrowFunctionExpression=s;var a=function(){return function(t,e,n){this.type=r.Syntax.AssignmentExpression,this.operator=t,this.left=e,this.right=n}}();e.AssignmentExpression=a;var u=function(){return function(t,e){this.type=r.Syntax.AssignmentPattern,this.left=t,this.right=e}}();e.AssignmentPattern=u;var c=function(){return function(t,e,n){this.type=r.Syntax.ArrowFunctionExpression,this.id=null,this.params=t,this.body=e,this.generator=!1,this.expression=n,this.async=!0}}();e.AsyncArrowFunctionExpression=c;var l=function(){return function(t,e,n){this.type=r.Syntax.FunctionDeclaration,this.id=t,this.params=e,this.body=n,this.generator=!1,this.expression=!1,this.async=!0}}();e.AsyncFunctionDeclaration=l;var h=function(){return function(t,e,n){this.type=r.Syntax.FunctionExpression,this.id=t,this.params=e,this.body=n,this.generator=!1,this.expression=!1,this.async=!0}}();e.AsyncFunctionExpression=h;var f=function(){return function(t){this.type=r.Syntax.AwaitExpression,this.argument=t}}();e.AwaitExpression=f;var p=function(){return function(t,e,n){var i="||"===t||"&&"===t;this.type=i?r.Syntax.LogicalExpression:r.Syntax.BinaryExpression,this.operator=t,this.left=e,this.right=n}}();e.BinaryExpression=p;var d=function(){return function(t){this.type=r.Syntax.BlockStatement,this.body=t}}();e.BlockStatement=d;var m=function(){return function(t){this.type=r.Syntax.BreakStatement,this.label=t}}();e.BreakStatement=m;var v=function(){return function(t,e){this.type=r.Syntax.CallExpression,this.callee=t,this.arguments=e}}();e.CallExpression=v;var y=function(){return function(t,e){this.type=r.Syntax.CatchClause,this.param=t,this.body=e}}();e.CatchClause=y;var g=function(){return function(t){this.type=r.Syntax.ClassBody,this.body=t}}();e.ClassBody=g;var x=function(){return function(t,e,n){this.type=r.Syntax.ClassDeclaration,this.id=t,this.superClass=e,this.body=n}}();e.ClassDeclaration=x;var b=function(){return function(t,e,n){this.type=r.Syntax.ClassExpression,this.id=t,this.superClass=e,this.body=n}}();e.ClassExpression=b;var D=function(){return function(t,e){this.type=r.Syntax.MemberExpression,this.computed=!0,this.object=t,this.property=e}}();e.ComputedMemberExpression=D;var E=function(){return function(t,e,n){this.type=r.Syntax.ConditionalExpression,this.test=t,this.consequent=e,this.alternate=n}}();e.ConditionalExpression=E;var w=function(){return function(t){this.type=r.Syntax.ContinueStatement,this.label=t}}();e.ContinueStatement=w;var _=function(){return function(){this.type=r.Syntax.DebuggerStatement}}();e.DebuggerStatement=_;var S=function(){return function(t,e){this.type=r.Syntax.ExpressionStatement,this.expression=t,this.directive=e}}();e.Directive=S;var A=function(){return function(t,e){this.type=r.Syntax.DoWhileStatement,this.body=t,this.test=e}}();e.DoWhileStatement=A;var C=function(){return function(){this.type=r.Syntax.EmptyStatement}}();e.EmptyStatement=C;var k=function(){return function(t){this.type=r.Syntax.ExportAllDeclaration,this.source=t}}();e.ExportAllDeclaration=k;var F=function(){return function(t){this.type=r.Syntax.ExportDefaultDeclaration,this.declaration=t}}();e.ExportDefaultDeclaration=F;var T=function(){return function(t,e,n){this.type=r.Syntax.ExportNamedDeclaration,this.declaration=t,this.specifiers=e,this.source=n}}();e.ExportNamedDeclaration=T;var I=function(){return function(t,e){this.type=r.Syntax.ExportSpecifier,this.exported=e,this.local=t}}();e.ExportSpecifier=I;var O=function(){return function(t){this.type=r.Syntax.ExpressionStatement,this.expression=t}}();e.ExpressionStatement=O;var M=function(){return function(t,e,n){this.type=r.Syntax.ForInStatement,this.left=t,this.right=e,this.body=n,this.each=!1}}();e.ForInStatement=M;var B=function(){return function(t,e,n){this.type=r.Syntax.ForOfStatement,this.left=t,this.right=e,this.body=n}}();e.ForOfStatement=B;var P=function(){return function(t,e,n,i){this.type=r.Syntax.ForStatement,this.init=t,this.test=e,this.update=n,this.body=i}}();e.ForStatement=P;var j=function(){return function(t,e,n,i){this.type=r.Syntax.FunctionDeclaration,this.id=t,this.params=e,this.body=n,this.generator=i,this.expression=!1,this.async=!1}}();e.FunctionDeclaration=j;var N=function(){return function(t,e,n,i){this.type=r.Syntax.FunctionExpression,this.id=t,this.params=e,this.body=n,this.generator=i,this.expression=!1,this.async=!1}}();e.FunctionExpression=N;var L=function(){return function(t){this.type=r.Syntax.Identifier,this.name=t}}();e.Identifier=L;var R=function(){return function(t,e,n){this.type=r.Syntax.IfStatement,this.test=t,this.consequent=e,this.alternate=n}}();e.IfStatement=R;var z=function(){return function(t,e){this.type=r.Syntax.ImportDeclaration,this.specifiers=t,this.source=e}}();e.ImportDeclaration=z;var U=function(){return function(t){this.type=r.Syntax.ImportDefaultSpecifier,this.local=t}}();e.ImportDefaultSpecifier=U;var J=function(){return function(t){this.type=r.Syntax.ImportNamespaceSpecifier,this.local=t}}();e.ImportNamespaceSpecifier=J;var X=function(){return function(t,e){this.type=r.Syntax.ImportSpecifier,this.local=t,this.imported=e}}();e.ImportSpecifier=X;var q=function(){return function(t,e){this.type=r.Syntax.LabeledStatement,this.label=t,this.body=e}}();e.LabeledStatement=q;var K=function(){return function(t,e){this.type=r.Syntax.Literal,this.value=t,this.raw=e}}();e.Literal=K;var W=function(){return function(t,e){this.type=r.Syntax.MetaProperty,this.meta=t,this.property=e}}();e.MetaProperty=W;var Y=function(){return function(t,e,n,i,o){this.type=r.Syntax.MethodDefinition,this.key=t,this.computed=e,this.value=n,this.kind=i,this.static=o}}();e.MethodDefinition=Y;var H=function(){return function(t){this.type=r.Syntax.Program,this.body=t,this.sourceType="module"}}();e.Module=H;var V=function(){return function(t,e){this.type=r.Syntax.NewExpression,this.callee=t,this.arguments=e}}();e.NewExpression=V;var G=function(){return function(t){this.type=r.Syntax.ObjectExpression,this.properties=t}}();e.ObjectExpression=G;var $=function(){return function(t){this.type=r.Syntax.ObjectPattern,this.properties=t}}();e.ObjectPattern=$;var Z=function(){return function(t,e,n,i,o,s){this.type=r.Syntax.Property,this.key=e,this.computed=n,this.value=i,this.kind=t,this.method=o,this.shorthand=s}}();e.Property=Z;var Q=function(){return function(t,e,n,i){this.type=r.Syntax.Literal,this.value=t,this.raw=e,this.regex={pattern:n,flags:i}}}();e.RegexLiteral=Q;var tt=function(){return function(t){this.type=r.Syntax.RestElement,this.argument=t}}();e.RestElement=tt;var et=function(){return function(t){this.type=r.Syntax.ReturnStatement,this.argument=t}}();e.ReturnStatement=et;var nt=function(){return function(t){this.type=r.Syntax.Program,this.body=t,this.sourceType="script"}}();e.Script=nt;var rt=function(){return function(t){this.type=r.Syntax.SequenceExpression,this.expressions=t}}();e.SequenceExpression=rt;var it=function(){return function(t){this.type=r.Syntax.SpreadElement,this.argument=t}}();e.SpreadElement=it;var ot=function(){return function(t,e){this.type=r.Syntax.MemberExpression,this.computed=!1,this.object=t,this.property=e}}();e.StaticMemberExpression=ot;var st=function(){return function(){this.type=r.Syntax.Super}}();e.Super=st;var at=function(){return function(t,e){this.type=r.Syntax.SwitchCase,this.test=t,this.consequent=e}}();e.SwitchCase=at;var ut=function(){return function(t,e){this.type=r.Syntax.SwitchStatement,this.discriminant=t,this.cases=e}}();e.SwitchStatement=ut;var ct=function(){return function(t,e){this.type=r.Syntax.TaggedTemplateExpression,this.tag=t,this.quasi=e}}();e.TaggedTemplateExpression=ct;var lt=function(){return function(t,e){this.type=r.Syntax.TemplateElement,this.value=t,this.tail=e}}();e.TemplateElement=lt;var ht=function(){return function(t,e){this.type=r.Syntax.TemplateLiteral,this.quasis=t,this.expressions=e}}();e.TemplateLiteral=ht;var ft=function(){return function(){this.type=r.Syntax.ThisExpression}}();e.ThisExpression=ft;var pt=function(){return function(t){this.type=r.Syntax.ThrowStatement,this.argument=t}}();e.ThrowStatement=pt;var dt=function(){return function(t,e,n){this.type=r.Syntax.TryStatement,this.block=t,this.handler=e,this.finalizer=n}}();e.TryStatement=dt;var mt=function(){return function(t,e){this.type=r.Syntax.UnaryExpression,this.operator=t,this.argument=e,this.prefix=!0}}();e.UnaryExpression=mt;var vt=function(){return function(t,e,n){this.type=r.Syntax.UpdateExpression,this.operator=t,this.argument=e,this.prefix=n}}();e.UpdateExpression=vt;var yt=function(){return function(t,e){this.type=r.Syntax.VariableDeclaration,this.declarations=t,this.kind=e}}();e.VariableDeclaration=yt;var gt=function(){return function(t,e){this.type=r.Syntax.VariableDeclarator,this.id=t,this.init=e}}();e.VariableDeclarator=gt;var xt=function(){return function(t,e){this.type=r.Syntax.WhileStatement,this.test=t,this.body=e}}();e.WhileStatement=xt;var bt=function(){return function(t,e){this.type=r.Syntax.WithStatement,this.object=t,this.body=e}}();e.WithStatement=bt;var Dt=function(){return function(t,e){this.type=r.Syntax.YieldExpression,this.argument=t,this.delegate=e}}();e.YieldExpression=Dt},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(9),i=n(10),o=n(11),s=n(7),a=n(12),u=n(2),c=n(13),l=function(){function t(t,e,n){void 0===e&&(e={}),this.config={range:"boolean"==typeof e.range&&e.range,loc:"boolean"==typeof e.loc&&e.loc,source:null,tokens:"boolean"==typeof e.tokens&&e.tokens,comment:"boolean"==typeof e.comment&&e.comment,tolerant:"boolean"==typeof e.tolerant&&e.tolerant},this.config.loc&&e.source&&null!==e.source&&(this.config.source=String(e.source)),this.delegate=n,this.errorHandler=new i.ErrorHandler,this.errorHandler.tolerant=this.config.tolerant,this.scanner=new a.Scanner(t,this.errorHandler),this.scanner.trackComment=this.config.comment,this.operatorPrecedence={")":0,";":0,",":0,"=":0,"]":0,"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":11,"/":11,"%":11},this.lookahead={type:2,value:"",lineNumber:this.scanner.lineNumber,lineStart:0,start:0,end:0},this.hasLineTerminator=!1,this.context={isModule:!1,await:!1,allowIn:!0,allowStrictDirective:!0,allowYield:!0,firstCoverInitializedNameError:null,isAssignmentTarget:!1,isBindingElement:!1,inFunctionBody:!1,inIteration:!1,inSwitch:!1,labelSet:{},strict:!1},this.tokens=[],this.startMarker={index:0,line:this.scanner.lineNumber,column:0},this.lastMarker={index:0,line:this.scanner.lineNumber,column:0},this.nextToken(),this.lastMarker={index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}}return t.prototype.throwError=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];var i=Array.prototype.slice.call(arguments,1),o=t.replace(/%(\d)/g,function(t,e){return r.assert(e<i.length,"Message reference must be in range"),i[e]}),s=this.lastMarker.index,a=this.lastMarker.line,u=this.lastMarker.column+1;throw this.errorHandler.createError(s,a,u,o)},t.prototype.tolerateError=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];var i=Array.prototype.slice.call(arguments,1),o=t.replace(/%(\d)/g,function(t,e){return r.assert(e<i.length,"Message reference must be in range"),i[e]}),s=this.lastMarker.index,a=this.scanner.lineNumber,u=this.lastMarker.column+1;this.errorHandler.tolerateError(s,a,u,o)},t.prototype.unexpectedTokenError=function(t,e){var n,r=e||o.Messages.UnexpectedToken;if(t?(e||(r=2===t.type?o.Messages.UnexpectedEOS:3===t.type?o.Messages.UnexpectedIdentifier:6===t.type?o.Messages.UnexpectedNumber:8===t.type?o.Messages.UnexpectedString:10===t.type?o.Messages.UnexpectedTemplate:o.Messages.UnexpectedToken,4===t.type&&(this.scanner.isFutureReservedWord(t.value)?r=o.Messages.UnexpectedReserved:this.context.strict&&this.scanner.isStrictModeReservedWord(t.value)&&(r=o.Messages.StrictReservedWord))),n=t.value):n="ILLEGAL",r=r.replace("%0",n),t&&"number"==typeof t.lineNumber){var i=t.start,s=t.lineNumber,a=this.lastMarker.index-this.lastMarker.column,u=t.start-a+1;return this.errorHandler.createError(i,s,u,r)}i=this.lastMarker.index,s=this.lastMarker.line,u=this.lastMarker.column+1;return this.errorHandler.createError(i,s,u,r)},t.prototype.throwUnexpectedToken=function(t,e){throw this.unexpectedTokenError(t,e)},t.prototype.tolerateUnexpectedToken=function(t,e){this.errorHandler.tolerate(this.unexpectedTokenError(t,e))},t.prototype.collectComments=function(){if(this.config.comment){var t=this.scanner.scanComments();if(t.length>0&&this.delegate)for(var e=0;e<t.length;++e){var n=t[e],r=void 0;r={type:n.multiLine?"BlockComment":"LineComment",value:this.scanner.source.slice(n.slice[0],n.slice[1])},this.config.range&&(r.range=n.range),this.config.loc&&(r.loc=n.loc);var i={start:{line:n.loc.start.line,column:n.loc.start.column,offset:n.range[0]},end:{line:n.loc.end.line,column:n.loc.end.column,offset:n.range[1]}};this.delegate(r,i)}}else this.scanner.scanComments()},t.prototype.getTokenRaw=function(t){return this.scanner.source.slice(t.start,t.end)},t.prototype.convertToken=function(t){var e={type:c.TokenName[t.type],value:this.getTokenRaw(t)};if(this.config.range&&(e.range=[t.start,t.end]),this.config.loc&&(e.loc={start:{line:this.startMarker.line,column:this.startMarker.column},end:{line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}}),9===t.type){var n=t.pattern,r=t.flags;e.regex={pattern:n,flags:r}}return e},t.prototype.nextToken=function(){var t=this.lookahead;this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart,this.collectComments(),this.scanner.index!==this.startMarker.index&&(this.startMarker.index=this.scanner.index,this.startMarker.line=this.scanner.lineNumber,this.startMarker.column=this.scanner.index-this.scanner.lineStart);var e=this.scanner.lex();return this.hasLineTerminator=t.lineNumber!==e.lineNumber,e&&this.context.strict&&3===e.type&&this.scanner.isStrictModeReservedWord(e.value)&&(e.type=4),this.lookahead=e,this.config.tokens&&2!==e.type&&this.tokens.push(this.convertToken(e)),t},t.prototype.nextRegexToken=function(){this.collectComments();var t=this.scanner.scanRegExp();return this.config.tokens&&(this.tokens.pop(),this.tokens.push(this.convertToken(t))),this.lookahead=t,this.nextToken(),t},t.prototype.createNode=function(){return{index:this.startMarker.index,line:this.startMarker.line,column:this.startMarker.column}},t.prototype.startNode=function(t){return{index:t.start,line:t.lineNumber,column:t.start-t.lineStart}},t.prototype.finalize=function(t,e){if(this.config.range&&(e.range=[t.index,this.lastMarker.index]),this.config.loc&&(e.loc={start:{line:t.line,column:t.column},end:{line:this.lastMarker.line,column:this.lastMarker.column}},this.config.source&&(e.loc.source=this.config.source)),this.delegate){var n={start:{line:t.line,column:t.column,offset:t.index},end:{line:this.lastMarker.line,column:this.lastMarker.column,offset:this.lastMarker.index}};this.delegate(e,n)}return e},t.prototype.expect=function(t){var e=this.nextToken();7===e.type&&e.value===t||this.throwUnexpectedToken(e)},t.prototype.expectCommaSeparator=function(){if(this.config.tolerant){var t=this.lookahead;7===t.type&&","===t.value?this.nextToken():7===t.type&&";"===t.value?(this.nextToken(),this.tolerateUnexpectedToken(t)):this.tolerateUnexpectedToken(t,o.Messages.UnexpectedToken)}else this.expect(",")},t.prototype.expectKeyword=function(t){var e=this.nextToken();4===e.type&&e.value===t||this.throwUnexpectedToken(e)},t.prototype.match=function(t){return 7===this.lookahead.type&&this.lookahead.value===t},t.prototype.matchKeyword=function(t){return 4===this.lookahead.type&&this.lookahead.value===t},t.prototype.matchContextualKeyword=function(t){return 3===this.lookahead.type&&this.lookahead.value===t},t.prototype.matchAssign=function(){if(7!==this.lookahead.type)return!1;var t=this.lookahead.value;return"="===t||"*="===t||"**="===t||"/="===t||"%="===t||"+="===t||"-="===t||"<<="===t||">>="===t||">>>="===t||"&="===t||"^="===t||"|="===t},t.prototype.isolateCoverGrammar=function(t){var e=this.context.isBindingElement,n=this.context.isAssignmentTarget,r=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var i=t.call(this);return null!==this.context.firstCoverInitializedNameError&&this.throwUnexpectedToken(this.context.firstCoverInitializedNameError),this.context.isBindingElement=e,this.context.isAssignmentTarget=n,this.context.firstCoverInitializedNameError=r,i},t.prototype.inheritCoverGrammar=function(t){var e=this.context.isBindingElement,n=this.context.isAssignmentTarget,r=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var i=t.call(this);return this.context.isBindingElement=this.context.isBindingElement&&e,this.context.isAssignmentTarget=this.context.isAssignmentTarget&&n,this.context.firstCoverInitializedNameError=r||this.context.firstCoverInitializedNameError,i},t.prototype.consumeSemicolon=function(){this.match(";")?this.nextToken():this.hasLineTerminator||(2===this.lookahead.type||this.match("}")||this.throwUnexpectedToken(this.lookahead),this.lastMarker.index=this.startMarker.index,this.lastMarker.line=this.startMarker.line,this.lastMarker.column=this.startMarker.column)},t.prototype.parsePrimaryExpression=function(){var t,e,n,r=this.createNode();switch(this.lookahead.type){case 3:(this.context.isModule||this.context.await)&&"await"===this.lookahead.value&&this.tolerateUnexpectedToken(this.lookahead),t=this.matchAsyncFunction()?this.parseFunctionExpression():this.finalize(r,new s.Identifier(this.nextToken().value));break;case 6:case 8:this.context.strict&&this.lookahead.octal&&this.tolerateUnexpectedToken(this.lookahead,o.Messages.StrictOctalLiteral),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,e=this.nextToken(),n=this.getTokenRaw(e),t=this.finalize(r,new s.Literal(e.value,n));break;case 1:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,e=this.nextToken(),n=this.getTokenRaw(e),t=this.finalize(r,new s.Literal("true"===e.value,n));break;case 5:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,e=this.nextToken(),n=this.getTokenRaw(e),t=this.finalize(r,new s.Literal(null,n));break;case 10:t=this.parseTemplateLiteral();break;case 7:switch(this.lookahead.value){case"(":this.context.isBindingElement=!1,t=this.inheritCoverGrammar(this.parseGroupExpression);break;case"[":t=this.inheritCoverGrammar(this.parseArrayInitializer);break;case"{":t=this.inheritCoverGrammar(this.parseObjectInitializer);break;case"/":case"/=":this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.scanner.index=this.startMarker.index,e=this.nextRegexToken(),n=this.getTokenRaw(e),t=this.finalize(r,new s.RegexLiteral(e.regex,n,e.pattern,e.flags));break;default:t=this.throwUnexpectedToken(this.nextToken())}break;case 4:!this.context.strict&&this.context.allowYield&&this.matchKeyword("yield")?t=this.parseIdentifierName():!this.context.strict&&this.matchKeyword("let")?t=this.finalize(r,new s.Identifier(this.nextToken().value)):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.matchKeyword("function")?t=this.parseFunctionExpression():this.matchKeyword("this")?(this.nextToken(),t=this.finalize(r,new s.ThisExpression)):t=this.matchKeyword("class")?this.parseClassExpression():this.throwUnexpectedToken(this.nextToken()));break;default:t=this.throwUnexpectedToken(this.nextToken())}return t},t.prototype.parseSpreadElement=function(){var t=this.createNode();this.expect("...");var e=this.inheritCoverGrammar(this.parseAssignmentExpression);return this.finalize(t,new s.SpreadElement(e))},t.prototype.parseArrayInitializer=function(){var t=this.createNode(),e=[];for(this.expect("[");!this.match("]");)if(this.match(","))this.nextToken(),e.push(null);else if(this.match("...")){var n=this.parseSpreadElement();this.match("]")||(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.expect(",")),e.push(n)}else e.push(this.inheritCoverGrammar(this.parseAssignmentExpression)),this.match("]")||this.expect(",");return this.expect("]"),this.finalize(t,new s.ArrayExpression(e))},t.prototype.parsePropertyMethod=function(t){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var e=this.context.strict,n=this.context.allowStrictDirective;this.context.allowStrictDirective=t.simple;var r=this.isolateCoverGrammar(this.parseFunctionSourceElements);return this.context.strict&&t.firstRestricted&&this.tolerateUnexpectedToken(t.firstRestricted,t.message),this.context.strict&&t.stricted&&this.tolerateUnexpectedToken(t.stricted,t.message),this.context.strict=e,this.context.allowStrictDirective=n,r},t.prototype.parsePropertyMethodFunction=function(){var t=this.createNode(),e=this.context.allowYield;this.context.allowYield=!1;var n=this.parseFormalParameters(),r=this.parsePropertyMethod(n);return this.context.allowYield=e,this.finalize(t,new s.FunctionExpression(null,n.params,r,!1))},t.prototype.parsePropertyMethodAsyncFunction=function(){var t=this.createNode(),e=this.context.allowYield,n=this.context.await;this.context.allowYield=!1,this.context.await=!0;var r=this.parseFormalParameters(),i=this.parsePropertyMethod(r);return this.context.allowYield=e,this.context.await=n,this.finalize(t,new s.AsyncFunctionExpression(null,r.params,i))},t.prototype.parseObjectPropertyKey=function(){var t,e=this.createNode(),n=this.nextToken();switch(n.type){case 8:case 6:this.context.strict&&n.octal&&this.tolerateUnexpectedToken(n,o.Messages.StrictOctalLiteral);var r=this.getTokenRaw(n);t=this.finalize(e,new s.Literal(n.value,r));break;case 3:case 1:case 5:case 4:t=this.finalize(e,new s.Identifier(n.value));break;case 7:"["===n.value?(t=this.isolateCoverGrammar(this.parseAssignmentExpression),this.expect("]")):t=this.throwUnexpectedToken(n);break;default:t=this.throwUnexpectedToken(n)}return t},t.prototype.isPropertyKey=function(t,e){return t.type===u.Syntax.Identifier&&t.name===e||t.type===u.Syntax.Literal&&t.value===e},t.prototype.parseObjectProperty=function(t){var e,n=this.createNode(),r=this.lookahead,i=null,a=null,u=!1,c=!1,l=!1,h=!1;if(3===r.type){var f=r.value;this.nextToken(),u=this.match("["),i=(h=!(this.hasLineTerminator||"async"!==f||this.match(":")||this.match("(")||this.match("*")))?this.parseObjectPropertyKey():this.finalize(n,new s.Identifier(f))}else this.match("*")?this.nextToken():(u=this.match("["),i=this.parseObjectPropertyKey());var p=this.qualifiedPropertyName(this.lookahead);if(3===r.type&&!h&&"get"===r.value&&p)e="get",u=this.match("["),i=this.parseObjectPropertyKey(),this.context.allowYield=!1,a=this.parseGetterMethod();else if(3===r.type&&!h&&"set"===r.value&&p)e="set",u=this.match("["),i=this.parseObjectPropertyKey(),a=this.parseSetterMethod();else if(7===r.type&&"*"===r.value&&p)e="init",u=this.match("["),i=this.parseObjectPropertyKey(),a=this.parseGeneratorMethod(),c=!0;else if(i||this.throwUnexpectedToken(this.lookahead),e="init",this.match(":")&&!h)!u&&this.isPropertyKey(i,"__proto__")&&(t.value&&this.tolerateError(o.Messages.DuplicateProtoProperty),t.value=!0),this.nextToken(),a=this.inheritCoverGrammar(this.parseAssignmentExpression);else if(this.match("("))a=h?this.parsePropertyMethodAsyncFunction():this.parsePropertyMethodFunction(),c=!0;else if(3===r.type){f=this.finalize(n,new s.Identifier(r.value));if(this.match("=")){this.context.firstCoverInitializedNameError=this.lookahead,this.nextToken(),l=!0;var d=this.isolateCoverGrammar(this.parseAssignmentExpression);a=this.finalize(n,new s.AssignmentPattern(f,d))}else l=!0,a=f}else this.throwUnexpectedToken(this.nextToken());return this.finalize(n,new s.Property(e,i,u,a,c,l))},t.prototype.parseObjectInitializer=function(){var t=this.createNode();this.expect("{");for(var e=[],n={value:!1};!this.match("}");)e.push(this.parseObjectProperty(n)),this.match("}")||this.expectCommaSeparator();return this.expect("}"),this.finalize(t,new s.ObjectExpression(e))},t.prototype.parseTemplateHead=function(){r.assert(this.lookahead.head,"Template literal must start with a template head");var t=this.createNode(),e=this.nextToken(),n=e.value,i=e.cooked;return this.finalize(t,new s.TemplateElement({raw:n,cooked:i},e.tail))},t.prototype.parseTemplateElement=function(){10!==this.lookahead.type&&this.throwUnexpectedToken();var t=this.createNode(),e=this.nextToken(),n=e.value,r=e.cooked;return this.finalize(t,new s.TemplateElement({raw:n,cooked:r},e.tail))},t.prototype.parseTemplateLiteral=function(){var t=this.createNode(),e=[],n=[],r=this.parseTemplateHead();for(n.push(r);!r.tail;)e.push(this.parseExpression()),r=this.parseTemplateElement(),n.push(r);return this.finalize(t,new s.TemplateLiteral(n,e))},t.prototype.reinterpretExpressionAsPattern=function(t){switch(t.type){case u.Syntax.Identifier:case u.Syntax.MemberExpression:case u.Syntax.RestElement:case u.Syntax.AssignmentPattern:break;case u.Syntax.SpreadElement:t.type=u.Syntax.RestElement,this.reinterpretExpressionAsPattern(t.argument);break;case u.Syntax.ArrayExpression:t.type=u.Syntax.ArrayPattern;for(var e=0;e<t.elements.length;e++)null!==t.elements[e]&&this.reinterpretExpressionAsPattern(t.elements[e]);break;case u.Syntax.ObjectExpression:t.type=u.Syntax.ObjectPattern;for(e=0;e<t.properties.length;e++)this.reinterpretExpressionAsPattern(t.properties[e].value);break;case u.Syntax.AssignmentExpression:t.type=u.Syntax.AssignmentPattern,delete t.operator,this.reinterpretExpressionAsPattern(t.left)}},t.prototype.parseGroupExpression=function(){var t;if(this.expect("("),this.match(")"))this.nextToken(),this.match("=>")||this.expect("=>"),t={type:"ArrowParameterPlaceHolder",params:[],async:!1};else{var e=this.lookahead,n=[];if(this.match("..."))t=this.parseRestElement(n),this.expect(")"),this.match("=>")||this.expect("=>"),t={type:"ArrowParameterPlaceHolder",params:[t],async:!1};else{var r=!1;if(this.context.isBindingElement=!0,t=this.inheritCoverGrammar(this.parseAssignmentExpression),this.match(",")){var i=[];for(this.context.isAssignmentTarget=!1,i.push(t);2!==this.lookahead.type&&this.match(",");){if(this.nextToken(),this.match(")")){this.nextToken();for(var o=0;o<i.length;o++)this.reinterpretExpressionAsPattern(i[o]);r=!0,t={type:"ArrowParameterPlaceHolder",params:i,async:!1}}else if(this.match("...")){this.context.isBindingElement||this.throwUnexpectedToken(this.lookahead),i.push(this.parseRestElement(n)),this.expect(")"),this.match("=>")||this.expect("=>"),this.context.isBindingElement=!1;for(o=0;o<i.length;o++)this.reinterpretExpressionAsPattern(i[o]);r=!0,t={type:"ArrowParameterPlaceHolder",params:i,async:!1}}else i.push(this.inheritCoverGrammar(this.parseAssignmentExpression));if(r)break}r||(t=this.finalize(this.startNode(e),new s.SequenceExpression(i)))}if(!r){if(this.expect(")"),this.match("=>")&&(t.type===u.Syntax.Identifier&&"yield"===t.name&&(r=!0,t={type:"ArrowParameterPlaceHolder",params:[t],async:!1}),!r)){if(this.context.isBindingElement||this.throwUnexpectedToken(this.lookahead),t.type===u.Syntax.SequenceExpression)for(o=0;o<t.expressions.length;o++)this.reinterpretExpressionAsPattern(t.expressions[o]);else this.reinterpretExpressionAsPattern(t);t={type:"ArrowParameterPlaceHolder",params:t.type===u.Syntax.SequenceExpression?t.expressions:[t],async:!1}}this.context.isBindingElement=!1}}}return t},t.prototype.parseArguments=function(){this.expect("(");var t=[];if(!this.match(")"))for(;;){var e=this.match("...")?this.parseSpreadElement():this.isolateCoverGrammar(this.parseAssignmentExpression);if(t.push(e),this.match(")"))break;if(this.expectCommaSeparator(),this.match(")"))break}return this.expect(")"),t},t.prototype.isIdentifierName=function(t){return 3===t.type||4===t.type||1===t.type||5===t.type},t.prototype.parseIdentifierName=function(){var t=this.createNode(),e=this.nextToken();return this.isIdentifierName(e)||this.throwUnexpectedToken(e),this.finalize(t,new s.Identifier(e.value))},t.prototype.parseNewExpression=function(){var t,e=this.createNode(),n=this.parseIdentifierName();if(r.assert("new"===n.name,"New expression must start with `new`"),this.match("."))if(this.nextToken(),3===this.lookahead.type&&this.context.inFunctionBody&&"target"===this.lookahead.value){var i=this.parseIdentifierName();t=new s.MetaProperty(n,i)}else this.throwUnexpectedToken(this.lookahead);else{var o=this.isolateCoverGrammar(this.parseLeftHandSideExpression),a=this.match("(")?this.parseArguments():[];t=new s.NewExpression(o,a),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}return this.finalize(e,t)},t.prototype.parseAsyncArgument=function(){var t=this.parseAssignmentExpression();return this.context.firstCoverInitializedNameError=null,t},t.prototype.parseAsyncArguments=function(){this.expect("(");var t=[];if(!this.match(")"))for(;;){var e=this.match("...")?this.parseSpreadElement():this.isolateCoverGrammar(this.parseAsyncArgument);if(t.push(e),this.match(")"))break;if(this.expectCommaSeparator(),this.match(")"))break}return this.expect(")"),t},t.prototype.parseLeftHandSideExpressionAllowCall=function(){var t,e=this.lookahead,n=this.matchContextualKeyword("async"),r=this.context.allowIn;for(this.context.allowIn=!0,this.matchKeyword("super")&&this.context.inFunctionBody?(t=this.createNode(),this.nextToken(),t=this.finalize(t,new s.Super),this.match("(")||this.match(".")||this.match("[")||this.throwUnexpectedToken(this.lookahead)):t=this.inheritCoverGrammar(this.matchKeyword("new")?this.parseNewExpression:this.parsePrimaryExpression);;)if(this.match(".")){this.context.isBindingElement=!1,this.context.isAssignmentTarget=!0,this.expect(".");var i=this.parseIdentifierName();t=this.finalize(this.startNode(e),new s.StaticMemberExpression(t,i))}else if(this.match("(")){var o=n&&e.lineNumber===this.lookahead.lineNumber;this.context.isBindingElement=!1,this.context.isAssignmentTarget=!1;var a=o?this.parseAsyncArguments():this.parseArguments();if(t=this.finalize(this.startNode(e),new s.CallExpression(t,a)),o&&this.match("=>")){for(var u=0;u<a.length;++u)this.reinterpretExpressionAsPattern(a[u]);t={type:"ArrowParameterPlaceHolder",params:a,async:!0}}}else if(this.match("[")){this.context.isBindingElement=!1,this.context.isAssignmentTarget=!0,this.expect("[");i=this.isolateCoverGrammar(this.parseExpression);this.expect("]"),t=this.finalize(this.startNode(e),new s.ComputedMemberExpression(t,i))}else{if(10!==this.lookahead.type||!this.lookahead.head)break;var c=this.parseTemplateLiteral();t=this.finalize(this.startNode(e),new s.TaggedTemplateExpression(t,c))}return this.context.allowIn=r,t},t.prototype.parseSuper=function(){var t=this.createNode();return this.expectKeyword("super"),this.match("[")||this.match(".")||this.throwUnexpectedToken(this.lookahead),this.finalize(t,new s.Super)},t.prototype.parseLeftHandSideExpression=function(){r.assert(this.context.allowIn,"callee of new expression always allow in keyword.");for(var t=this.startNode(this.lookahead),e=this.matchKeyword("super")&&this.context.inFunctionBody?this.parseSuper():this.inheritCoverGrammar(this.matchKeyword("new")?this.parseNewExpression:this.parsePrimaryExpression);;)if(this.match("[")){this.context.isBindingElement=!1,this.context.isAssignmentTarget=!0,this.expect("[");var n=this.isolateCoverGrammar(this.parseExpression);this.expect("]"),e=this.finalize(t,new s.ComputedMemberExpression(e,n))}else if(this.match(".")){this.context.isBindingElement=!1,this.context.isAssignmentTarget=!0,this.expect(".");n=this.parseIdentifierName();e=this.finalize(t,new s.StaticMemberExpression(e,n))}else{if(10!==this.lookahead.type||!this.lookahead.head)break;var i=this.parseTemplateLiteral();e=this.finalize(t,new s.TaggedTemplateExpression(e,i))}return e},t.prototype.parseUpdateExpression=function(){var t,e=this.lookahead;if(this.match("++")||this.match("--")){var n=this.startNode(e),r=this.nextToken();t=this.inheritCoverGrammar(this.parseUnaryExpression),this.context.strict&&t.type===u.Syntax.Identifier&&this.scanner.isRestrictedWord(t.name)&&this.tolerateError(o.Messages.StrictLHSPrefix),this.context.isAssignmentTarget||this.tolerateError(o.Messages.InvalidLHSInAssignment);var i=!0;t=this.finalize(n,new s.UpdateExpression(r.value,t,i)),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}else if(t=this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall),!this.hasLineTerminator&&7===this.lookahead.type&&(this.match("++")||this.match("--"))){this.context.strict&&t.type===u.Syntax.Identifier&&this.scanner.isRestrictedWord(t.name)&&this.tolerateError(o.Messages.StrictLHSPostfix),this.context.isAssignmentTarget||this.tolerateError(o.Messages.InvalidLHSInAssignment),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var a=this.nextToken().value;i=!1;t=this.finalize(this.startNode(e),new s.UpdateExpression(a,t,i))}return t},t.prototype.parseAwaitExpression=function(){var t=this.createNode();this.nextToken();var e=this.parseUnaryExpression();return this.finalize(t,new s.AwaitExpression(e))},t.prototype.parseUnaryExpression=function(){var t;if(this.match("+")||this.match("-")||this.match("~")||this.match("!")||this.matchKeyword("delete")||this.matchKeyword("void")||this.matchKeyword("typeof")){var e=this.startNode(this.lookahead),n=this.nextToken();t=this.inheritCoverGrammar(this.parseUnaryExpression),t=this.finalize(e,new s.UnaryExpression(n.value,t)),this.context.strict&&"delete"===t.operator&&t.argument.type===u.Syntax.Identifier&&this.tolerateError(o.Messages.StrictDelete),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}else t=this.context.await&&this.matchContextualKeyword("await")?this.parseAwaitExpression():this.parseUpdateExpression();return t},t.prototype.parseExponentiationExpression=function(){var t=this.lookahead,e=this.inheritCoverGrammar(this.parseUnaryExpression);if(e.type!==u.Syntax.UnaryExpression&&this.match("**")){this.nextToken(),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var n=e,r=this.isolateCoverGrammar(this.parseExponentiationExpression);e=this.finalize(this.startNode(t),new s.BinaryExpression("**",n,r))}return e},t.prototype.binaryPrecedence=function(t){var e=t.value;return 7===t.type?this.operatorPrecedence[e]||0:4===t.type&&("instanceof"===e||this.context.allowIn&&"in"===e)?7:0},t.prototype.parseBinaryExpression=function(){var t=this.lookahead,e=this.inheritCoverGrammar(this.parseExponentiationExpression),n=this.lookahead,r=this.binaryPrecedence(n);if(r>0){this.nextToken(),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;for(var i=[t,this.lookahead],o=e,a=this.isolateCoverGrammar(this.parseExponentiationExpression),u=[o,n.value,a],c=[r];!((r=this.binaryPrecedence(this.lookahead))<=0);){for(;u.length>2&&r<=c[c.length-1];){a=u.pop();var l=u.pop();c.pop(),o=u.pop(),i.pop();var h=this.startNode(i[i.length-1]);u.push(this.finalize(h,new s.BinaryExpression(l,o,a)))}u.push(this.nextToken().value),c.push(r),i.push(this.lookahead),u.push(this.isolateCoverGrammar(this.parseExponentiationExpression))}var f=u.length-1;for(e=u[f],i.pop();f>1;){h=this.startNode(i.pop()),l=u[f-1];e=this.finalize(h,new s.BinaryExpression(l,u[f-2],e)),f-=2}}return e},t.prototype.parseConditionalExpression=function(){var t=this.lookahead,e=this.inheritCoverGrammar(this.parseBinaryExpression);if(this.match("?")){this.nextToken();var n=this.context.allowIn;this.context.allowIn=!0;var r=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowIn=n,this.expect(":");var i=this.isolateCoverGrammar(this.parseAssignmentExpression);e=this.finalize(this.startNode(t),new s.ConditionalExpression(e,r,i)),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}return e},t.prototype.checkPatternParam=function(t,e){switch(e.type){case u.Syntax.Identifier:this.validateParam(t,e,e.name);break;case u.Syntax.RestElement:this.checkPatternParam(t,e.argument);break;case u.Syntax.AssignmentPattern:this.checkPatternParam(t,e.left);break;case u.Syntax.ArrayPattern:for(var n=0;n<e.elements.length;n++)null!==e.elements[n]&&this.checkPatternParam(t,e.elements[n]);break;case u.Syntax.ObjectPattern:for(n=0;n<e.properties.length;n++)this.checkPatternParam(t,e.properties[n].value)}t.simple=t.simple&&e instanceof s.Identifier},t.prototype.reinterpretAsCoverFormalsList=function(t){var e,n=[t],r=!1;switch(t.type){case u.Syntax.Identifier:break;case"ArrowParameterPlaceHolder":n=t.params,r=t.async;break;default:return null}e={simple:!0,paramSet:{}};for(var i=0;i<n.length;++i){(s=n[i]).type===u.Syntax.AssignmentPattern?s.right.type===u.Syntax.YieldExpression&&(s.right.argument&&this.throwUnexpectedToken(this.lookahead),s.right.type=u.Syntax.Identifier,s.right.name="yield",delete s.right.argument,delete s.right.delegate):r&&s.type===u.Syntax.Identifier&&"await"===s.name&&this.throwUnexpectedToken(this.lookahead),this.checkPatternParam(e,s),n[i]=s}if(this.context.strict||!this.context.allowYield)for(i=0;i<n.length;++i){var s;(s=n[i]).type===u.Syntax.YieldExpression&&this.throwUnexpectedToken(this.lookahead)}if(e.message===o.Messages.StrictParamDupe){var a=this.context.strict?e.stricted:e.firstRestricted;this.throwUnexpectedToken(a,e.message)}return{simple:e.simple,params:n,stricted:e.stricted,firstRestricted:e.firstRestricted,message:e.message}},t.prototype.parseAssignmentExpression=function(){var t;if(!this.context.allowYield&&this.matchKeyword("yield"))t=this.parseYieldExpression();else{var e=this.lookahead,n=e;if(t=this.parseConditionalExpression(),3===n.type&&n.lineNumber===this.lookahead.lineNumber&&"async"===n.value&&(3===this.lookahead.type||this.matchKeyword("yield"))){var r=this.parsePrimaryExpression();this.reinterpretExpressionAsPattern(r),t={type:"ArrowParameterPlaceHolder",params:[r],async:!0}}if("ArrowParameterPlaceHolder"===t.type||this.match("=>")){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var i=t.async,a=this.reinterpretAsCoverFormalsList(t);if(a){this.hasLineTerminator&&this.tolerateUnexpectedToken(this.lookahead),this.context.firstCoverInitializedNameError=null;var c=this.context.strict,l=this.context.allowStrictDirective;this.context.allowStrictDirective=a.simple;var h=this.context.allowYield,f=this.context.await;this.context.allowYield=!0,this.context.await=i;var p=this.startNode(e);this.expect("=>");var d=void 0;if(this.match("{")){var m=this.context.allowIn;this.context.allowIn=!0,d=this.parseFunctionSourceElements(),this.context.allowIn=m}else d=this.isolateCoverGrammar(this.parseAssignmentExpression);var v=d.type!==u.Syntax.BlockStatement;this.context.strict&&a.firstRestricted&&this.throwUnexpectedToken(a.firstRestricted,a.message),this.context.strict&&a.stricted&&this.tolerateUnexpectedToken(a.stricted,a.message),t=i?this.finalize(p,new s.AsyncArrowFunctionExpression(a.params,d,v)):this.finalize(p,new s.ArrowFunctionExpression(a.params,d,v)),this.context.strict=c,this.context.allowStrictDirective=l,this.context.allowYield=h,this.context.await=f}}else if(this.matchAssign()){if(this.context.isAssignmentTarget||this.tolerateError(o.Messages.InvalidLHSInAssignment),this.context.strict&&t.type===u.Syntax.Identifier){var y=t;this.scanner.isRestrictedWord(y.name)&&this.tolerateUnexpectedToken(n,o.Messages.StrictLHSAssignment),this.scanner.isStrictModeReservedWord(y.name)&&this.tolerateUnexpectedToken(n,o.Messages.StrictReservedWord)}this.match("=")?this.reinterpretExpressionAsPattern(t):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1);var g=(n=this.nextToken()).value,x=this.isolateCoverGrammar(this.parseAssignmentExpression);t=this.finalize(this.startNode(e),new s.AssignmentExpression(g,t,x)),this.context.firstCoverInitializedNameError=null}}return t},t.prototype.parseExpression=function(){var t=this.lookahead,e=this.isolateCoverGrammar(this.parseAssignmentExpression);if(this.match(",")){var n=[];for(n.push(e);2!==this.lookahead.type&&this.match(",");)this.nextToken(),n.push(this.isolateCoverGrammar(this.parseAssignmentExpression));e=this.finalize(this.startNode(t),new s.SequenceExpression(n))}return e},t.prototype.parseStatementListItem=function(){var t;if(this.context.isAssignmentTarget=!0,this.context.isBindingElement=!0,4===this.lookahead.type)switch(this.lookahead.value){case"export":this.context.isModule||this.tolerateUnexpectedToken(this.lookahead,o.Messages.IllegalExportDeclaration),t=this.parseExportDeclaration();break;case"import":this.context.isModule||this.tolerateUnexpectedToken(this.lookahead,o.Messages.IllegalImportDeclaration),t=this.parseImportDeclaration();break;case"const":t=this.parseLexicalDeclaration({inFor:!1});break;case"function":t=this.parseFunctionDeclaration();break;case"class":t=this.parseClassDeclaration();break;case"let":t=this.isLexicalDeclaration()?this.parseLexicalDeclaration({inFor:!1}):this.parseStatement();break;default:t=this.parseStatement()}else t=this.parseStatement();return t},t.prototype.parseBlock=function(){var t=this.createNode();this.expect("{");for(var e=[];!this.match("}");)e.push(this.parseStatementListItem());return this.expect("}"),this.finalize(t,new s.BlockStatement(e))},t.prototype.parseLexicalBinding=function(t,e){var n=this.createNode(),r=this.parsePattern([],t);this.context.strict&&r.type===u.Syntax.Identifier&&this.scanner.isRestrictedWord(r.name)&&this.tolerateError(o.Messages.StrictVarName);var i=null;return"const"===t?this.matchKeyword("in")||this.matchContextualKeyword("of")||(this.match("=")?(this.nextToken(),i=this.isolateCoverGrammar(this.parseAssignmentExpression)):this.throwError(o.Messages.DeclarationMissingInitializer,"const")):(!e.inFor&&r.type!==u.Syntax.Identifier||this.match("="))&&(this.expect("="),i=this.isolateCoverGrammar(this.parseAssignmentExpression)),this.finalize(n,new s.VariableDeclarator(r,i))},t.prototype.parseBindingList=function(t,e){for(var n=[this.parseLexicalBinding(t,e)];this.match(",");)this.nextToken(),n.push(this.parseLexicalBinding(t,e));return n},t.prototype.isLexicalDeclaration=function(){var t=this.scanner.saveState();this.scanner.scanComments();var e=this.scanner.lex();return this.scanner.restoreState(t),3===e.type||7===e.type&&"["===e.value||7===e.type&&"{"===e.value||4===e.type&&"let"===e.value||4===e.type&&"yield"===e.value},t.prototype.parseLexicalDeclaration=function(t){var e=this.createNode(),n=this.nextToken().value;r.assert("let"===n||"const"===n,"Lexical declaration must be either let or const");var i=this.parseBindingList(n,t);return this.consumeSemicolon(),this.finalize(e,new s.VariableDeclaration(i,n))},t.prototype.parseBindingRestElement=function(t,e){var n=this.createNode();this.expect("...");var r=this.parsePattern(t,e);return this.finalize(n,new s.RestElement(r))},t.prototype.parseArrayPattern=function(t,e){var n=this.createNode();this.expect("[");for(var r=[];!this.match("]");)if(this.match(","))this.nextToken(),r.push(null);else{if(this.match("...")){r.push(this.parseBindingRestElement(t,e));break}r.push(this.parsePatternWithDefault(t,e)),this.match("]")||this.expect(",")}return this.expect("]"),this.finalize(n,new s.ArrayPattern(r))},t.prototype.parsePropertyPattern=function(t,e){var n,r,i=this.createNode(),o=!1,a=!1;if(3===this.lookahead.type){var u=this.lookahead;n=this.parseVariableIdentifier();var c=this.finalize(i,new s.Identifier(u.value));if(this.match("=")){t.push(u),a=!0,this.nextToken();var l=this.parseAssignmentExpression();r=this.finalize(this.startNode(u),new s.AssignmentPattern(c,l))}else this.match(":")?(this.expect(":"),r=this.parsePatternWithDefault(t,e)):(t.push(u),a=!0,r=c)}else o=this.match("["),n=this.parseObjectPropertyKey(),this.expect(":"),r=this.parsePatternWithDefault(t,e);return this.finalize(i,new s.Property("init",n,o,r,!1,a))},t.prototype.parseObjectPattern=function(t,e){var n=this.createNode(),r=[];for(this.expect("{");!this.match("}");)r.push(this.parsePropertyPattern(t,e)),this.match("}")||this.expect(",");return this.expect("}"),this.finalize(n,new s.ObjectPattern(r))},t.prototype.parsePattern=function(t,e){var n;return this.match("[")?n=this.parseArrayPattern(t,e):this.match("{")?n=this.parseObjectPattern(t,e):(!this.matchKeyword("let")||"const"!==e&&"let"!==e||this.tolerateUnexpectedToken(this.lookahead,o.Messages.LetInLexicalBinding),t.push(this.lookahead),n=this.parseVariableIdentifier(e)),n},t.prototype.parsePatternWithDefault=function(t,e){var n=this.lookahead,r=this.parsePattern(t,e);if(this.match("=")){this.nextToken();var i=this.context.allowYield;this.context.allowYield=!0;var o=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowYield=i,r=this.finalize(this.startNode(n),new s.AssignmentPattern(r,o))}return r},t.prototype.parseVariableIdentifier=function(t){var e=this.createNode(),n=this.nextToken();return 4===n.type&&"yield"===n.value?this.context.strict?this.tolerateUnexpectedToken(n,o.Messages.StrictReservedWord):this.context.allowYield||this.throwUnexpectedToken(n):3!==n.type?this.context.strict&&4===n.type&&this.scanner.isStrictModeReservedWord(n.value)?this.tolerateUnexpectedToken(n,o.Messages.StrictReservedWord):(this.context.strict||"let"!==n.value||"var"!==t)&&this.throwUnexpectedToken(n):(this.context.isModule||this.context.await)&&3===n.type&&"await"===n.value&&this.tolerateUnexpectedToken(n),this.finalize(e,new s.Identifier(n.value))},t.prototype.parseVariableDeclaration=function(t){var e=this.createNode(),n=this.parsePattern([],"var");this.context.strict&&n.type===u.Syntax.Identifier&&this.scanner.isRestrictedWord(n.name)&&this.tolerateError(o.Messages.StrictVarName);var r=null;return this.match("=")?(this.nextToken(),r=this.isolateCoverGrammar(this.parseAssignmentExpression)):n.type===u.Syntax.Identifier||t.inFor||this.expect("="),this.finalize(e,new s.VariableDeclarator(n,r))},t.prototype.parseVariableDeclarationList=function(t){var e={inFor:t.inFor},n=[];for(n.push(this.parseVariableDeclaration(e));this.match(",");)this.nextToken(),n.push(this.parseVariableDeclaration(e));return n},t.prototype.parseVariableStatement=function(){var t=this.createNode();this.expectKeyword("var");var e=this.parseVariableDeclarationList({inFor:!1});return this.consumeSemicolon(),this.finalize(t,new s.VariableDeclaration(e,"var"))},t.prototype.parseEmptyStatement=function(){var t=this.createNode();return this.expect(";"),this.finalize(t,new s.EmptyStatement)},t.prototype.parseExpressionStatement=function(){var t=this.createNode(),e=this.parseExpression();return this.consumeSemicolon(),this.finalize(t,new s.ExpressionStatement(e))},t.prototype.parseIfClause=function(){return this.context.strict&&this.matchKeyword("function")&&this.tolerateError(o.Messages.StrictFunction),this.parseStatement()},t.prototype.parseIfStatement=function(){var t,e=this.createNode(),n=null;this.expectKeyword("if"),this.expect("(");var r=this.parseExpression();return!this.match(")")&&this.config.tolerant?(this.tolerateUnexpectedToken(this.nextToken()),t=this.finalize(this.createNode(),new s.EmptyStatement)):(this.expect(")"),t=this.parseIfClause(),this.matchKeyword("else")&&(this.nextToken(),n=this.parseIfClause())),this.finalize(e,new s.IfStatement(r,t,n))},t.prototype.parseDoWhileStatement=function(){var t=this.createNode();this.expectKeyword("do");var e=this.context.inIteration;this.context.inIteration=!0;var n=this.parseStatement();this.context.inIteration=e,this.expectKeyword("while"),this.expect("(");var r=this.parseExpression();return!this.match(")")&&this.config.tolerant?this.tolerateUnexpectedToken(this.nextToken()):(this.expect(")"),this.match(";")&&this.nextToken()),this.finalize(t,new s.DoWhileStatement(n,r))},t.prototype.parseWhileStatement=function(){var t,e=this.createNode();this.expectKeyword("while"),this.expect("(");var n=this.parseExpression();if(!this.match(")")&&this.config.tolerant)this.tolerateUnexpectedToken(this.nextToken()),t=this.finalize(this.createNode(),new s.EmptyStatement);else{this.expect(")");var r=this.context.inIteration;this.context.inIteration=!0,t=this.parseStatement(),this.context.inIteration=r}return this.finalize(e,new s.WhileStatement(n,t))},t.prototype.parseForStatement=function(){var t,e,n,r=null,i=null,a=null,c=!0,l=this.createNode();if(this.expectKeyword("for"),this.expect("("),this.match(";"))this.nextToken();else if(this.matchKeyword("var")){r=this.createNode(),this.nextToken();var h=this.context.allowIn;this.context.allowIn=!1;var f=this.parseVariableDeclarationList({inFor:!0});if(this.context.allowIn=h,1===f.length&&this.matchKeyword("in")){var p=f[0];p.init&&(p.id.type===u.Syntax.ArrayPattern||p.id.type===u.Syntax.ObjectPattern||this.context.strict)&&this.tolerateError(o.Messages.ForInOfLoopInitializer,"for-in"),r=this.finalize(r,new s.VariableDeclaration(f,"var")),this.nextToken(),t=r,e=this.parseExpression(),r=null}else 1===f.length&&null===f[0].init&&this.matchContextualKeyword("of")?(r=this.finalize(r,new s.VariableDeclaration(f,"var")),this.nextToken(),t=r,e=this.parseAssignmentExpression(),r=null,c=!1):(r=this.finalize(r,new s.VariableDeclaration(f,"var")),this.expect(";"))}else if(this.matchKeyword("const")||this.matchKeyword("let")){r=this.createNode();var d=this.nextToken().value;if(this.context.strict||"in"!==this.lookahead.value){h=this.context.allowIn;this.context.allowIn=!1;f=this.parseBindingList(d,{inFor:!0});this.context.allowIn=h,1===f.length&&null===f[0].init&&this.matchKeyword("in")?(r=this.finalize(r,new s.VariableDeclaration(f,d)),this.nextToken(),t=r,e=this.parseExpression(),r=null):1===f.length&&null===f[0].init&&this.matchContextualKeyword("of")?(r=this.finalize(r,new s.VariableDeclaration(f,d)),this.nextToken(),t=r,e=this.parseAssignmentExpression(),r=null,c=!1):(this.consumeSemicolon(),r=this.finalize(r,new s.VariableDeclaration(f,d)))}else r=this.finalize(r,new s.Identifier(d)),this.nextToken(),t=r,e=this.parseExpression(),r=null}else{var m=this.lookahead;h=this.context.allowIn;if(this.context.allowIn=!1,r=this.inheritCoverGrammar(this.parseAssignmentExpression),this.context.allowIn=h,this.matchKeyword("in"))this.context.isAssignmentTarget&&r.type!==u.Syntax.AssignmentExpression||this.tolerateError(o.Messages.InvalidLHSInForIn),this.nextToken(),this.reinterpretExpressionAsPattern(r),t=r,e=this.parseExpression(),r=null;else if(this.matchContextualKeyword("of"))this.context.isAssignmentTarget&&r.type!==u.Syntax.AssignmentExpression||this.tolerateError(o.Messages.InvalidLHSInForLoop),this.nextToken(),this.reinterpretExpressionAsPattern(r),t=r,e=this.parseAssignmentExpression(),r=null,c=!1;else{if(this.match(",")){for(var v=[r];this.match(",");)this.nextToken(),v.push(this.isolateCoverGrammar(this.parseAssignmentExpression));r=this.finalize(this.startNode(m),new s.SequenceExpression(v))}this.expect(";")}}if(void 0===t&&(this.match(";")||(i=this.parseExpression()),this.expect(";"),this.match(")")||(a=this.parseExpression())),!this.match(")")&&this.config.tolerant)this.tolerateUnexpectedToken(this.nextToken()),n=this.finalize(this.createNode(),new s.EmptyStatement);else{this.expect(")");var y=this.context.inIteration;this.context.inIteration=!0,n=this.isolateCoverGrammar(this.parseStatement),this.context.inIteration=y}return void 0===t?this.finalize(l,new s.ForStatement(r,i,a,n)):c?this.finalize(l,new s.ForInStatement(t,e,n)):this.finalize(l,new s.ForOfStatement(t,e,n))},t.prototype.parseContinueStatement=function(){var t=this.createNode();this.expectKeyword("continue");var e=null;if(3===this.lookahead.type&&!this.hasLineTerminator){var n=this.parseVariableIdentifier();e=n;var r="$"+n.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,r)||this.throwError(o.Messages.UnknownLabel,n.name)}return this.consumeSemicolon(),null!==e||this.context.inIteration||this.throwError(o.Messages.IllegalContinue),this.finalize(t,new s.ContinueStatement(e))},t.prototype.parseBreakStatement=function(){var t=this.createNode();this.expectKeyword("break");var e=null;if(3===this.lookahead.type&&!this.hasLineTerminator){var n=this.parseVariableIdentifier(),r="$"+n.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,r)||this.throwError(o.Messages.UnknownLabel,n.name),e=n}return this.consumeSemicolon(),null!==e||this.context.inIteration||this.context.inSwitch||this.throwError(o.Messages.IllegalBreak),this.finalize(t,new s.BreakStatement(e))},t.prototype.parseReturnStatement=function(){this.context.inFunctionBody||this.tolerateError(o.Messages.IllegalReturn);var t=this.createNode();this.expectKeyword("return");var e=!this.match(";")&&!this.match("}")&&!this.hasLineTerminator&&2!==this.lookahead.type?this.parseExpression():null;return this.consumeSemicolon(),this.finalize(t,new s.ReturnStatement(e))},t.prototype.parseWithStatement=function(){this.context.strict&&this.tolerateError(o.Messages.StrictModeWith);var t,e=this.createNode();this.expectKeyword("with"),this.expect("(");var n=this.parseExpression();return!this.match(")")&&this.config.tolerant?(this.tolerateUnexpectedToken(this.nextToken()),t=this.finalize(this.createNode(),new s.EmptyStatement)):(this.expect(")"),t=this.parseStatement()),this.finalize(e,new s.WithStatement(n,t))},t.prototype.parseSwitchCase=function(){var t,e=this.createNode();this.matchKeyword("default")?(this.nextToken(),t=null):(this.expectKeyword("case"),t=this.parseExpression()),this.expect(":");for(var n=[];!(this.match("}")||this.matchKeyword("default")||this.matchKeyword("case"));)n.push(this.parseStatementListItem());return this.finalize(e,new s.SwitchCase(t,n))},t.prototype.parseSwitchStatement=function(){var t=this.createNode();this.expectKeyword("switch"),this.expect("(");var e=this.parseExpression();this.expect(")");var n=this.context.inSwitch;this.context.inSwitch=!0;var r=[],i=!1;for(this.expect("{");!this.match("}");){var a=this.parseSwitchCase();null===a.test&&(i&&this.throwError(o.Messages.MultipleDefaultsInSwitch),i=!0),r.push(a)}return this.expect("}"),this.context.inSwitch=n,this.finalize(t,new s.SwitchStatement(e,r))},t.prototype.parseLabelledStatement=function(){var t,e=this.createNode(),n=this.parseExpression();if(n.type===u.Syntax.Identifier&&this.match(":")){this.nextToken();var r=n,i="$"+r.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,i)&&this.throwError(o.Messages.Redeclaration,"Label",r.name),this.context.labelSet[i]=!0;var a=void 0;if(this.matchKeyword("class"))this.tolerateUnexpectedToken(this.lookahead),a=this.parseClassDeclaration();else if(this.matchKeyword("function")){var c=this.lookahead,l=this.parseFunctionDeclaration();this.context.strict?this.tolerateUnexpectedToken(c,o.Messages.StrictFunction):l.generator&&this.tolerateUnexpectedToken(c,o.Messages.GeneratorInLegacyContext),a=l}else a=this.parseStatement();delete this.context.labelSet[i],t=new s.LabeledStatement(r,a)}else this.consumeSemicolon(),t=new s.ExpressionStatement(n);return this.finalize(e,t)},t.prototype.parseThrowStatement=function(){var t=this.createNode();this.expectKeyword("throw"),this.hasLineTerminator&&this.throwError(o.Messages.NewlineAfterThrow);var e=this.parseExpression();return this.consumeSemicolon(),this.finalize(t,new s.ThrowStatement(e))},t.prototype.parseCatchClause=function(){var t=this.createNode();this.expectKeyword("catch"),this.expect("("),this.match(")")&&this.throwUnexpectedToken(this.lookahead);for(var e=[],n=this.parsePattern(e),r={},i=0;i<e.length;i++){var a="$"+e[i].value;Object.prototype.hasOwnProperty.call(r,a)&&this.tolerateError(o.Messages.DuplicateBinding,e[i].value),r[a]=!0}this.context.strict&&n.type===u.Syntax.Identifier&&this.scanner.isRestrictedWord(n.name)&&this.tolerateError(o.Messages.StrictCatchVariable),this.expect(")");var c=this.parseBlock();return this.finalize(t,new s.CatchClause(n,c))},t.prototype.parseFinallyClause=function(){return this.expectKeyword("finally"),this.parseBlock()},t.prototype.parseTryStatement=function(){var t=this.createNode();this.expectKeyword("try");var e=this.parseBlock(),n=this.matchKeyword("catch")?this.parseCatchClause():null,r=this.matchKeyword("finally")?this.parseFinallyClause():null;return n||r||this.throwError(o.Messages.NoCatchOrFinally),this.finalize(t,new s.TryStatement(e,n,r))},t.prototype.parseDebuggerStatement=function(){var t=this.createNode();return this.expectKeyword("debugger"),this.consumeSemicolon(),this.finalize(t,new s.DebuggerStatement)},t.prototype.parseStatement=function(){var t;switch(this.lookahead.type){case 1:case 5:case 6:case 8:case 10:case 9:t=this.parseExpressionStatement();break;case 7:var e=this.lookahead.value;t="{"===e?this.parseBlock():"("===e?this.parseExpressionStatement():";"===e?this.parseEmptyStatement():this.parseExpressionStatement();break;case 3:t=this.matchAsyncFunction()?this.parseFunctionDeclaration():this.parseLabelledStatement();break;case 4:switch(this.lookahead.value){case"break":t=this.parseBreakStatement();break;case"continue":t=this.parseContinueStatement();break;case"debugger":t=this.parseDebuggerStatement();break;case"do":t=this.parseDoWhileStatement();break;case"for":t=this.parseForStatement();break;case"function":t=this.parseFunctionDeclaration();break;case"if":t=this.parseIfStatement();break;case"return":t=this.parseReturnStatement();break;case"switch":t=this.parseSwitchStatement();break;case"throw":t=this.parseThrowStatement();break;case"try":t=this.parseTryStatement();break;case"var":t=this.parseVariableStatement();break;case"while":t=this.parseWhileStatement();break;case"with":t=this.parseWithStatement();break;default:t=this.parseExpressionStatement()}break;default:t=this.throwUnexpectedToken(this.lookahead)}return t},t.prototype.parseFunctionSourceElements=function(){var t=this.createNode();this.expect("{");var e=this.parseDirectivePrologues(),n=this.context.labelSet,r=this.context.inIteration,i=this.context.inSwitch,o=this.context.inFunctionBody;for(this.context.labelSet={},this.context.inIteration=!1,this.context.inSwitch=!1,this.context.inFunctionBody=!0;2!==this.lookahead.type&&!this.match("}");)e.push(this.parseStatementListItem());return this.expect("}"),this.context.labelSet=n,this.context.inIteration=r,this.context.inSwitch=i,this.context.inFunctionBody=o,this.finalize(t,new s.BlockStatement(e))},t.prototype.validateParam=function(t,e,n){var r="$"+n;this.context.strict?(this.scanner.isRestrictedWord(n)&&(t.stricted=e,t.message=o.Messages.StrictParamName),Object.prototype.hasOwnProperty.call(t.paramSet,r)&&(t.stricted=e,t.message=o.Messages.StrictParamDupe)):t.firstRestricted||(this.scanner.isRestrictedWord(n)?(t.firstRestricted=e,t.message=o.Messages.StrictParamName):this.scanner.isStrictModeReservedWord(n)?(t.firstRestricted=e,t.message=o.Messages.StrictReservedWord):Object.prototype.hasOwnProperty.call(t.paramSet,r)&&(t.stricted=e,t.message=o.Messages.StrictParamDupe)),"function"==typeof Object.defineProperty?Object.defineProperty(t.paramSet,r,{value:!0,enumerable:!0,writable:!0,configurable:!0}):t.paramSet[r]=!0},t.prototype.parseRestElement=function(t){var e=this.createNode();this.expect("...");var n=this.parsePattern(t);return this.match("=")&&this.throwError(o.Messages.DefaultRestParameter),this.match(")")||this.throwError(o.Messages.ParameterAfterRestParameter),this.finalize(e,new s.RestElement(n))},t.prototype.parseFormalParameter=function(t){for(var e=[],n=this.match("...")?this.parseRestElement(e):this.parsePatternWithDefault(e),r=0;r<e.length;r++)this.validateParam(t,e[r],e[r].value);t.simple=t.simple&&n instanceof s.Identifier,t.params.push(n)},t.prototype.parseFormalParameters=function(t){var e;if(e={simple:!0,params:[],firstRestricted:t},this.expect("("),!this.match(")"))for(e.paramSet={};2!==this.lookahead.type&&(this.parseFormalParameter(e),!this.match(")"))&&(this.expect(","),!this.match(")")););return this.expect(")"),{simple:e.simple,params:e.params,stricted:e.stricted,firstRestricted:e.firstRestricted,message:e.message}},t.prototype.matchAsyncFunction=function(){var t=this.matchContextualKeyword("async");if(t){var e=this.scanner.saveState();this.scanner.scanComments();var n=this.scanner.lex();this.scanner.restoreState(e),t=e.lineNumber===n.lineNumber&&4===n.type&&"function"===n.value}return t},t.prototype.parseFunctionDeclaration=function(t){var e=this.createNode(),n=this.matchContextualKeyword("async");n&&this.nextToken(),this.expectKeyword("function");var r,i=!n&&this.match("*");i&&this.nextToken();var a=null,u=null;if(!t||!this.match("(")){var c=this.lookahead;a=this.parseVariableIdentifier(),this.context.strict?this.scanner.isRestrictedWord(c.value)&&this.tolerateUnexpectedToken(c,o.Messages.StrictFunctionName):this.scanner.isRestrictedWord(c.value)?(u=c,r=o.Messages.StrictFunctionName):this.scanner.isStrictModeReservedWord(c.value)&&(u=c,r=o.Messages.StrictReservedWord)}var l=this.context.await,h=this.context.allowYield;this.context.await=n,this.context.allowYield=!i;var f=this.parseFormalParameters(u),p=f.params,d=f.stricted;u=f.firstRestricted,f.message&&(r=f.message);var m=this.context.strict,v=this.context.allowStrictDirective;this.context.allowStrictDirective=f.simple;var y=this.parseFunctionSourceElements();return this.context.strict&&u&&this.throwUnexpectedToken(u,r),this.context.strict&&d&&this.tolerateUnexpectedToken(d,r),this.context.strict=m,this.context.allowStrictDirective=v,this.context.await=l,this.context.allowYield=h,n?this.finalize(e,new s.AsyncFunctionDeclaration(a,p,y)):this.finalize(e,new s.FunctionDeclaration(a,p,y,i))},t.prototype.parseFunctionExpression=function(){var t=this.createNode(),e=this.matchContextualKeyword("async");e&&this.nextToken(),this.expectKeyword("function");var n,r=!e&&this.match("*");r&&this.nextToken();var i,a=null,u=this.context.await,c=this.context.allowYield;if(this.context.await=e,this.context.allowYield=!r,!this.match("(")){var l=this.lookahead;a=this.context.strict||r||!this.matchKeyword("yield")?this.parseVariableIdentifier():this.parseIdentifierName(),this.context.strict?this.scanner.isRestrictedWord(l.value)&&this.tolerateUnexpectedToken(l,o.Messages.StrictFunctionName):this.scanner.isRestrictedWord(l.value)?(i=l,n=o.Messages.StrictFunctionName):this.scanner.isStrictModeReservedWord(l.value)&&(i=l,n=o.Messages.StrictReservedWord)}var h=this.parseFormalParameters(i),f=h.params,p=h.stricted;i=h.firstRestricted,h.message&&(n=h.message);var d=this.context.strict,m=this.context.allowStrictDirective;this.context.allowStrictDirective=h.simple;var v=this.parseFunctionSourceElements();return this.context.strict&&i&&this.throwUnexpectedToken(i,n),this.context.strict&&p&&this.tolerateUnexpectedToken(p,n),this.context.strict=d,this.context.allowStrictDirective=m,this.context.await=u,this.context.allowYield=c,e?this.finalize(t,new s.AsyncFunctionExpression(a,f,v)):this.finalize(t,new s.FunctionExpression(a,f,v,r))},t.prototype.parseDirective=function(){var t=this.lookahead,e=this.createNode(),n=this.parseExpression(),r=n.type===u.Syntax.Literal?this.getTokenRaw(t).slice(1,-1):null;return this.consumeSemicolon(),this.finalize(e,r?new s.Directive(n,r):new s.ExpressionStatement(n))},t.prototype.parseDirectivePrologues=function(){for(var t=null,e=[];;){var n=this.lookahead;if(8!==n.type)break;var r=this.parseDirective();e.push(r);var i=r.directive;if("string"!=typeof i)break;"use strict"===i?(this.context.strict=!0,t&&this.tolerateUnexpectedToken(t,o.Messages.StrictOctalLiteral),this.context.allowStrictDirective||this.tolerateUnexpectedToken(n,o.Messages.IllegalLanguageModeDirective)):!t&&n.octal&&(t=n)}return e},t.prototype.qualifiedPropertyName=function(t){switch(t.type){case 3:case 8:case 1:case 5:case 6:case 4:return!0;case 7:return"["===t.value}return!1},t.prototype.parseGetterMethod=function(){var t=this.createNode(),e=this.context.allowYield;this.context.allowYield=!1;var n=this.parseFormalParameters();n.params.length>0&&this.tolerateError(o.Messages.BadGetterArity);var r=this.parsePropertyMethod(n);return this.context.allowYield=e,this.finalize(t,new s.FunctionExpression(null,n.params,r,!1))},t.prototype.parseSetterMethod=function(){var t=this.createNode(),e=this.context.allowYield;this.context.allowYield=!1;var n=this.parseFormalParameters();1!==n.params.length?this.tolerateError(o.Messages.BadSetterArity):n.params[0]instanceof s.RestElement&&this.tolerateError(o.Messages.BadSetterRestParameter);var r=this.parsePropertyMethod(n);return this.context.allowYield=e,this.finalize(t,new s.FunctionExpression(null,n.params,r,!1))},t.prototype.parseGeneratorMethod=function(){var t=this.createNode(),e=this.context.allowYield;this.context.allowYield=!0;var n=this.parseFormalParameters();this.context.allowYield=!1;var r=this.parsePropertyMethod(n);return this.context.allowYield=e,this.finalize(t,new s.FunctionExpression(null,n.params,r,!0))},t.prototype.isStartOfExpression=function(){var t=!0,e=this.lookahead.value;switch(this.lookahead.type){case 7:t="["===e||"("===e||"{"===e||"+"===e||"-"===e||"!"===e||"~"===e||"++"===e||"--"===e||"/"===e||"/="===e;break;case 4:t="class"===e||"delete"===e||"function"===e||"let"===e||"new"===e||"super"===e||"this"===e||"typeof"===e||"void"===e||"yield"===e}return t},t.prototype.parseYieldExpression=function(){var t=this.createNode();this.expectKeyword("yield");var e=null,n=!1;if(!this.hasLineTerminator){var r=this.context.allowYield;this.context.allowYield=!1,(n=this.match("*"))?(this.nextToken(),e=this.parseAssignmentExpression()):this.isStartOfExpression()&&(e=this.parseAssignmentExpression()),this.context.allowYield=r}return this.finalize(t,new s.YieldExpression(e,n))},t.prototype.parseClassElement=function(t){var e=this.lookahead,n=this.createNode(),r="",i=null,a=null,u=!1,c=!1,l=!1,h=!1;if(this.match("*"))this.nextToken();else if(u=this.match("["),"static"===(i=this.parseObjectPropertyKey()).name&&(this.qualifiedPropertyName(this.lookahead)||this.match("*"))&&(e=this.lookahead,l=!0,u=this.match("["),this.match("*")?this.nextToken():i=this.parseObjectPropertyKey()),3===e.type&&!this.hasLineTerminator&&"async"===e.value){var f=this.lookahead.value;":"!==f&&"("!==f&&"*"!==f&&(h=!0,e=this.lookahead,i=this.parseObjectPropertyKey(),3===e.type&&("get"===e.value||"set"===e.value?this.tolerateUnexpectedToken(e):"constructor"===e.value&&this.tolerateUnexpectedToken(e,o.Messages.ConstructorIsAsync)))}var p=this.qualifiedPropertyName(this.lookahead);return 3===e.type?"get"===e.value&&p?(r="get",u=this.match("["),i=this.parseObjectPropertyKey(),this.context.allowYield=!1,a=this.parseGetterMethod()):"set"===e.value&&p&&(r="set",u=this.match("["),i=this.parseObjectPropertyKey(),a=this.parseSetterMethod()):7===e.type&&"*"===e.value&&p&&(r="init",u=this.match("["),i=this.parseObjectPropertyKey(),a=this.parseGeneratorMethod(),c=!0),!r&&i&&this.match("(")&&(r="init",a=h?this.parsePropertyMethodAsyncFunction():this.parsePropertyMethodFunction(),c=!0),r||this.throwUnexpectedToken(this.lookahead),"init"===r&&(r="method"),u||(l&&this.isPropertyKey(i,"prototype")&&this.throwUnexpectedToken(e,o.Messages.StaticPrototype),!l&&this.isPropertyKey(i,"constructor")&&(("method"!==r||!c||a&&a.generator)&&this.throwUnexpectedToken(e,o.Messages.ConstructorSpecialMethod),t.value?this.throwUnexpectedToken(e,o.Messages.DuplicateConstructor):t.value=!0,r="constructor")),this.finalize(n,new s.MethodDefinition(i,u,a,r,l))},t.prototype.parseClassElementList=function(){var t=[],e={value:!1};for(this.expect("{");!this.match("}");)this.match(";")?this.nextToken():t.push(this.parseClassElement(e));return this.expect("}"),t},t.prototype.parseClassBody=function(){var t=this.createNode(),e=this.parseClassElementList();return this.finalize(t,new s.ClassBody(e))},t.prototype.parseClassDeclaration=function(t){var e=this.createNode(),n=this.context.strict;this.context.strict=!0,this.expectKeyword("class");var r=t&&3!==this.lookahead.type?null:this.parseVariableIdentifier(),i=null;this.matchKeyword("extends")&&(this.nextToken(),i=this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall));var o=this.parseClassBody();return this.context.strict=n,this.finalize(e,new s.ClassDeclaration(r,i,o))},t.prototype.parseClassExpression=function(){var t=this.createNode(),e=this.context.strict;this.context.strict=!0,this.expectKeyword("class");var n=3===this.lookahead.type?this.parseVariableIdentifier():null,r=null;this.matchKeyword("extends")&&(this.nextToken(),r=this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall));var i=this.parseClassBody();return this.context.strict=e,this.finalize(t,new s.ClassExpression(n,r,i))},t.prototype.parseModule=function(){this.context.strict=!0,this.context.isModule=!0;for(var t=this.createNode(),e=this.parseDirectivePrologues();2!==this.lookahead.type;)e.push(this.parseStatementListItem());return this.finalize(t,new s.Module(e))},t.prototype.parseScript=function(){for(var t=this.createNode(),e=this.parseDirectivePrologues();2!==this.lookahead.type;)e.push(this.parseStatementListItem());return this.finalize(t,new s.Script(e))},t.prototype.parseModuleSpecifier=function(){var t=this.createNode();8!==this.lookahead.type&&this.throwError(o.Messages.InvalidModuleSpecifier);var e=this.nextToken(),n=this.getTokenRaw(e);return this.finalize(t,new s.Literal(e.value,n))},t.prototype.parseImportSpecifier=function(){var t,e,n=this.createNode();return 3===this.lookahead.type?(e=t=this.parseVariableIdentifier(),this.matchContextualKeyword("as")&&(this.nextToken(),e=this.parseVariableIdentifier())):(e=t=this.parseIdentifierName(),this.matchContextualKeyword("as")?(this.nextToken(),e=this.parseVariableIdentifier()):this.throwUnexpectedToken(this.nextToken())),this.finalize(n,new s.ImportSpecifier(e,t))},t.prototype.parseNamedImports=function(){this.expect("{");for(var t=[];!this.match("}");)t.push(this.parseImportSpecifier()),this.match("}")||this.expect(",");return this.expect("}"),t},t.prototype.parseImportDefaultSpecifier=function(){var t=this.createNode(),e=this.parseIdentifierName();return this.finalize(t,new s.ImportDefaultSpecifier(e))},t.prototype.parseImportNamespaceSpecifier=function(){var t=this.createNode();this.expect("*"),this.matchContextualKeyword("as")||this.throwError(o.Messages.NoAsAfterImportNamespace),this.nextToken();var e=this.parseIdentifierName();return this.finalize(t,new s.ImportNamespaceSpecifier(e))},t.prototype.parseImportDeclaration=function(){this.context.inFunctionBody&&this.throwError(o.Messages.IllegalImportDeclaration);var t,e=this.createNode();this.expectKeyword("import");var n=[];if(8===this.lookahead.type)t=this.parseModuleSpecifier();else{if(this.match("{")?n=n.concat(this.parseNamedImports()):this.match("*")?n.push(this.parseImportNamespaceSpecifier()):this.isIdentifierName(this.lookahead)&&!this.matchKeyword("default")?(n.push(this.parseImportDefaultSpecifier()),this.match(",")&&(this.nextToken(),this.match("*")?n.push(this.parseImportNamespaceSpecifier()):this.match("{")?n=n.concat(this.parseNamedImports()):this.throwUnexpectedToken(this.lookahead))):this.throwUnexpectedToken(this.nextToken()),!this.matchContextualKeyword("from")){var r=this.lookahead.value?o.Messages.UnexpectedToken:o.Messages.MissingFromClause;this.throwError(r,this.lookahead.value)}this.nextToken(),t=this.parseModuleSpecifier()}return this.consumeSemicolon(),this.finalize(e,new s.ImportDeclaration(n,t))},t.prototype.parseExportSpecifier=function(){var t=this.createNode(),e=this.parseIdentifierName(),n=e;return this.matchContextualKeyword("as")&&(this.nextToken(),n=this.parseIdentifierName()),this.finalize(t,new s.ExportSpecifier(e,n))},t.prototype.parseExportDeclaration=function(){this.context.inFunctionBody&&this.throwError(o.Messages.IllegalExportDeclaration);var t,e=this.createNode();if(this.expectKeyword("export"),this.matchKeyword("default"))if(this.nextToken(),this.matchKeyword("function")){var n=this.parseFunctionDeclaration(!0);t=this.finalize(e,new s.ExportDefaultDeclaration(n))}else if(this.matchKeyword("class")){n=this.parseClassDeclaration(!0);t=this.finalize(e,new s.ExportDefaultDeclaration(n))}else if(this.matchContextualKeyword("async")){n=this.matchAsyncFunction()?this.parseFunctionDeclaration(!0):this.parseAssignmentExpression();t=this.finalize(e,new s.ExportDefaultDeclaration(n))}else{this.matchContextualKeyword("from")&&this.throwError(o.Messages.UnexpectedToken,this.lookahead.value);n=this.match("{")?this.parseObjectInitializer():this.match("[")?this.parseArrayInitializer():this.parseAssignmentExpression();this.consumeSemicolon(),t=this.finalize(e,new s.ExportDefaultDeclaration(n))}else if(this.match("*")){if(this.nextToken(),!this.matchContextualKeyword("from")){var r=this.lookahead.value?o.Messages.UnexpectedToken:o.Messages.MissingFromClause;this.throwError(r,this.lookahead.value)}this.nextToken();var i=this.parseModuleSpecifier();this.consumeSemicolon(),t=this.finalize(e,new s.ExportAllDeclaration(i))}else if(4===this.lookahead.type){n=void 0;switch(this.lookahead.value){case"let":case"const":n=this.parseLexicalDeclaration({inFor:!1});break;case"var":case"class":case"function":n=this.parseStatementListItem();break;default:this.throwUnexpectedToken(this.lookahead)}t=this.finalize(e,new s.ExportNamedDeclaration(n,[],null))}else if(this.matchAsyncFunction()){n=this.parseFunctionDeclaration();t=this.finalize(e,new s.ExportNamedDeclaration(n,[],null))}else{var a=[],u=null,c=!1;for(this.expect("{");!this.match("}");)c=c||this.matchKeyword("default"),a.push(this.parseExportSpecifier()),this.match("}")||this.expect(",");if(this.expect("}"),this.matchContextualKeyword("from"))this.nextToken(),u=this.parseModuleSpecifier(),this.consumeSemicolon();else if(c){r=this.lookahead.value?o.Messages.UnexpectedToken:o.Messages.MissingFromClause;this.throwError(r,this.lookahead.value)}else this.consumeSemicolon();t=this.finalize(e,new s.ExportNamedDeclaration(null,a,u))}return t},t}();e.Parser=l},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.assert=function(t,e){if(!t)throw new Error("ASSERT: "+e)}},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(){this.errors=[],this.tolerant=!1}return t.prototype.recordError=function(t){this.errors.push(t)},t.prototype.tolerate=function(t){if(!this.tolerant)throw t;this.recordError(t)},t.prototype.constructError=function(t,e){var n=new Error(t);try{throw n}catch(t){Object.create&&Object.defineProperty&&(n=Object.create(t),Object.defineProperty(n,"column",{value:e}))}return n},t.prototype.createError=function(t,e,n,r){var i="Line "+e+": "+r,o=this.constructError(i,n);return o.index=t,o.lineNumber=e,o.description=r,o},t.prototype.throwError=function(t,e,n,r){throw this.createError(t,e,n,r)},t.prototype.tolerateError=function(t,e,n,r){var i=this.createError(t,e,n,r);if(!this.tolerant)throw i;this.recordError(i)},t}();e.ErrorHandler=n},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Messages={BadGetterArity:"Getter must not have any formal parameters",BadSetterArity:"Setter must have exactly one formal parameter",BadSetterRestParameter:"Setter function argument must not be a rest parameter",ConstructorIsAsync:"Class constructor may not be an async method",ConstructorSpecialMethod:"Class constructor may not be an accessor",DeclarationMissingInitializer:"Missing initializer in %0 declaration",DefaultRestParameter:"Unexpected token =",DuplicateBinding:"Duplicate binding %0",DuplicateConstructor:"A class may only have one constructor",DuplicateProtoProperty:"Duplicate __proto__ fields are not allowed in object literals",ForInOfLoopInitializer:"%0 loop variable declaration may not have an initializer",GeneratorInLegacyContext:"Generator declarations are not allowed in legacy contexts",IllegalBreak:"Illegal break statement",IllegalContinue:"Illegal continue statement",IllegalExportDeclaration:"Unexpected token",IllegalImportDeclaration:"Unexpected token",IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list",IllegalReturn:"Illegal return statement",InvalidEscapedReservedWord:"Keyword must not contain escaped characters",InvalidHexEscapeSequence:"Invalid hexadecimal escape sequence",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",InvalidLHSInForLoop:"Invalid left-hand side in for-loop",InvalidModuleSpecifier:"Unexpected token",InvalidRegExp:"Invalid regular expression",LetInLexicalBinding:"let is disallowed as a lexically bound name",MissingFromClause:"Unexpected token",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NewlineAfterThrow:"Illegal newline after throw",NoAsAfterImportNamespace:"Unexpected token",NoCatchOrFinally:"Missing catch or finally after try",ParameterAfterRestParameter:"Rest parameter must be last formal parameter",Redeclaration:"%0 '%1' has already been declared",StaticPrototype:"Classes may not have static property named prototype",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictModeWith:"Strict mode code may not include a with statement",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictReservedWord:"Use of future reserved word in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",TemplateOctalLiteral:"Octal literals are not allowed in template strings.",UnexpectedEOS:"Unexpected end of input",UnexpectedIdentifier:"Unexpected identifier",UnexpectedNumber:"Unexpected number",UnexpectedReserved:"Unexpected reserved word",UnexpectedString:"Unexpected string",UnexpectedTemplate:"Unexpected quasi %0",UnexpectedToken:"Unexpected token %0",UnexpectedTokenIllegal:"Unexpected token ILLEGAL",UnknownLabel:"Undefined label '%0'",UnterminatedRegExp:"Invalid regular expression: missing /"}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(9),i=n(4),o=n(11);function s(t){return"0123456789abcdef".indexOf(t.toLowerCase())}function a(t){return"01234567".indexOf(t)}var u=function(){function t(t,e){this.source=t,this.errorHandler=e,this.trackComment=!1,this.length=t.length,this.index=0,this.lineNumber=t.length>0?1:0,this.lineStart=0,this.curlyStack=[]}return t.prototype.saveState=function(){return{index:this.index,lineNumber:this.lineNumber,lineStart:this.lineStart}},t.prototype.restoreState=function(t){this.index=t.index,this.lineNumber=t.lineNumber,this.lineStart=t.lineStart},t.prototype.eof=function(){return this.index>=this.length},t.prototype.throwUnexpectedToken=function(t){return void 0===t&&(t=o.Messages.UnexpectedTokenIllegal),this.errorHandler.throwError(this.index,this.lineNumber,this.index-this.lineStart+1,t)},t.prototype.tolerateUnexpectedToken=function(t){void 0===t&&(t=o.Messages.UnexpectedTokenIllegal),this.errorHandler.tolerateError(this.index,this.lineNumber,this.index-this.lineStart+1,t)},t.prototype.skipSingleLineComment=function(t){var e,n,r=[];for(this.trackComment&&(r=[],e=this.index-t,n={start:{line:this.lineNumber,column:this.index-this.lineStart-t},end:{}});!this.eof();){var o=this.source.charCodeAt(this.index);if(++this.index,i.Character.isLineTerminator(o)){if(this.trackComment){n.end={line:this.lineNumber,column:this.index-this.lineStart-1};var s={multiLine:!1,slice:[e+t,this.index-1],range:[e,this.index-1],loc:n};r.push(s)}return 13===o&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,r}}if(this.trackComment){n.end={line:this.lineNumber,column:this.index-this.lineStart};s={multiLine:!1,slice:[e+t,this.index],range:[e,this.index],loc:n};r.push(s)}return r},t.prototype.skipMultiLineComment=function(){var t,e,n=[];for(this.trackComment&&(n=[],t=this.index-2,e={start:{line:this.lineNumber,column:this.index-this.lineStart-2},end:{}});!this.eof();){var r=this.source.charCodeAt(this.index);if(i.Character.isLineTerminator(r))13===r&&10===this.source.charCodeAt(this.index+1)&&++this.index,++this.lineNumber,++this.index,this.lineStart=this.index;else if(42===r){if(47===this.source.charCodeAt(this.index+1)){if(this.index+=2,this.trackComment){e.end={line:this.lineNumber,column:this.index-this.lineStart};var o={multiLine:!0,slice:[t+2,this.index-2],range:[t,this.index],loc:e};n.push(o)}return n}++this.index}else++this.index}if(this.trackComment){e.end={line:this.lineNumber,column:this.index-this.lineStart};o={multiLine:!0,slice:[t+2,this.index],range:[t,this.index],loc:e};n.push(o)}return this.tolerateUnexpectedToken(),n},t.prototype.scanComments=function(){var t;this.trackComment&&(t=[]);for(var e=0===this.index;!this.eof();){var n=this.source.charCodeAt(this.index);if(i.Character.isWhiteSpace(n))++this.index;else if(i.Character.isLineTerminator(n))++this.index,13===n&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,e=!0;else if(47===n)if(47===(n=this.source.charCodeAt(this.index+1))){this.index+=2;var r=this.skipSingleLineComment(2);this.trackComment&&(t=t.concat(r)),e=!0}else{if(42!==n)break;this.index+=2;r=this.skipMultiLineComment();this.trackComment&&(t=t.concat(r))}else if(e&&45===n){if(45!==this.source.charCodeAt(this.index+1)||62!==this.source.charCodeAt(this.index+2))break;this.index+=3;r=this.skipSingleLineComment(3);this.trackComment&&(t=t.concat(r))}else{if(60!==n)break;if("!--"!==this.source.slice(this.index+1,this.index+4))break;this.index+=4;r=this.skipSingleLineComment(4);this.trackComment&&(t=t.concat(r))}}return t},t.prototype.isFutureReservedWord=function(t){switch(t){case"enum":case"export":case"import":case"super":return!0;default:return!1}},t.prototype.isStrictModeReservedWord=function(t){switch(t){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}},t.prototype.isRestrictedWord=function(t){return"eval"===t||"arguments"===t},t.prototype.isKeyword=function(t){switch(t.length){case 2:return"if"===t||"in"===t||"do"===t;case 3:return"var"===t||"for"===t||"new"===t||"try"===t||"let"===t;case 4:return"this"===t||"else"===t||"case"===t||"void"===t||"with"===t||"enum"===t;case 5:return"while"===t||"break"===t||"catch"===t||"throw"===t||"const"===t||"yield"===t||"class"===t||"super"===t;case 6:return"return"===t||"typeof"===t||"delete"===t||"switch"===t||"export"===t||"import"===t;case 7:return"default"===t||"finally"===t||"extends"===t;case 8:return"function"===t||"continue"===t||"debugger"===t;case 10:return"instanceof"===t;default:return!1}},t.prototype.codePointAt=function(t){var e=this.source.charCodeAt(t);if(e>=55296&&e<=56319){var n=this.source.charCodeAt(t+1);if(n>=56320&&n<=57343)e=1024*(e-55296)+n-56320+65536}return e},t.prototype.scanHexEscape=function(t){for(var e="u"===t?4:2,n=0,r=0;r<e;++r){if(this.eof()||!i.Character.isHexDigit(this.source.charCodeAt(this.index)))return null;n=16*n+s(this.source[this.index++])}return String.fromCharCode(n)},t.prototype.scanUnicodeCodePointEscape=function(){var t=this.source[this.index],e=0;for("}"===t&&this.throwUnexpectedToken();!this.eof()&&(t=this.source[this.index++],i.Character.isHexDigit(t.charCodeAt(0)));)e=16*e+s(t);return(e>1114111||"}"!==t)&&this.throwUnexpectedToken(),i.Character.fromCodePoint(e)},t.prototype.getIdentifier=function(){for(var t=this.index++;!this.eof();){var e=this.source.charCodeAt(this.index);if(92===e)return this.index=t,this.getComplexIdentifier();if(e>=55296&&e<57343)return this.index=t,this.getComplexIdentifier();if(!i.Character.isIdentifierPart(e))break;++this.index}return this.source.slice(t,this.index)},t.prototype.getComplexIdentifier=function(){var t,e=this.codePointAt(this.index),n=i.Character.fromCodePoint(e);for(this.index+=n.length,92===e&&(117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,t=this.scanUnicodeCodePointEscape()):null!==(t=this.scanHexEscape("u"))&&"\\"!==t&&i.Character.isIdentifierStart(t.charCodeAt(0))||this.throwUnexpectedToken(),n=t);!this.eof()&&(e=this.codePointAt(this.index),i.Character.isIdentifierPart(e));)n+=t=i.Character.fromCodePoint(e),this.index+=t.length,92===e&&(n=n.substr(0,n.length-1),117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,t=this.scanUnicodeCodePointEscape()):null!==(t=this.scanHexEscape("u"))&&"\\"!==t&&i.Character.isIdentifierPart(t.charCodeAt(0))||this.throwUnexpectedToken(),n+=t);return n},t.prototype.octalToDecimal=function(t){var e="0"!==t,n=a(t);return!this.eof()&&i.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(e=!0,n=8*n+a(this.source[this.index++]),"0123".indexOf(t)>=0&&!this.eof()&&i.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(n=8*n+a(this.source[this.index++]))),{code:n,octal:e}},t.prototype.scanIdentifier=function(){var t,e=this.index,n=92===this.source.charCodeAt(e)?this.getComplexIdentifier():this.getIdentifier();if(3!==(t=1===n.length?3:this.isKeyword(n)?4:"null"===n?5:"true"===n||"false"===n?1:3)&&e+n.length!==this.index){var r=this.index;this.index=e,this.tolerateUnexpectedToken(o.Messages.InvalidEscapedReservedWord),this.index=r}return{type:t,value:n,lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},t.prototype.scanPunctuator=function(){var t=this.index,e=this.source[this.index];switch(e){case"(":case"{":"{"===e&&this.curlyStack.push("{"),++this.index;break;case".":++this.index,"."===this.source[this.index]&&"."===this.source[this.index+1]&&(this.index+=2,e="...");break;case"}":++this.index,this.curlyStack.pop();break;case")":case";":case",":case"[":case"]":case":":case"?":case"~":++this.index;break;default:">>>="===(e=this.source.substr(this.index,4))?this.index+=4:"==="===(e=e.substr(0,3))||"!=="===e||">>>"===e||"<<="===e||">>="===e||"**="===e?this.index+=3:"&&"===(e=e.substr(0,2))||"||"===e||"=="===e||"!="===e||"+="===e||"-="===e||"*="===e||"/="===e||"++"===e||"--"===e||"<<"===e||">>"===e||"&="===e||"|="===e||"^="===e||"%="===e||"<="===e||">="===e||"=>"===e||"**"===e?this.index+=2:(e=this.source[this.index],"<>=!+-*%&|^/".indexOf(e)>=0&&++this.index)}return this.index===t&&this.throwUnexpectedToken(),{type:7,value:e,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},t.prototype.scanHexLiteral=function(t){for(var e="";!this.eof()&&i.Character.isHexDigit(this.source.charCodeAt(this.index));)e+=this.source[this.index++];return 0===e.length&&this.throwUnexpectedToken(),i.Character.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:6,value:parseInt("0x"+e,16),lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},t.prototype.scanBinaryLiteral=function(t){for(var e,n="";!this.eof()&&("0"===(e=this.source[this.index])||"1"===e);)n+=this.source[this.index++];return 0===n.length&&this.throwUnexpectedToken(),this.eof()||(e=this.source.charCodeAt(this.index),(i.Character.isIdentifierStart(e)||i.Character.isDecimalDigit(e))&&this.throwUnexpectedToken()),{type:6,value:parseInt(n,2),lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},t.prototype.scanOctalLiteral=function(t,e){var n="",r=!1;for(i.Character.isOctalDigit(t.charCodeAt(0))?(r=!0,n="0"+this.source[this.index++]):++this.index;!this.eof()&&i.Character.isOctalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];return r||0!==n.length||this.throwUnexpectedToken(),(i.Character.isIdentifierStart(this.source.charCodeAt(this.index))||i.Character.isDecimalDigit(this.source.charCodeAt(this.index)))&&this.throwUnexpectedToken(),{type:6,value:parseInt(n,8),octal:r,lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},t.prototype.isImplicitOctalLiteral=function(){for(var t=this.index+1;t<this.length;++t){var e=this.source[t];if("8"===e||"9"===e)return!1;if(!i.Character.isOctalDigit(e.charCodeAt(0)))return!0}return!0},t.prototype.scanNumericLiteral=function(){var t=this.index,e=this.source[t];r.assert(i.Character.isDecimalDigit(e.charCodeAt(0))||"."===e,"Numeric literal must start with a decimal digit or a decimal point");var n="";if("."!==e){if(n=this.source[this.index++],e=this.source[this.index],"0"===n){if("x"===e||"X"===e)return++this.index,this.scanHexLiteral(t);if("b"===e||"B"===e)return++this.index,this.scanBinaryLiteral(t);if("o"===e||"O"===e)return this.scanOctalLiteral(e,t);if(e&&i.Character.isOctalDigit(e.charCodeAt(0))&&this.isImplicitOctalLiteral())return this.scanOctalLiteral(e,t)}for(;i.Character.isDecimalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];e=this.source[this.index]}if("."===e){for(n+=this.source[this.index++];i.Character.isDecimalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];e=this.source[this.index]}if("e"===e||"E"===e)if(n+=this.source[this.index++],"+"!==(e=this.source[this.index])&&"-"!==e||(n+=this.source[this.index++]),i.Character.isDecimalDigit(this.source.charCodeAt(this.index)))for(;i.Character.isDecimalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];else this.throwUnexpectedToken();return i.Character.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:6,value:parseFloat(n),lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},t.prototype.scanStringLiteral=function(){var t=this.index,e=this.source[t];r.assert("'"===e||'"'===e,"String literal must starts with a quote"),++this.index;for(var n=!1,s="";!this.eof();){var a=this.source[this.index++];if(a===e){e="";break}if("\\"===a)if((a=this.source[this.index++])&&i.Character.isLineTerminator(a.charCodeAt(0)))++this.lineNumber,"\r"===a&&"\n"===this.source[this.index]&&++this.index,this.lineStart=this.index;else switch(a){case"u":if("{"===this.source[this.index])++this.index,s+=this.scanUnicodeCodePointEscape();else{var u=this.scanHexEscape(a);null===u&&this.throwUnexpectedToken(),s+=u}break;case"x":var c=this.scanHexEscape(a);null===c&&this.throwUnexpectedToken(o.Messages.InvalidHexEscapeSequence),s+=c;break;case"n":s+="\n";break;case"r":s+="\r";break;case"t":s+="\t";break;case"b":s+="\b";break;case"f":s+="\f";break;case"v":s+="\v";break;case"8":case"9":s+=a,this.tolerateUnexpectedToken();break;default:if(a&&i.Character.isOctalDigit(a.charCodeAt(0))){var l=this.octalToDecimal(a);n=l.octal||n,s+=String.fromCharCode(l.code)}else s+=a}else{if(i.Character.isLineTerminator(a.charCodeAt(0)))break;s+=a}}return""!==e&&(this.index=t,this.throwUnexpectedToken()),{type:8,value:s,octal:n,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},t.prototype.scanTemplate=function(){var t="",e=!1,n=this.index,r="`"===this.source[n],s=!1,a=2;for(++this.index;!this.eof();){var u=this.source[this.index++];if("`"===u){a=1,s=!0,e=!0;break}if("$"===u){if("{"===this.source[this.index]){this.curlyStack.push("${"),++this.index,e=!0;break}t+=u}else if("\\"===u)if(u=this.source[this.index++],i.Character.isLineTerminator(u.charCodeAt(0)))++this.lineNumber,"\r"===u&&"\n"===this.source[this.index]&&++this.index,this.lineStart=this.index;else switch(u){case"n":t+="\n";break;case"r":t+="\r";break;case"t":t+="\t";break;case"u":if("{"===this.source[this.index])++this.index,t+=this.scanUnicodeCodePointEscape();else{var c=this.index,l=this.scanHexEscape(u);null!==l?t+=l:(this.index=c,t+=u)}break;case"x":var h=this.scanHexEscape(u);null===h&&this.throwUnexpectedToken(o.Messages.InvalidHexEscapeSequence),t+=h;break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="\v";break;default:"0"===u?(i.Character.isDecimalDigit(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(o.Messages.TemplateOctalLiteral),t+="\0"):i.Character.isOctalDigit(u.charCodeAt(0))?this.throwUnexpectedToken(o.Messages.TemplateOctalLiteral):t+=u}else i.Character.isLineTerminator(u.charCodeAt(0))?(++this.lineNumber,"\r"===u&&"\n"===this.source[this.index]&&++this.index,this.lineStart=this.index,t+="\n"):t+=u}return e||this.throwUnexpectedToken(),r||this.curlyStack.pop(),{type:10,value:this.source.slice(n+1,this.index-a),cooked:t,head:r,tail:s,lineNumber:this.lineNumber,lineStart:this.lineStart,start:n,end:this.index}},t.prototype.testRegExp=function(t,e){var n=t,r=this;e.indexOf("u")>=0&&(n=n.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g,function(t,e,n){var i=parseInt(e||n,16);return i>1114111&&r.throwUnexpectedToken(o.Messages.InvalidRegExp),i<=65535?String.fromCharCode(i):""}).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,""));try{RegExp(n)}catch(t){this.throwUnexpectedToken(o.Messages.InvalidRegExp)}try{return new RegExp(t,e)}catch(t){return null}},t.prototype.scanRegExpBody=function(){var t=this.source[this.index];r.assert("/"===t,"Regular expression literal must start with a slash");for(var e=this.source[this.index++],n=!1,s=!1;!this.eof();)if(e+=t=this.source[this.index++],"\\"===t)t=this.source[this.index++],i.Character.isLineTerminator(t.charCodeAt(0))&&this.throwUnexpectedToken(o.Messages.UnterminatedRegExp),e+=t;else if(i.Character.isLineTerminator(t.charCodeAt(0)))this.throwUnexpectedToken(o.Messages.UnterminatedRegExp);else if(n)"]"===t&&(n=!1);else{if("/"===t){s=!0;break}"["===t&&(n=!0)}return s||this.throwUnexpectedToken(o.Messages.UnterminatedRegExp),e.substr(1,e.length-2)},t.prototype.scanRegExpFlags=function(){for(var t="";!this.eof();){var e=this.source[this.index];if(!i.Character.isIdentifierPart(e.charCodeAt(0)))break;if(++this.index,"\\"!==e||this.eof())t+=e,e;else if("u"===(e=this.source[this.index])){++this.index;var n=this.index,r=this.scanHexEscape("u");if(null!==r)for(t+=r,"\\u";n<this.index;++n)this.source[n];else this.index=n,t+="u","\\u";this.tolerateUnexpectedToken()}else"\\",this.tolerateUnexpectedToken()}return t},t.prototype.scanRegExp=function(){var t=this.index,e=this.scanRegExpBody(),n=this.scanRegExpFlags();return{type:9,value:"",pattern:e,flags:n,regex:this.testRegExp(e,n),lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},t.prototype.lex=function(){if(this.eof())return{type:2,value:"",lineNumber:this.lineNumber,lineStart:this.lineStart,start:this.index,end:this.index};var t=this.source.charCodeAt(this.index);return i.Character.isIdentifierStart(t)?this.scanIdentifier():40===t||41===t||59===t?this.scanPunctuator():39===t||34===t?this.scanStringLiteral():46===t?i.Character.isDecimalDigit(this.source.charCodeAt(this.index+1))?this.scanNumericLiteral():this.scanPunctuator():i.Character.isDecimalDigit(t)?this.scanNumericLiteral():96===t||125===t&&"${"===this.curlyStack[this.curlyStack.length-1]?this.scanTemplate():t>=55296&&t<57343&&i.Character.isIdentifierStart(this.codePointAt(this.index))?this.scanIdentifier():this.scanPunctuator()},t}();e.Scanner=u},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TokenName={},e.TokenName[1]="Boolean",e.TokenName[2]="<end>",e.TokenName[3]="Identifier",e.TokenName[4]="Keyword",e.TokenName[5]="Null",e.TokenName[6]="Numeric",e.TokenName[7]="Punctuator",e.TokenName[8]="String",e.TokenName[9]="RegularExpression",e.TokenName[10]="Template"},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.XHTMLEntities={quot:'"',amp:"&",apos:"'",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",lang:"⟨",rang:"⟩"}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(10),i=n(12),o=n(13),s=function(){function t(){this.values=[],this.curly=this.paren=-1}return t.prototype.beforeFunctionExpression=function(t){return["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","**=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","**","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="].indexOf(t)>=0},t.prototype.isRegexStart=function(){var t=this.values[this.values.length-1],e=null!==t;switch(t){case"this":case"]":e=!1;break;case")":var n=this.values[this.paren-1];e="if"===n||"while"===n||"for"===n||"with"===n;break;case"}":if(e=!1,"function"===this.values[this.curly-3])e=!!(r=this.values[this.curly-4])&&!this.beforeFunctionExpression(r);else if("function"===this.values[this.curly-4]){var r;e=!(r=this.values[this.curly-5])||!this.beforeFunctionExpression(r)}}return e},t.prototype.push=function(t){7===t.type||4===t.type?("{"===t.value?this.curly=this.values.length:"("===t.value&&(this.paren=this.values.length),this.values.push(t.value)):this.values.push(null)},t}(),a=function(){function t(t,e){this.errorHandler=new r.ErrorHandler,this.errorHandler.tolerant=!!e&&("boolean"==typeof e.tolerant&&e.tolerant),this.scanner=new i.Scanner(t,this.errorHandler),this.scanner.trackComment=!!e&&("boolean"==typeof e.comment&&e.comment),this.trackRange=!!e&&("boolean"==typeof e.range&&e.range),this.trackLoc=!!e&&("boolean"==typeof e.loc&&e.loc),this.buffer=[],this.reader=new s}return t.prototype.errors=function(){return this.errorHandler.errors},t.prototype.getNextToken=function(){if(0===this.buffer.length){var t=this.scanner.scanComments();if(this.scanner.trackComment)for(var e=0;e<t.length;++e){var n=t[e],r=this.scanner.source.slice(n.slice[0],n.slice[1]),i={type:n.multiLine?"BlockComment":"LineComment",value:r};this.trackRange&&(i.range=n.range),this.trackLoc&&(i.loc=n.loc),this.buffer.push(i)}if(!this.scanner.eof()){var s=void 0;this.trackLoc&&(s={start:{line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart},end:{}});var a="/"===this.scanner.source[this.scanner.index]&&this.reader.isRegexStart()?this.scanner.scanRegExp():this.scanner.lex();this.reader.push(a);var u={type:o.TokenName[a.type],value:this.scanner.source.slice(a.start,a.end)};if(this.trackRange&&(u.range=[a.start,a.end]),this.trackLoc&&(s.end={line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart},u.loc=s),9===a.type){var c=a.pattern,l=a.flags;u.regex={pattern:c,flags:l}}this.buffer.push(u)}}return this.buffer.shift()},t}();e.Tokenizer=a}])},t.exports=r()},function(t,e,n){"use strict";var r,i,o,s,a,u,c,l=n(66),h=n(12),f=Function.prototype.apply,p=Function.prototype.call,d=Object.create,m=Object.defineProperty,v=Object.defineProperties,y=Object.prototype.hasOwnProperty,g={configurable:!0,enumerable:!1,writable:!0};a={on:r=function(t,e){var n;return h(e),y.call(this,"__ee__")?n=this.__ee__:(n=g.value=d(null),m(this,"__ee__",g),g.value=null),n[t]?"object"==typeof n[t]?n[t].push(e):n[t]=[n[t],e]:n[t]=e,this},once:i=function(t,e){var n,i;return h(e),i=this,r.call(this,t,n=function(){o.call(i,t,n),f.call(e,this,arguments)}),n.__eeOnceListener__=e,this},off:o=function(t,e){var n,r,i,o;if(h(e),!y.call(this,"__ee__"))return this;if(!(n=this.__ee__)[t])return this;if("object"==typeof(r=n[t]))for(o=0;i=r[o];++o)i!==e&&i.__eeOnceListener__!==e||(2===r.length?n[t]=r[o?0:1]:r.splice(o,1));else r!==e&&r.__eeOnceListener__!==e||delete n[t];return this},emit:s=function(t){var e,n,r,i,o;if(y.call(this,"__ee__")&&(i=this.__ee__[t]))if("object"==typeof i){for(n=arguments.length,o=new Array(n-1),e=1;e<n;++e)o[e-1]=arguments[e];for(i=i.slice(),e=0;r=i[e];++e)f.call(r,this,o)}else switch(arguments.length){case 1:p.call(i,this);break;case 2:p.call(i,this,arguments[1]);break;case 3:p.call(i,this,arguments[1],arguments[2]);break;default:for(n=arguments.length,o=new Array(n-1),e=1;e<n;++e)o[e-1]=arguments[e];f.call(i,this,o)}}},u={on:l(r),once:l(i),off:l(o),emit:l(s)},c=v({},u),t.exports=e=function(t){return null==t?d(c):v(Object(t),u)},e.methods=a},function(t,e){e.read=function(t,e,n,r,i){var o,s,a=8*i-r-1,u=(1<<a)-1,c=u>>1,l=-7,h=n?i-1:0,f=n?-1:1,p=t[e+h];for(h+=f,o=p&(1<<-l)-1,p>>=-l,l+=a;l>0;o=256*o+t[e+h],h+=f,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=r;l>0;s=256*s+t[e+h],h+=f,l-=8);if(0===o)o=1-c;else{if(o===u)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,r),o-=c}return(p?-1:1)*s*Math.pow(2,o-r)},e.write=function(t,e,n,r,i,o){var s,a,u,c=8*o-i-1,l=(1<<c)-1,h=l>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:o-1,d=r?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=l):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+h>=1?f/u:f*Math.pow(2,1-h))*u>=2&&(s++,u/=2),s+h>=l?(a=0,s=l):s+h>=1?(a=(e*u-1)*Math.pow(2,i),s+=h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;t[n+p]=255&a,p+=d,a/=256,i-=8);for(s=s<<i|a,c+=i;c>0;t[n+p]=255&s,p+=d,s/=256,c-=8);t[n+p-d]|=128*m}},function(t,e,n){"use strict";var r=n(362);t.exports=r},function(t,e,n){"use strict";var r=n(364),i=n(363);function o(t){return function(){throw new Error("Function "+t+" is deprecated and cannot be used.")}}t.exports.Type=n(0),t.exports.Schema=n(34),t.exports.FAILSAFE_SCHEMA=n(113),t.exports.JSON_SCHEMA=n(171),t.exports.CORE_SCHEMA=n(170),t.exports.DEFAULT_SAFE_SCHEMA=n(48),t.exports.DEFAULT_FULL_SCHEMA=n(70),t.exports.load=r.load,t.exports.loadAll=r.loadAll,t.exports.safeLoad=r.safeLoad,t.exports.safeLoadAll=r.safeLoadAll,t.exports.dump=i.dump,t.exports.safeDump=i.safeDump,t.exports.YAMLException=n(47),t.exports.MINIMAL_SCHEMA=n(113),t.exports.SAFE_SCHEMA=n(48),t.exports.DEFAULT_SCHEMA=n(70),t.exports.scan=o("scan"),t.exports.parse=o("parse"),t.exports.compose=o("compose"),t.exports.addConstructor=o("addConstructor")},function(t,e,n){"use strict";var r=n(33),i=n(47),o=n(70),s=n(48),a=Object.prototype.toString,u=Object.prototype.hasOwnProperty,c=9,l=10,h=32,f=33,p=34,d=35,m=37,v=38,y=39,g=42,x=44,b=45,D=58,E=62,w=63,_=64,S=91,A=93,C=96,k=123,F=124,T=125,I={0:"\\0",7:"\\a",8:"\\b",9:"\\t",10:"\\n",11:"\\v",12:"\\f",13:"\\r",27:"\\e",34:'\\"',92:"\\\\",133:"\\N",160:"\\_",8232:"\\L",8233:"\\P"},O=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"];function M(t){var e,n,o;if(e=t.toString(16).toUpperCase(),t<=255)n="x",o=2;else if(t<=65535)n="u",o=4;else{if(!(t<=4294967295))throw new i("code point within a string may not be greater than 0xFFFFFFFF");n="U",o=8}return"\\"+n+r.repeat("0",o-e.length)+e}function B(t){this.schema=t.schema||o,this.indent=Math.max(1,t.indent||2),this.skipInvalid=t.skipInvalid||!1,this.flowLevel=r.isNothing(t.flowLevel)?-1:t.flowLevel,this.styleMap=function(t,e){var n,r,i,o,s,a,c;if(null===e)return{};for(n={},i=0,o=(r=Object.keys(e)).length;i<o;i+=1)s=r[i],a=String(e[s]),"!!"===s.slice(0,2)&&(s="tag:yaml.org,2002:"+s.slice(2)),(c=t.compiledTypeMap.fallback[s])&&u.call(c.styleAliases,a)&&(a=c.styleAliases[a]),n[s]=a;return n}(this.schema,t.styles||null),this.sortKeys=t.sortKeys||!1,this.lineWidth=t.lineWidth||80,this.noRefs=t.noRefs||!1,this.noCompatMode=t.noCompatMode||!1,this.condenseFlow=t.condenseFlow||!1,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function P(t,e){for(var n,i=r.repeat(" ",e),o=0,s=-1,a="",u=t.length;o<u;)-1===(s=t.indexOf("\n",o))?(n=t.slice(o),o=u):(n=t.slice(o,s+1),o=s+1),n.length&&"\n"!==n&&(a+=i),a+=n;return a}function j(t,e){return"\n"+r.repeat(" ",t.indent*e)}function N(t){return t===h||t===c}function L(t){return 32<=t&&t<=126||161<=t&&t<=55295&&8232!==t&&8233!==t||57344<=t&&t<=65533&&65279!==t||65536<=t&&t<=1114111}function R(t){return L(t)&&65279!==t&&t!==x&&t!==S&&t!==A&&t!==k&&t!==T&&t!==D&&t!==d}var z=1,U=2,J=3,X=4,q=5;function K(t,e,n,r,i){var o,s,a,u=!1,c=!1,h=-1!==r,I=-1,O=L(a=t.charCodeAt(0))&&65279!==a&&!N(a)&&a!==b&&a!==w&&a!==D&&a!==x&&a!==S&&a!==A&&a!==k&&a!==T&&a!==d&&a!==v&&a!==g&&a!==f&&a!==F&&a!==E&&a!==y&&a!==p&&a!==m&&a!==_&&a!==C&&!N(t.charCodeAt(t.length-1));if(e)for(o=0;o<t.length;o++){if(!L(s=t.charCodeAt(o)))return q;O=O&&R(s)}else{for(o=0;o<t.length;o++){if((s=t.charCodeAt(o))===l)u=!0,h&&(c=c||o-I-1>r&&" "!==t[I+1],I=o);else if(!L(s))return q;O=O&&R(s)}c=c||h&&o-I-1>r&&" "!==t[I+1]}return u||c?" "===t[0]&&n>9?q:c?X:J:O&&!i(t)?z:U}function W(t,e,n,r){t.dump=function(){if(0===e.length)return"''";if(!t.noCompatMode&&-1!==O.indexOf(e))return"'"+e+"'";var o=t.indent*Math.max(1,n),s=-1===t.lineWidth?-1:Math.max(Math.min(t.lineWidth,40),t.lineWidth-o),a=r||t.flowLevel>-1&&n>=t.flowLevel;switch(K(e,a,t.indent,s,function(e){return function(t,e){var n,r;for(n=0,r=t.implicitTypes.length;n<r;n+=1)if(t.implicitTypes[n].resolve(e))return!0;return!1}(t,e)})){case z:return e;case U:return"'"+e.replace(/'/g,"''")+"'";case J:return"|"+Y(e,t.indent)+H(P(e,o));case X:return">"+Y(e,t.indent)+H(P(function(t,e){var n,r,i=/(\n+)([^\n]*)/g,o=(a=t.indexOf("\n"),a=-1!==a?a:t.length,i.lastIndex=a,V(t.slice(0,a),e)),s="\n"===t[0]||" "===t[0];var a;for(;r=i.exec(t);){var u=r[1],c=r[2];n=" "===c[0],o+=u+(s||n||""===c?"":"\n")+V(c,e),s=n}return o}(e,s),o));case q:return'"'+function(t){for(var e,n,r,i="",o=0;o<t.length;o++)(e=t.charCodeAt(o))>=55296&&e<=56319&&(n=t.charCodeAt(o+1))>=56320&&n<=57343?(i+=M(1024*(e-55296)+n-56320+65536),o++):(r=I[e],i+=!r&&L(e)?t[o]:r||M(e));return i}(e)+'"';default:throw new i("impossible error: invalid scalar style")}}()}function Y(t,e){var n=" "===t[0]?String(e):"",r="\n"===t[t.length-1];return n+(r&&("\n"===t[t.length-2]||"\n"===t)?"+":r?"":"-")+"\n"}function H(t){return"\n"===t[t.length-1]?t.slice(0,-1):t}function V(t,e){if(""===t||" "===t[0])return t;for(var n,r,i=/ [^ ]/g,o=0,s=0,a=0,u="";n=i.exec(t);)(a=n.index)-o>e&&(r=s>o?s:a,u+="\n"+t.slice(o,r),o=r+1),s=a;return u+="\n",t.length-o>e&&s>o?u+=t.slice(o,s)+"\n"+t.slice(s+1):u+=t.slice(o),u.slice(1)}function G(t,e,n){var r,o,s,c,l,h;for(s=0,c=(o=n?t.explicitTypes:t.implicitTypes).length;s<c;s+=1)if(((l=o[s]).instanceOf||l.predicate)&&(!l.instanceOf||"object"==typeof e&&e instanceof l.instanceOf)&&(!l.predicate||l.predicate(e))){if(t.tag=n?l.tag:"?",l.represent){if(h=t.styleMap[l.tag]||l.defaultStyle,"[object Function]"===a.call(l.represent))r=l.represent(e,h);else{if(!u.call(l.represent,h))throw new i("!<"+l.tag+'> tag resolver accepts not "'+h+'" style');r=l.represent[h](e,h)}t.dump=r}return!0}return!1}function $(t,e,n,r,o,s){t.tag=null,t.dump=n,G(t,n,!1)||G(t,n,!0);var u=a.call(t.dump);r&&(r=t.flowLevel<0||t.flowLevel>e);var c,h,f="[object Object]"===u||"[object Array]"===u;if(f&&(h=-1!==(c=t.duplicates.indexOf(n))),(null!==t.tag&&"?"!==t.tag||h||2!==t.indent&&e>0)&&(o=!1),h&&t.usedDuplicates[c])t.dump="*ref_"+c;else{if(f&&h&&!t.usedDuplicates[c]&&(t.usedDuplicates[c]=!0),"[object Object]"===u)r&&0!==Object.keys(t.dump).length?(!function(t,e,n,r){var o,s,a,u,c,h,f="",p=t.tag,d=Object.keys(n);if(!0===t.sortKeys)d.sort();else if("function"==typeof t.sortKeys)d.sort(t.sortKeys);else if(t.sortKeys)throw new i("sortKeys must be a boolean or a function");for(o=0,s=d.length;o<s;o+=1)h="",r&&0===o||(h+=j(t,e)),u=n[a=d[o]],$(t,e+1,a,!0,!0,!0)&&((c=null!==t.tag&&"?"!==t.tag||t.dump&&t.dump.length>1024)&&(t.dump&&l===t.dump.charCodeAt(0)?h+="?":h+="? "),h+=t.dump,c&&(h+=j(t,e)),$(t,e+1,u,!0,c)&&(t.dump&&l===t.dump.charCodeAt(0)?h+=":":h+=": ",f+=h+=t.dump));t.tag=p,t.dump=f||"{}"}(t,e,t.dump,o),h&&(t.dump="&ref_"+c+t.dump)):(!function(t,e,n){var r,i,o,s,a,u="",c=t.tag,l=Object.keys(n);for(r=0,i=l.length;r<i;r+=1)a=t.condenseFlow?'"':"",0!==r&&(a+=", "),s=n[o=l[r]],$(t,e,o,!1,!1)&&(t.dump.length>1024&&(a+="? "),a+=t.dump+(t.condenseFlow?'"':"")+":"+(t.condenseFlow?"":" "),$(t,e,s,!1,!1)&&(u+=a+=t.dump));t.tag=c,t.dump="{"+u+"}"}(t,e,t.dump),h&&(t.dump="&ref_"+c+" "+t.dump));else if("[object Array]"===u)r&&0!==t.dump.length?(!function(t,e,n,r){var i,o,s="",a=t.tag;for(i=0,o=n.length;i<o;i+=1)$(t,e+1,n[i],!0,!0)&&(r&&0===i||(s+=j(t,e)),t.dump&&l===t.dump.charCodeAt(0)?s+="-":s+="- ",s+=t.dump);t.tag=a,t.dump=s||"[]"}(t,e,t.dump,o),h&&(t.dump="&ref_"+c+t.dump)):(!function(t,e,n){var r,i,o="",s=t.tag;for(r=0,i=n.length;r<i;r+=1)$(t,e,n[r],!1,!1)&&(0!==r&&(o+=","+(t.condenseFlow?"":" ")),o+=t.dump);t.tag=s,t.dump="["+o+"]"}(t,e,t.dump),h&&(t.dump="&ref_"+c+" "+t.dump));else{if("[object String]"!==u){if(t.skipInvalid)return!1;throw new i("unacceptable kind of an object to dump "+u)}"?"!==t.tag&&W(t,t.dump,e,s)}null!==t.tag&&"?"!==t.tag&&(t.dump="!<"+t.tag+"> "+t.dump)}return!0}function Z(t,e){var n,r,i=[],o=[];for(function t(e,n,r){var i,o,s;if(null!==e&&"object"==typeof e)if(-1!==(o=n.indexOf(e)))-1===r.indexOf(o)&&r.push(o);else if(n.push(e),Array.isArray(e))for(o=0,s=e.length;o<s;o+=1)t(e[o],n,r);else for(i=Object.keys(e),o=0,s=i.length;o<s;o+=1)t(e[i[o]],n,r)}(t,i,o),n=0,r=o.length;n<r;n+=1)e.duplicates.push(i[o[n]]);e.usedDuplicates=new Array(r)}function Q(t,e){var n=new B(e=e||{});return n.noRefs||Z(t,n),$(n,0,t,!0,!0)?n.dump+"\n":""}t.exports.dump=Q,t.exports.safeDump=function(t,e){return Q(t,r.extend({schema:s},e))}},function(t,e,n){"use strict";var r=n(33),i=n(47),o=n(365),s=n(48),a=n(70),u=Object.prototype.hasOwnProperty,c=1,l=2,h=3,f=4,p=1,d=2,m=3,v=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,y=/[\x85\u2028\u2029]/,g=/[,\[\]\{\}]/,x=/^(?:!|!!|![a-z\-]+!)$/i,b=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function D(t){return 10===t||13===t}function E(t){return 9===t||32===t}function w(t){return 9===t||32===t||10===t||13===t}function _(t){return 44===t||91===t||93===t||123===t||125===t}function S(t){var e;return 48<=t&&t<=57?t-48:97<=(e=32|t)&&e<=102?e-97+10:-1}function A(t){return 48===t?"\0":97===t?"":98===t?"\b":116===t?"\t":9===t?"\t":110===t?"\n":118===t?"\v":102===t?"\f":114===t?"\r":101===t?"":32===t?" ":34===t?'"':47===t?"/":92===t?"\\":78===t?"
":95===t?" ":76===t?"\u2028":80===t?"\u2029":""}function C(t){return t<=65535?String.fromCharCode(t):String.fromCharCode(55296+(t-65536>>10),56320+(t-65536&1023))}for(var k=new Array(256),F=new Array(256),T=0;T<256;T++)k[T]=A(T)?1:0,F[T]=A(T);function I(t,e){return new i(e,new o(t.filename,t.input,t.position,t.line,t.position-t.lineStart))}function O(t,e){throw I(t,e)}function M(t,e){t.onWarning&&t.onWarning.call(null,I(t,e))}var B={YAML:function(t,e,n){var r,i,o;null!==t.version&&O(t,"duplication of %YAML directive"),1!==n.length&&O(t,"YAML directive accepts exactly one argument"),null===(r=/^([0-9]+)\.([0-9]+)$/.exec(n[0]))&&O(t,"ill-formed argument of the YAML directive"),i=parseInt(r[1],10),o=parseInt(r[2],10),1!==i&&O(t,"unacceptable YAML version of the document"),t.version=n[0],t.checkLineBreaks=o<2,1!==o&&2!==o&&M(t,"unsupported YAML version of the document")},TAG:function(t,e,n){var r,i;2!==n.length&&O(t,"TAG directive accepts exactly two arguments"),r=n[0],i=n[1],x.test(r)||O(t,"ill-formed tag handle (first argument) of the TAG directive"),u.call(t.tagMap,r)&&O(t,'there is a previously declared suffix for "'+r+'" tag handle'),b.test(i)||O(t,"ill-formed tag prefix (second argument) of the TAG directive"),t.tagMap[r]=i}};function P(t,e,n,r){var i,o,s,a;if(e<n){if(a=t.input.slice(e,n),r)for(i=0,o=a.length;i<o;i+=1)9===(s=a.charCodeAt(i))||32<=s&&s<=1114111||O(t,"expected valid JSON character");else v.test(a)&&O(t,"the stream contains non-printable characters");t.result+=a}}function j(t,e,n,i){var o,s,a,c;for(r.isObject(n)||O(t,"cannot merge mappings; the provided source object is unacceptable"),a=0,c=(o=Object.keys(n)).length;a<c;a+=1)s=o[a],u.call(e,s)||(e[s]=n[s],i[s]=!0)}function N(t,e,n,r,i,o,s,a){var c,l;if(i=String(i),null===e&&(e={}),"tag:yaml.org,2002:merge"===r)if(Array.isArray(o))for(c=0,l=o.length;c<l;c+=1)j(t,e,o[c],n);else j(t,e,o,n);else t.json||u.call(n,i)||!u.call(e,i)||(t.line=s||t.line,t.position=a||t.position,O(t,"duplicated mapping key")),e[i]=o,delete n[i];return e}function L(t){var e;10===(e=t.input.charCodeAt(t.position))?t.position++:13===e?(t.position++,10===t.input.charCodeAt(t.position)&&t.position++):O(t,"a line break is expected"),t.line+=1,t.lineStart=t.position}function R(t,e,n){for(var r=0,i=t.input.charCodeAt(t.position);0!==i;){for(;E(i);)i=t.input.charCodeAt(++t.position);if(e&&35===i)do{i=t.input.charCodeAt(++t.position)}while(10!==i&&13!==i&&0!==i);if(!D(i))break;for(L(t),i=t.input.charCodeAt(t.position),r++,t.lineIndent=0;32===i;)t.lineIndent++,i=t.input.charCodeAt(++t.position)}return-1!==n&&0!==r&&t.lineIndent<n&&M(t,"deficient indentation"),r}function z(t){var e,n=t.position;return!(45!==(e=t.input.charCodeAt(n))&&46!==e||e!==t.input.charCodeAt(n+1)||e!==t.input.charCodeAt(n+2)||(n+=3,0!==(e=t.input.charCodeAt(n))&&!w(e)))}function U(t,e){1===e?t.result+=" ":e>1&&(t.result+=r.repeat("\n",e-1))}function J(t,e){var n,r,i=t.tag,o=t.anchor,s=[],a=!1;for(null!==t.anchor&&(t.anchorMap[t.anchor]=s),r=t.input.charCodeAt(t.position);0!==r&&45===r&&w(t.input.charCodeAt(t.position+1));)if(a=!0,t.position++,R(t,!0,-1)&&t.lineIndent<=e)s.push(null),r=t.input.charCodeAt(t.position);else if(n=t.line,K(t,e,h,!1,!0),s.push(t.result),R(t,!0,-1),r=t.input.charCodeAt(t.position),(t.line===n||t.lineIndent>e)&&0!==r)O(t,"bad indentation of a sequence entry");else if(t.lineIndent<e)break;return!!a&&(t.tag=i,t.anchor=o,t.kind="sequence",t.result=s,!0)}function X(t){var e,n,r,i,o=!1,s=!1;if(33!==(i=t.input.charCodeAt(t.position)))return!1;if(null!==t.tag&&O(t,"duplication of a tag property"),60===(i=t.input.charCodeAt(++t.position))?(o=!0,i=t.input.charCodeAt(++t.position)):33===i?(s=!0,n="!!",i=t.input.charCodeAt(++t.position)):n="!",e=t.position,o){do{i=t.input.charCodeAt(++t.position)}while(0!==i&&62!==i);t.position<t.length?(r=t.input.slice(e,t.position),i=t.input.charCodeAt(++t.position)):O(t,"unexpected end of the stream within a verbatim tag")}else{for(;0!==i&&!w(i);)33===i&&(s?O(t,"tag suffix cannot contain exclamation marks"):(n=t.input.slice(e-1,t.position+1),x.test(n)||O(t,"named tag handle cannot contain such characters"),s=!0,e=t.position+1)),i=t.input.charCodeAt(++t.position);r=t.input.slice(e,t.position),g.test(r)&&O(t,"tag suffix cannot contain flow indicator characters")}return r&&!b.test(r)&&O(t,"tag name cannot contain such characters: "+r),o?t.tag=r:u.call(t.tagMap,n)?t.tag=t.tagMap[n]+r:"!"===n?t.tag="!"+r:"!!"===n?t.tag="tag:yaml.org,2002:"+r:O(t,'undeclared tag handle "'+n+'"'),!0}function q(t){var e,n;if(38!==(n=t.input.charCodeAt(t.position)))return!1;for(null!==t.anchor&&O(t,"duplication of an anchor property"),n=t.input.charCodeAt(++t.position),e=t.position;0!==n&&!w(n)&&!_(n);)n=t.input.charCodeAt(++t.position);return t.position===e&&O(t,"name of an anchor node must contain at least one character"),t.anchor=t.input.slice(e,t.position),!0}function K(t,e,n,i,o){var s,a,v,y,g,x,b,A,T=1,I=!1,M=!1;if(null!==t.listener&&t.listener("open",t),t.tag=null,t.anchor=null,t.kind=null,t.result=null,s=a=v=f===n||h===n,i&&R(t,!0,-1)&&(I=!0,t.lineIndent>e?T=1:t.lineIndent===e?T=0:t.lineIndent<e&&(T=-1)),1===T)for(;X(t)||q(t);)R(t,!0,-1)?(I=!0,v=s,t.lineIndent>e?T=1:t.lineIndent===e?T=0:t.lineIndent<e&&(T=-1)):v=!1;if(v&&(v=I||o),1!==T&&f!==n||(b=c===n||l===n?e:e+1,A=t.position-t.lineStart,1===T?v&&(J(t,A)||function(t,e,n){var r,i,o,s,a,u=t.tag,c=t.anchor,h={},p={},d=null,m=null,v=null,y=!1,g=!1;for(null!==t.anchor&&(t.anchorMap[t.anchor]=h),a=t.input.charCodeAt(t.position);0!==a;){if(r=t.input.charCodeAt(t.position+1),o=t.line,s=t.position,63!==a&&58!==a||!w(r)){if(!K(t,n,l,!1,!0))break;if(t.line===o){for(a=t.input.charCodeAt(t.position);E(a);)a=t.input.charCodeAt(++t.position);if(58===a)w(a=t.input.charCodeAt(++t.position))||O(t,"a whitespace character is expected after the key-value separator within a block mapping"),y&&(N(t,h,p,d,m,null),d=m=v=null),g=!0,y=!1,i=!1,d=t.tag,m=t.result;else{if(!g)return t.tag=u,t.anchor=c,!0;O(t,"can not read an implicit mapping pair; a colon is missed")}}else{if(!g)return t.tag=u,t.anchor=c,!0;O(t,"can not read a block mapping entry; a multiline key may not be an implicit key")}}else 63===a?(y&&(N(t,h,p,d,m,null),d=m=v=null),g=!0,y=!0,i=!0):y?(y=!1,i=!0):O(t,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),t.position+=1,a=r;if((t.line===o||t.lineIndent>e)&&(K(t,e,f,!0,i)&&(y?m=t.result:v=t.result),y||(N(t,h,p,d,m,v,o,s),d=m=v=null),R(t,!0,-1),a=t.input.charCodeAt(t.position)),t.lineIndent>e&&0!==a)O(t,"bad indentation of a mapping entry");else if(t.lineIndent<e)break}return y&&N(t,h,p,d,m,null),g&&(t.tag=u,t.anchor=c,t.kind="mapping",t.result=h),g}(t,A,b))||function(t,e){var n,r,i,o,s,a,u,l,h,f,p=!0,d=t.tag,m=t.anchor,v={};if(91===(f=t.input.charCodeAt(t.position)))i=93,a=!1,r=[];else{if(123!==f)return!1;i=125,a=!0,r={}}for(null!==t.anchor&&(t.anchorMap[t.anchor]=r),f=t.input.charCodeAt(++t.position);0!==f;){if(R(t,!0,e),(f=t.input.charCodeAt(t.position))===i)return t.position++,t.tag=d,t.anchor=m,t.kind=a?"mapping":"sequence",t.result=r,!0;p||O(t,"missed comma between flow collection entries"),l=u=h=null,o=s=!1,63===f&&w(t.input.charCodeAt(t.position+1))&&(o=s=!0,t.position++,R(t,!0,e)),n=t.line,K(t,e,c,!1,!0),l=t.tag,u=t.result,R(t,!0,e),f=t.input.charCodeAt(t.position),!s&&t.line!==n||58!==f||(o=!0,f=t.input.charCodeAt(++t.position),R(t,!0,e),K(t,e,c,!1,!0),h=t.result),a?N(t,r,v,l,u,h):o?r.push(N(t,null,v,l,u,h)):r.push(u),R(t,!0,e),44===(f=t.input.charCodeAt(t.position))?(p=!0,f=t.input.charCodeAt(++t.position)):p=!1}O(t,"unexpected end of the stream within a flow collection")}(t,b)?M=!0:(a&&function(t,e){var n,i,o,s,a,u=p,c=!1,l=!1,h=e,f=0,v=!1;if(124===(s=t.input.charCodeAt(t.position)))i=!1;else{if(62!==s)return!1;i=!0}for(t.kind="scalar",t.result="";0!==s;)if(43===(s=t.input.charCodeAt(++t.position))||45===s)p===u?u=43===s?m:d:O(t,"repeat of a chomping mode identifier");else{if(!((o=48<=(a=s)&&a<=57?a-48:-1)>=0))break;0===o?O(t,"bad explicit indentation width of a block scalar; it cannot be less than one"):l?O(t,"repeat of an indentation width identifier"):(h=e+o-1,l=!0)}if(E(s)){do{s=t.input.charCodeAt(++t.position)}while(E(s));if(35===s)do{s=t.input.charCodeAt(++t.position)}while(!D(s)&&0!==s)}for(;0!==s;){for(L(t),t.lineIndent=0,s=t.input.charCodeAt(t.position);(!l||t.lineIndent<h)&&32===s;)t.lineIndent++,s=t.input.charCodeAt(++t.position);if(!l&&t.lineIndent>h&&(h=t.lineIndent),D(s))f++;else{if(t.lineIndent<h){u===m?t.result+=r.repeat("\n",c?1+f:f):u===p&&c&&(t.result+="\n");break}for(i?E(s)?(v=!0,t.result+=r.repeat("\n",c?1+f:f)):v?(v=!1,t.result+=r.repeat("\n",f+1)):0===f?c&&(t.result+=" "):t.result+=r.repeat("\n",f):t.result+=r.repeat("\n",c?1+f:f),c=!0,l=!0,f=0,n=t.position;!D(s)&&0!==s;)s=t.input.charCodeAt(++t.position);P(t,n,t.position,!1)}}return!0}(t,b)||function(t,e){var n,r,i;if(39!==(n=t.input.charCodeAt(t.position)))return!1;for(t.kind="scalar",t.result="",t.position++,r=i=t.position;0!==(n=t.input.charCodeAt(t.position));)if(39===n){if(P(t,r,t.position,!0),39!==(n=t.input.charCodeAt(++t.position)))return!0;r=t.position,t.position++,i=t.position}else D(n)?(P(t,r,i,!0),U(t,R(t,!1,e)),r=i=t.position):t.position===t.lineStart&&z(t)?O(t,"unexpected end of the document within a single quoted scalar"):(t.position++,i=t.position);O(t,"unexpected end of the stream within a single quoted scalar")}(t,b)||function(t,e){var n,r,i,o,s,a,u;if(34!==(a=t.input.charCodeAt(t.position)))return!1;for(t.kind="scalar",t.result="",t.position++,n=r=t.position;0!==(a=t.input.charCodeAt(t.position));){if(34===a)return P(t,n,t.position,!0),t.position++,!0;if(92===a){if(P(t,n,t.position,!0),D(a=t.input.charCodeAt(++t.position)))R(t,!1,e);else if(a<256&&k[a])t.result+=F[a],t.position++;else if((s=120===(u=a)?2:117===u?4:85===u?8:0)>0){for(i=s,o=0;i>0;i--)(s=S(a=t.input.charCodeAt(++t.position)))>=0?o=(o<<4)+s:O(t,"expected hexadecimal character");t.result+=C(o),t.position++}else O(t,"unknown escape sequence");n=r=t.position}else D(a)?(P(t,n,r,!0),U(t,R(t,!1,e)),n=r=t.position):t.position===t.lineStart&&z(t)?O(t,"unexpected end of the document within a double quoted scalar"):(t.position++,r=t.position)}O(t,"unexpected end of the stream within a double quoted scalar")}(t,b)?M=!0:!function(t){var e,n,r;if(42!==(r=t.input.charCodeAt(t.position)))return!1;for(r=t.input.charCodeAt(++t.position),e=t.position;0!==r&&!w(r)&&!_(r);)r=t.input.charCodeAt(++t.position);return t.position===e&&O(t,"name of an alias node must contain at least one character"),n=t.input.slice(e,t.position),t.anchorMap.hasOwnProperty(n)||O(t,'unidentified alias "'+n+'"'),t.result=t.anchorMap[n],R(t,!0,-1),!0}(t)?function(t,e,n){var r,i,o,s,a,u,c,l,h=t.kind,f=t.result;if(w(l=t.input.charCodeAt(t.position))||_(l)||35===l||38===l||42===l||33===l||124===l||62===l||39===l||34===l||37===l||64===l||96===l)return!1;if((63===l||45===l)&&(w(r=t.input.charCodeAt(t.position+1))||n&&_(r)))return!1;for(t.kind="scalar",t.result="",i=o=t.position,s=!1;0!==l;){if(58===l){if(w(r=t.input.charCodeAt(t.position+1))||n&&_(r))break}else if(35===l){if(w(t.input.charCodeAt(t.position-1)))break}else{if(t.position===t.lineStart&&z(t)||n&&_(l))break;if(D(l)){if(a=t.line,u=t.lineStart,c=t.lineIndent,R(t,!1,-1),t.lineIndent>=e){s=!0,l=t.input.charCodeAt(t.position);continue}t.position=o,t.line=a,t.lineStart=u,t.lineIndent=c;break}}s&&(P(t,i,o,!1),U(t,t.line-a),i=o=t.position,s=!1),E(l)||(o=t.position+1),l=t.input.charCodeAt(++t.position)}return P(t,i,o,!1),!!t.result||(t.kind=h,t.result=f,!1)}(t,b,c===n)&&(M=!0,null===t.tag&&(t.tag="?")):(M=!0,null===t.tag&&null===t.anchor||O(t,"alias node should not have any properties")),null!==t.anchor&&(t.anchorMap[t.anchor]=t.result)):0===T&&(M=v&&J(t,A))),null!==t.tag&&"!"!==t.tag)if("?"===t.tag){for(y=0,g=t.implicitTypes.length;y<g;y+=1)if((x=t.implicitTypes[y]).resolve(t.result)){t.result=x.construct(t.result),t.tag=x.tag,null!==t.anchor&&(t.anchorMap[t.anchor]=t.result);break}}else u.call(t.typeMap[t.kind||"fallback"],t.tag)?(x=t.typeMap[t.kind||"fallback"][t.tag],null!==t.result&&x.kind!==t.kind&&O(t,"unacceptable node kind for !<"+t.tag+'> tag; it should be "'+x.kind+'", not "'+t.kind+'"'),x.resolve(t.result)?(t.result=x.construct(t.result),null!==t.anchor&&(t.anchorMap[t.anchor]=t.result)):O(t,"cannot resolve a node with !<"+t.tag+"> explicit tag")):O(t,"unknown tag !<"+t.tag+">");return null!==t.listener&&t.listener("close",t),null!==t.tag||null!==t.anchor||M}function W(t){var e,n,r,i,o=t.position,s=!1;for(t.version=null,t.checkLineBreaks=t.legacy,t.tagMap={},t.anchorMap={};0!==(i=t.input.charCodeAt(t.position))&&(R(t,!0,-1),i=t.input.charCodeAt(t.position),!(t.lineIndent>0||37!==i));){for(s=!0,i=t.input.charCodeAt(++t.position),e=t.position;0!==i&&!w(i);)i=t.input.charCodeAt(++t.position);for(r=[],(n=t.input.slice(e,t.position)).length<1&&O(t,"directive name must not be less than one character in length");0!==i;){for(;E(i);)i=t.input.charCodeAt(++t.position);if(35===i){do{i=t.input.charCodeAt(++t.position)}while(0!==i&&!D(i));break}if(D(i))break;for(e=t.position;0!==i&&!w(i);)i=t.input.charCodeAt(++t.position);r.push(t.input.slice(e,t.position))}0!==i&&L(t),u.call(B,n)?B[n](t,n,r):M(t,'unknown document directive "'+n+'"')}R(t,!0,-1),0===t.lineIndent&&45===t.input.charCodeAt(t.position)&&45===t.input.charCodeAt(t.position+1)&&45===t.input.charCodeAt(t.position+2)?(t.position+=3,R(t,!0,-1)):s&&O(t,"directives end mark is expected"),K(t,t.lineIndent-1,f,!1,!0),R(t,!0,-1),t.checkLineBreaks&&y.test(t.input.slice(o,t.position))&&M(t,"non-ASCII line breaks are interpreted as content"),t.documents.push(t.result),t.position===t.lineStart&&z(t)?46===t.input.charCodeAt(t.position)&&(t.position+=3,R(t,!0,-1)):t.position<t.length-1&&O(t,"end of the stream or a document separator is expected")}function Y(t,e){t=String(t),e=e||{},0!==t.length&&(10!==t.charCodeAt(t.length-1)&&13!==t.charCodeAt(t.length-1)&&(t+="\n"),65279===t.charCodeAt(0)&&(t=t.slice(1)));var n=new function(t,e){this.input=t,this.filename=e.filename||null,this.schema=e.schema||a,this.onWarning=e.onWarning||null,this.legacy=e.legacy||!1,this.json=e.json||!1,this.listener=e.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=t.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}(t,e);for(n.input+="\0";32===n.input.charCodeAt(n.position);)n.lineIndent+=1,n.position+=1;for(;n.position<n.length-1;)W(n);return n.documents}function H(t,e,n){var r,i,o=Y(t,n);if("function"!=typeof e)return o;for(r=0,i=o.length;r<i;r+=1)e(o[r])}function V(t,e){var n=Y(t,e);if(0!==n.length){if(1===n.length)return n[0];throw new i("expected a single document in the stream, but found more")}}t.exports.loadAll=H,t.exports.load=V,t.exports.safeLoadAll=function(t,e,n){if("function"!=typeof e)return H(t,r.extend({schema:s},n));H(t,e,r.extend({schema:s},n))},t.exports.safeLoad=function(t,e){return V(t,r.extend({schema:s},e))}},function(t,e,n){"use strict";var r=n(33);function i(t,e,n,r,i){this.name=t,this.buffer=e,this.position=n,this.line=r,this.column=i}i.prototype.getSnippet=function(t,e){var n,i,o,s,a;if(!this.buffer)return null;for(t=t||4,e=e||75,n="",i=this.position;i>0&&-1==="\0\r\n
\u2028\u2029".indexOf(this.buffer.charAt(i-1));)if(i-=1,this.position-i>e/2-1){n=" ... ",i+=5;break}for(o="",s=this.position;s<this.buffer.length&&-1==="\0\r\n
\u2028\u2029".indexOf(this.buffer.charAt(s));)if((s+=1)-this.position>e/2-1){o=" ... ",s-=5;break}return a=this.buffer.slice(i,s),r.repeat(" ",t)+n+a+o+"\n"+r.repeat(" ",t+this.position-i+n.length)+"^"},i.prototype.toString=function(t){var e,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),t||(e=this.getSnippet())&&(n+=":\n"+e),n},t.exports=i},function(t,e,n){"use strict";var r;try{r=n(81).Buffer}catch(t){}var i=n(0),o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";t.exports=new i("tag:yaml.org,2002:binary",{kind:"scalar",resolve:function(t){if(null===t)return!1;var e,n,r=0,i=t.length,s=o;for(n=0;n<i;n++)if(!((e=s.indexOf(t.charAt(n)))>64)){if(e<0)return!1;r+=6}return r%8==0},construct:function(t){var e,n,i=t.replace(/[\r\n=]/g,""),s=i.length,a=o,u=0,c=[];for(e=0;e<s;e++)e%4==0&&e&&(c.push(u>>16&255),c.push(u>>8&255),c.push(255&u)),u=u<<6|a.indexOf(i.charAt(e));return 0==(n=s%4*6)?(c.push(u>>16&255),c.push(u>>8&255),c.push(255&u)):18===n?(c.push(u>>10&255),c.push(u>>2&255)):12===n&&c.push(u>>4&255),r?r.from?r.from(c):new r(c):c},predicate:function(t){return r&&r.isBuffer(t)},represent:function(t){var e,n,r="",i=0,s=t.length,a=o;for(e=0;e<s;e++)e%3==0&&e&&(r+=a[i>>18&63],r+=a[i>>12&63],r+=a[i>>6&63],r+=a[63&i]),i=(i<<8)+t[e];return 0==(n=s%3)?(r+=a[i>>18&63],r+=a[i>>12&63],r+=a[i>>6&63],r+=a[63&i]):2===n?(r+=a[i>>10&63],r+=a[i>>4&63],r+=a[i<<2&63],r+=a[64]):1===n&&(r+=a[i>>2&63],r+=a[i<<4&63],r+=a[64],r+=a[64]),r}})},function(t,e,n){"use strict";var r=n(0);t.exports=new r("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(t){if(null===t)return!1;var e=t.length;return 4===e&&("true"===t||"True"===t||"TRUE"===t)||5===e&&("false"===t||"False"===t||"FALSE"===t)},construct:function(t){return"true"===t||"True"===t||"TRUE"===t},predicate:function(t){return"[object Boolean]"===Object.prototype.toString.call(t)},represent:{lowercase:function(t){return t?"true":"false"},uppercase:function(t){return t?"TRUE":"FALSE"},camelcase:function(t){return t?"True":"False"}},defaultStyle:"lowercase"})},function(t,e,n){"use strict";var r=n(33),i=n(0),o=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var s=/^[-+]?[0-9]+e/;t.exports=new i("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(t){return null!==t&&!(!o.test(t)||"_"===t[t.length-1])},construct:function(t){var e,n,r,i;return n="-"===(e=t.replace(/_/g,"").toLowerCase())[0]?-1:1,i=[],"+-".indexOf(e[0])>=0&&(e=e.slice(1)),".inf"===e?1===n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===e?NaN:e.indexOf(":")>=0?(e.split(":").forEach(function(t){i.unshift(parseFloat(t,10))}),e=0,r=1,i.forEach(function(t){e+=t*r,r*=60}),n*e):n*parseFloat(e,10)},predicate:function(t){return"[object Number]"===Object.prototype.toString.call(t)&&(t%1!=0||r.isNegativeZero(t))},represent:function(t,e){var n;if(isNaN(t))switch(e){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===t)switch(e){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===t)switch(e){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(r.isNegativeZero(t))return"-0.0";return n=t.toString(10),s.test(n)?n.replace("e",".e"):n},defaultStyle:"lowercase"})},function(t,e,n){"use strict";var r=n(33),i=n(0);function o(t){return 48<=t&&t<=55}function s(t){return 48<=t&&t<=57}t.exports=new i("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(t){if(null===t)return!1;var e,n,r=t.length,i=0,a=!1;if(!r)return!1;if("-"!==(e=t[i])&&"+"!==e||(e=t[++i]),"0"===e){if(i+1===r)return!0;if("b"===(e=t[++i])){for(i++;i<r;i++)if("_"!==(e=t[i])){if("0"!==e&&"1"!==e)return!1;a=!0}return a&&"_"!==e}if("x"===e){for(i++;i<r;i++)if("_"!==(e=t[i])){if(!(48<=(n=t.charCodeAt(i))&&n<=57||65<=n&&n<=70||97<=n&&n<=102))return!1;a=!0}return a&&"_"!==e}for(;i<r;i++)if("_"!==(e=t[i])){if(!o(t.charCodeAt(i)))return!1;a=!0}return a&&"_"!==e}if("_"===e)return!1;for(;i<r;i++)if("_"!==(e=t[i])){if(":"===e)break;if(!s(t.charCodeAt(i)))return!1;a=!0}return!(!a||"_"===e)&&(":"!==e||/^(:[0-5]?[0-9])+$/.test(t.slice(i)))},construct:function(t){var e,n,r=t,i=1,o=[];return-1!==r.indexOf("_")&&(r=r.replace(/_/g,"")),"-"!==(e=r[0])&&"+"!==e||("-"===e&&(i=-1),e=(r=r.slice(1))[0]),"0"===r?0:"0"===e?"b"===r[1]?i*parseInt(r.slice(2),2):"x"===r[1]?i*parseInt(r,16):i*parseInt(r,8):-1!==r.indexOf(":")?(r.split(":").forEach(function(t){o.unshift(parseInt(t,10))}),r=0,n=1,o.forEach(function(t){r+=t*n,n*=60}),i*r):i*parseInt(r,10)},predicate:function(t){return"[object Number]"===Object.prototype.toString.call(t)&&t%1==0&&!r.isNegativeZero(t)},represent:{binary:function(t){return t>=0?"0b"+t.toString(2):"-0b"+t.toString(2).slice(1)},octal:function(t){return t>=0?"0"+t.toString(8):"-0"+t.toString(8).slice(1)},decimal:function(t){return t.toString(10)},hexadecimal:function(t){return t>=0?"0x"+t.toString(16).toUpperCase():"-0x"+t.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})},function(t,e,n){"use strict";var r;try{r=n(358)}catch(t){"undefined"!=typeof window&&(r=window.esprima)}var i=n(0);t.exports=new i("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:function(t){if(null===t)return!1;try{var e="("+t+")",n=r.parse(e,{range:!0});return"Program"===n.type&&1===n.body.length&&"ExpressionStatement"===n.body[0].type&&("ArrowFunctionExpression"===n.body[0].expression.type||"FunctionExpression"===n.body[0].expression.type)}catch(t){return!1}},construct:function(t){var e,n="("+t+")",i=r.parse(n,{range:!0}),o=[];if("Program"!==i.type||1!==i.body.length||"ExpressionStatement"!==i.body[0].type||"ArrowFunctionExpression"!==i.body[0].expression.type&&"FunctionExpression"!==i.body[0].expression.type)throw new Error("Failed to resolve function");return i.body[0].expression.params.forEach(function(t){o.push(t.name)}),e=i.body[0].expression.body.range,new Function(o,n.slice(e[0]+1,e[1]-1))},predicate:function(t){return"[object Function]"===Object.prototype.toString.call(t)},represent:function(t){return t.toString()}})},function(t,e,n){"use strict";var r=n(0);t.exports=new r("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:function(t){if(null===t)return!1;if(0===t.length)return!1;var e=t,n=/\/([gim]*)$/.exec(t),r="";if("/"===e[0]){if(n&&(r=n[1]),r.length>3)return!1;if("/"!==e[e.length-r.length-1])return!1}return!0},construct:function(t){var e=t,n=/\/([gim]*)$/.exec(t),r="";return"/"===e[0]&&(n&&(r=n[1]),e=e.slice(1,e.length-r.length-1)),new RegExp(e,r)},predicate:function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},represent:function(t){var e="/"+t.source+"/";return t.global&&(e+="g"),t.multiline&&(e+="m"),t.ignoreCase&&(e+="i"),e}})},function(t,e,n){"use strict";var r=n(0);t.exports=new r("tag:yaml.org,2002:js/undefined",{kind:"scalar",resolve:function(){return!0},construct:function(){},predicate:function(t){return void 0===t},represent:function(){return""}})},function(t,e,n){"use strict";var r=n(0);t.exports=new r("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return null!==t?t:{}}})},function(t,e,n){"use strict";var r=n(0);t.exports=new r("tag:yaml.org,2002:merge",{kind:"scalar",resolve:function(t){return"<<"===t||null===t}})},function(t,e,n){"use strict";var r=n(0);t.exports=new r("tag:yaml.org,2002:null",{kind:"scalar",resolve:function(t){if(null===t)return!0;var e=t.length;return 1===e&&"~"===t||4===e&&("null"===t||"Null"===t||"NULL"===t)},construct:function(){return null},predicate:function(t){return null===t},represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"}},defaultStyle:"lowercase"})},function(t,e,n){"use strict";var r=n(0),i=Object.prototype.hasOwnProperty,o=Object.prototype.toString;t.exports=new r("tag:yaml.org,2002:omap",{kind:"sequence",resolve:function(t){if(null===t)return!0;var e,n,r,s,a,u=[],c=t;for(e=0,n=c.length;e<n;e+=1){if(r=c[e],a=!1,"[object Object]"!==o.call(r))return!1;for(s in r)if(i.call(r,s)){if(a)return!1;a=!0}if(!a)return!1;if(-1!==u.indexOf(s))return!1;u.push(s)}return!0},construct:function(t){return null!==t?t:[]}})},function(t,e,n){"use strict";var r=n(0),i=Object.prototype.toString;t.exports=new r("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:function(t){if(null===t)return!0;var e,n,r,o,s,a=t;for(s=new Array(a.length),e=0,n=a.length;e<n;e+=1){if(r=a[e],"[object Object]"!==i.call(r))return!1;if(1!==(o=Object.keys(r)).length)return!1;s[e]=[o[0],r[o[0]]]}return!0},construct:function(t){if(null===t)return[];var e,n,r,i,o,s=t;for(o=new Array(s.length),e=0,n=s.length;e<n;e+=1)r=s[e],i=Object.keys(r),o[e]=[i[0],r[i[0]]];return o}})},function(t,e,n){"use strict";var r=n(0);t.exports=new r("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return null!==t?t:[]}})},function(t,e,n){"use strict";var r=n(0),i=Object.prototype.hasOwnProperty;t.exports=new r("tag:yaml.org,2002:set",{kind:"mapping",resolve:function(t){if(null===t)return!0;var e,n=t;for(e in n)if(i.call(n,e)&&null!==n[e])return!1;return!0},construct:function(t){return null!==t?t:{}}})},function(t,e,n){"use strict";var r=n(0);t.exports=new r("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return null!==t?t:""}})},function(t,e,n){"use strict";var r=n(0),i=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),o=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");t.exports=new r("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:function(t){return null!==t&&(null!==i.exec(t)||null!==o.exec(t))},construct:function(t){var e,n,r,s,a,u,c,l,h=0,f=null;if(null===(e=i.exec(t))&&(e=o.exec(t)),null===e)throw new Error("Date resolve error");if(n=+e[1],r=+e[2]-1,s=+e[3],!e[4])return new Date(Date.UTC(n,r,s));if(a=+e[4],u=+e[5],c=+e[6],e[7]){for(h=e[7].slice(0,3);h.length<3;)h+="0";h=+h}return e[9]&&(f=6e4*(60*+e[10]+ +(e[11]||0)),"-"===e[9]&&(f=-f)),l=new Date(Date.UTC(n,r,s,a,u,c,h)),f&&l.setTime(l.getTime()-f),l},instanceOf:Date,represent:function(t){return t.toISOString()}})},function(t,e,n){var r=n(35)(n(7),"DataView");t.exports=r},function(t,e,n){var r=n(437),i=n(438),o=n(439),s=n(440),a=n(441);function u(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}u.prototype.clear=r,u.prototype.delete=i,u.prototype.get=o,u.prototype.has=s,u.prototype.set=a,t.exports=u},function(t,e,n){var r=n(35)(n(7),"Promise");t.exports=r},function(t,e,n){var r=n(35)(n(7),"Set");t.exports=r},function(t,e,n){var r=n(115),i=n(462),o=n(463);function s(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new r;++e<n;)this.add(t[e])}s.prototype.add=s.prototype.push=i,s.prototype.has=o,t.exports=s},function(t,e,n){var r=n(7).Uint8Array;t.exports=r},function(t,e,n){var r=n(35)(n(7),"WeakMap");t.exports=r},function(t,e){t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=0,o=[];++n<r;){var s=t[n];e(s,n,t)&&(o[i++]=s)}return o}},function(t,e,n){var r=n(415),i=n(183),o=n(8),s=n(184),a=n(117),u=n(186),c=Object.prototype.hasOwnProperty;t.exports=function(t,e){var n=o(t),l=!n&&i(t),h=!n&&!l&&s(t),f=!n&&!l&&!h&&u(t),p=n||l||h||f,d=p?r(t.length,String):[],m=d.length;for(var v in t)!e&&!c.call(t,v)||p&&("length"==v||h&&("offset"==v||"parent"==v)||f&&("buffer"==v||"byteLength"==v||"byteOffset"==v)||a(v,m))||d.push(v);return d}},function(t,e){t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i}},function(t,e){t.exports=function(t,e){for(var n=-1,r=e.length,i=t.length;++n<r;)t[i+n]=e[n];return t}},function(t,e){t.exports=function(t,e,n,r){var i=-1,o=null==t?0:t.length;for(r&&o&&(n=t[++i]);++i<o;)n=e(n,t[i],i,t);return n}},function(t,e){t.exports=function(t){return t.split("")}},function(t,e){var n=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;t.exports=function(t){return t.match(n)||[]}},function(t,e,n){var r=n(399),i=n(421)(r);t.exports=i},function(t,e){t.exports=function(t,e,n,r){for(var i=t.length,o=n+(r?1:-1);r?o--:++o<i;)if(e(t[o],o,t))return o;return-1}},function(t,e,n){var r=n(422)();t.exports=r},function(t,e,n){var r=n(398),i=n(80);t.exports=function(t,e){return t&&r(t,e,i)}},function(t,e,n){var r=n(392),i=n(8);t.exports=function(t,e,n){var o=e(t);return i(t)?o:r(o,n(t))}},function(t,e){t.exports=function(t,e){return null!=t&&e in Object(t)}},function(t,e,n){var r=n(49),i=n(51),o="[object Arguments]";t.exports=function(t){return i(t)&&r(t)==o}},function(t,e,n){var r=n(172),i=n(177),o=n(427),s=n(428),a=n(433),u=n(8),c=n(184),l=n(186),h=1,f="[object Arguments]",p="[object Array]",d="[object Object]",m=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,v,y,g){var x=u(t),b=u(e),D=x?p:a(t),E=b?p:a(e),w=(D=D==f?d:D)==d,_=(E=E==f?d:E)==d,S=D==E;if(S&&c(t)){if(!c(e))return!1;x=!0,w=!1}if(S&&!w)return g||(g=new r),x||l(t)?i(t,e,n,v,y,g):o(t,e,D,n,v,y,g);if(!(n&h)){var A=w&&m.call(t,"__wrapped__"),C=_&&m.call(e,"__wrapped__");if(A||C){var k=A?t.value():t,F=C?e.value():e;return g||(g=new r),y(k,F,n,v,g)}}return!!S&&(g||(g=new r),s(t,e,n,v,y,g))}},function(t,e,n){var r=n(172),i=n(175),o=1,s=2;t.exports=function(t,e,n,a){var u=n.length,c=u,l=!a;if(null==t)return!c;for(t=Object(t);u--;){var h=n[u];if(l&&h[2]?h[1]!==t[h[0]]:!(h[0]in t))return!1}for(;++u<c;){var f=(h=n[u])[0],p=t[f],d=h[1];if(l&&h[2]){if(void 0===p&&!(f in t))return!1}else{var m=new r;if(a)var v=a(p,d,f,t,e,m);if(!(void 0===v?i(d,p,o|s,a,m):v))return!1}}return!0}},function(t,e,n){var r=n(185),i=n(444),o=n(50),s=n(182),a=/^\[object .+?Constructor\]$/,u=Function.prototype,c=Object.prototype,l=u.toString,h=c.hasOwnProperty,f=RegExp("^"+l.call(h).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(t){return!(!o(t)||i(t))&&(r(t)?f:a).test(s(t))}},function(t,e,n){var r=n(49),i=n(119),o=n(51),s={};s["[object Float32Array]"]=s["[object Float64Array]"]=s["[object Int8Array]"]=s["[object Int16Array]"]=s["[object Int32Array]"]=s["[object Uint8Array]"]=s["[object Uint8ClampedArray]"]=s["[object Uint16Array]"]=s["[object Uint32Array]"]=!0,s["[object Arguments]"]=s["[object Array]"]=s["[object ArrayBuffer]"]=s["[object Boolean]"]=s["[object DataView]"]=s["[object Date]"]=s["[object Error]"]=s["[object Function]"]=s["[object Map]"]=s["[object Number]"]=s["[object Object]"]=s["[object RegExp]"]=s["[object Set]"]=s["[object String]"]=s["[object WeakMap]"]=!1,t.exports=function(t){return o(t)&&i(t.length)&&!!s[r(t)]}},function(t,e,n){var r=n(445),i=n(458),o=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return i(t);var e=[];for(var n in Object(t))o.call(t,n)&&"constructor"!=n&&e.push(n);return e}},function(t,e,n){var r=n(404),i=n(430),o=n(181);t.exports=function(t){var e=i(t);return 1==e.length&&e[0][2]?o(e[0][0],e[0][1]):function(n){return n===t||r(n,t,e)}}},function(t,e,n){var r=n(175),i=n(479),o=n(480),s=n(118),a=n(180),u=n(181),c=n(76),l=1,h=2;t.exports=function(t,e){return s(t)&&a(e)?u(c(t),e):function(n){var s=i(n,t);return void 0===s&&s===e?o(n,t):r(e,s,l|h)}}},function(t,e){t.exports=function(t){return function(e){return null==e?void 0:e[t]}}},function(t,e,n){var r=n(174);t.exports=function(t){return function(e){return r(e,t)}}},function(t,e){t.exports=function(t){return function(e){return null==t?void 0:t[e]}}},function(t,e){t.exports=function(t,e,n){var r=-1,i=t.length;e<0&&(e=-e>i?0:i+e),(n=n>i?i:n)<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var o=Array(i);++r<i;)o[r]=t[r+e];return o}},function(t,e,n){var r=n(396);t.exports=function(t,e){var n;return r(t,function(t,r,i){return!(n=e(t,r,i))}),!!n}},function(t,e){t.exports=function(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}},function(t,e,n){var r=n(72),i=n(391),o=n(8),s=n(79),a=1/0,u=r?r.prototype:void 0,c=u?u.toString:void 0;t.exports=function t(e){if("string"==typeof e)return e;if(o(e))return i(e,t)+"";if(s(e))return c?c.call(e):"";var n=e+"";return"0"==n&&1/e==-a?"-0":n}},function(t,e){t.exports=function(t){return function(e){return t(e)}}},function(t,e){t.exports=function(t,e){return t.has(e)}},function(t,e,n){var r=n(413);t.exports=function(t,e,n){var i=t.length;return n=void 0===n?i:n,!e&&n>=i?t:r(t,e,n)}},function(t,e,n){var r=n(7)["__core-js_shared__"];t.exports=r},function(t,e,n){var r=n(78);t.exports=function(t,e){return function(n,i){if(null==n)return n;if(!r(n))return t(n,i);for(var o=n.length,s=e?o:-1,a=Object(n);(e?s--:++s<o)&&!1!==i(a[s],s,a););return n}}},function(t,e){t.exports=function(t){return function(e,n,r){for(var i=-1,o=Object(e),s=r(e),a=s.length;a--;){var u=s[t?a:++i];if(!1===n(o[u],u,o))break}return e}}},function(t,e,n){var r=n(419),i=n(179),o=n(470),s=n(52);t.exports=function(t){return function(e){e=s(e);var n=i(e)?o(e):void 0,a=n?n[0]:e.charAt(0),u=n?r(n,1).join(""):e.slice(1);return a[t]()+u}}},function(t,e,n){var r=n(393),i=n(476),o=n(489),s=RegExp("['’]","g");t.exports=function(t){return function(e){return r(o(i(e).replace(s,"")),t,"")}}},function(t,e,n){var r=n(116),i=n(78),o=n(80);t.exports=function(t){return function(e,n,s){var a=Object(e);if(!i(e)){var u=r(n,3);e=o(e),n=function(t){return u(a[t],t,a)}}var c=t(e,n,s);return c>-1?a[u?e[c]:c]:void 0}}},function(t,e,n){var r=n(412)({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"});t.exports=r},function(t,e,n){var r=n(72),i=n(387),o=n(77),s=n(177),a=n(456),u=n(464),c=1,l=2,h="[object Boolean]",f="[object Date]",p="[object Error]",d="[object Map]",m="[object Number]",v="[object RegExp]",y="[object Set]",g="[object String]",x="[object Symbol]",b="[object ArrayBuffer]",D="[object DataView]",E=r?r.prototype:void 0,w=E?E.valueOf:void 0;t.exports=function(t,e,n,r,E,_,S){switch(n){case D:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case b:return!(t.byteLength!=e.byteLength||!_(new i(t),new i(e)));case h:case f:case m:return o(+t,+e);case p:return t.name==e.name&&t.message==e.message;case v:case g:return t==e+"";case d:var A=a;case y:var C=r&c;if(A||(A=u),t.size!=e.size&&!C)return!1;var k=S.get(t);if(k)return k==e;r|=l,S.set(t,e);var F=s(A(t),A(e),r,E,_,S);return S.delete(t),F;case x:if(w)return w.call(t)==w.call(e)}return!1}},function(t,e,n){var r=n(429),i=1,o=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,s,a,u){var c=n&i,l=r(t),h=l.length;if(h!=r(e).length&&!c)return!1;for(var f=h;f--;){var p=l[f];if(!(c?p in e:o.call(e,p)))return!1}var d=u.get(t);if(d&&u.get(e))return d==e;var m=!0;u.set(t,e),u.set(e,t);for(var v=c;++f<h;){var y=t[p=l[f]],g=e[p];if(s)var x=c?s(g,y,p,e,t,u):s(y,g,p,t,e,u);if(!(void 0===x?y===g||a(y,g,n,s,u):x)){m=!1;break}v||(v="constructor"==p)}if(m&&!v){var b=t.constructor,D=e.constructor;b!=D&&"constructor"in t&&"constructor"in e&&!("function"==typeof b&&b instanceof b&&"function"==typeof D&&D instanceof D)&&(m=!1)}return u.delete(t),u.delete(e),m}},function(t,e,n){var r=n(400),i=n(432),o=n(80);t.exports=function(t){return r(t,o,i)}},function(t,e,n){var r=n(180),i=n(80);t.exports=function(t){for(var e=i(t),n=e.length;n--;){var o=e[n],s=t[o];e[n]=[o,s,r(s)]}return e}},function(t,e,n){var r=n(72),i=Object.prototype,o=i.hasOwnProperty,s=i.toString,a=r?r.toStringTag:void 0;t.exports=function(t){var e=o.call(t,a),n=t[a];try{t[a]=void 0;var r=!0}catch(t){}var i=s.call(t);return r&&(e?t[a]=n:delete t[a]),i}},function(t,e,n){var r=n(389),i=n(484),o=Object.prototype.propertyIsEnumerable,s=Object.getOwnPropertySymbols,a=s?function(t){return null==t?[]:(t=Object(t),r(s(t),function(e){return o.call(t,e)}))}:i;t.exports=a},function(t,e,n){var r=n(382),i=n(114),o=n(384),s=n(385),a=n(388),u=n(49),c=n(182),l=c(r),h=c(i),f=c(o),p=c(s),d=c(a),m=u;(r&&"[object DataView]"!=m(new r(new ArrayBuffer(1)))||i&&"[object Map]"!=m(new i)||o&&"[object Promise]"!=m(o.resolve())||s&&"[object Set]"!=m(new s)||a&&"[object WeakMap]"!=m(new a))&&(m=function(t){var e=u(t),n="[object Object]"==e?t.constructor:void 0,r=n?c(n):"";if(r)switch(r){case l:return"[object DataView]";case h:return"[object Map]";case f:return"[object Promise]";case p:return"[object Set]";case d:return"[object WeakMap]"}return e}),t.exports=m},function(t,e){t.exports=function(t,e){return null==t?void 0:t[e]}},function(t,e,n){var r=n(176),i=n(183),o=n(8),s=n(117),a=n(119),u=n(76);t.exports=function(t,e,n){for(var c=-1,l=(e=r(e,t)).length,h=!1;++c<l;){var f=u(e[c]);if(!(h=null!=t&&n(t,f)))break;t=t[f]}return h||++c!=l?h:!!(l=null==t?0:t.length)&&a(l)&&s(f,l)&&(o(t)||i(t))}},function(t,e){var n=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;t.exports=function(t){return n.test(t)}},function(t,e,n){var r=n(75);t.exports=function(){this.__data__=r?r(null):{},this.size=0}},function(t,e){t.exports=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}},function(t,e,n){var r=n(75),i="__lodash_hash_undefined__",o=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;if(r){var n=e[t];return n===i?void 0:n}return o.call(e,t)?e[t]:void 0}},function(t,e,n){var r=n(75),i=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;return r?void 0!==e[t]:i.call(e,t)}},function(t,e,n){var r=n(75),i="__lodash_hash_undefined__";t.exports=function(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=r&&void 0===e?i:e,this}},function(t,e,n){var r=n(77),i=n(78),o=n(117),s=n(50);t.exports=function(t,e,n){if(!s(n))return!1;var a=typeof e;return!!("number"==a?i(n)&&o(e,n.length):"string"==a&&e in n)&&r(n[e],t)}},function(t,e){t.exports=function(t){var e=typeof t;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t}},function(t,e,n){var r,i=n(420),o=(r=/[^.]+$/.exec(i&&i.keys&&i.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";t.exports=function(t){return!!o&&o in t}},function(t,e){var n=Object.prototype;t.exports=function(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||n)}},function(t,e){t.exports=function(){this.__data__=[],this.size=0}},function(t,e,n){var r=n(73),i=Array.prototype.splice;t.exports=function(t){var e=this.__data__,n=r(e,t);return!(n<0||(n==e.length-1?e.pop():i.call(e,n,1),--this.size,0))}},function(t,e,n){var r=n(73);t.exports=function(t){var e=this.__data__,n=r(e,t);return n<0?void 0:e[n][1]}},function(t,e,n){var r=n(73);t.exports=function(t){return r(this.__data__,t)>-1}},function(t,e,n){var r=n(73);t.exports=function(t,e){var n=this.__data__,i=r(n,t);return i<0?(++this.size,n.push([t,e])):n[i][1]=e,this}},function(t,e,n){var r=n(383),i=n(71),o=n(114);t.exports=function(){this.size=0,this.__data__={hash:new r,map:new(o||i),string:new r}}},function(t,e,n){var r=n(74);t.exports=function(t){var e=r(this,t).delete(t);return this.size-=e?1:0,e}},function(t,e,n){var r=n(74);t.exports=function(t){return r(this,t).get(t)}},function(t,e,n){var r=n(74);t.exports=function(t){return r(this,t).has(t)}},function(t,e,n){var r=n(74);t.exports=function(t,e){var n=r(this,t),i=n.size;return n.set(t,e),this.size+=n.size==i?0:1,this}},function(t,e){t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach(function(t,r){n[++e]=[r,t]}),n}},function(t,e,n){var r=n(187),i=500;t.exports=function(t){var e=r(t,function(t){return n.size===i&&n.clear(),t}),n=e.cache;return e}},function(t,e,n){var r=n(461)(Object.keys,Object);t.exports=r},function(t,e,n){(function(t){var r=n(178),i="object"==typeof e&&e&&!e.nodeType&&e,o=i&&"object"==typeof t&&t&&!t.nodeType&&t,s=o&&o.exports===i&&r.process,a=function(){try{return s&&s.binding&&s.binding("util")}catch(t){}}();t.exports=a}).call(e,n(204)(t))},function(t,e){var n=Object.prototype.toString;t.exports=function(t){return n.call(t)}},function(t,e){t.exports=function(t,e){return function(n){return t(e(n))}}},function(t,e){var n="__lodash_hash_undefined__";t.exports=function(t){return this.__data__.set(t,n),this}},function(t,e){t.exports=function(t){return this.__data__.has(t)}},function(t,e){t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach(function(t){n[++e]=t}),n}},function(t,e,n){var r=n(71);t.exports=function(){this.__data__=new r,this.size=0}},function(t,e){t.exports=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}},function(t,e){t.exports=function(t){return this.__data__.get(t)}},function(t,e){t.exports=function(t){return this.__data__.has(t)}},function(t,e,n){var r=n(71),i=n(114),o=n(115),s=200;t.exports=function(t,e){var n=this.__data__;if(n instanceof r){var a=n.__data__;if(!i||a.length<s-1)return a.push([t,e]),this.size=++n.size,this;n=this.__data__=new o(a)}return n.set(t,e),this.size=n.size,this}},function(t,e,n){var r=n(394),i=n(179),o=n(472);t.exports=function(t){return i(t)?o(t):r(t)}},function(t,e,n){var r=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,i=/\\(\\)?/g,o=n(457)(function(t){var e=[];return 46===t.charCodeAt(0)&&e.push(""),t.replace(r,function(t,n,r,o){e.push(r?o.replace(i,"$1"):n||t)}),e});t.exports=o},function(t,e){var n="[\\ud800-\\udfff]",r="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",i="\\ud83c[\\udffb-\\udfff]",o="[^\\ud800-\\udfff]",s="(?:\\ud83c[\\udde6-\\uddff]){2}",a="[\\ud800-\\udbff][\\udc00-\\udfff]",u="(?:"+r+"|"+i+")"+"?",c="[\\ufe0e\\ufe0f]?"+u+("(?:\\u200d(?:"+[o,s,a].join("|")+")[\\ufe0e\\ufe0f]?"+u+")*"),l="(?:"+[o+r+"?",r,s,a,n].join("|")+")",h=RegExp(i+"(?="+i+")|"+l+c,"g");t.exports=function(t){return t.match(h)||[]}},function(t,e){var n="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",r="["+n+"]",i="\\d+",o="[\\u2700-\\u27bf]",s="[a-z\\xdf-\\xf6\\xf8-\\xff]",a="[^\\ud800-\\udfff"+n+i+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",u="(?:\\ud83c[\\udde6-\\uddff]){2}",c="[\\ud800-\\udbff][\\udc00-\\udfff]",l="[A-Z\\xc0-\\xd6\\xd8-\\xde]",h="(?:"+s+"|"+a+")",f="(?:"+l+"|"+a+")",p="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",d="[\\ufe0e\\ufe0f]?"+p+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",u,c].join("|")+")[\\ufe0e\\ufe0f]?"+p+")*"),m="(?:"+[o,u,c].join("|")+")"+d,v=RegExp([l+"?"+s+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[r,l,"$"].join("|")+")",f+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[r,l+h,"$"].join("|")+")",l+"?"+h+"+(?:['’](?:d|ll|m|re|s|t|ve))?",l+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",i,m].join("|"),"g");t.exports=function(t){return t.match(v)||[]}},function(t,e,n){var r=n(475),i=n(424)(function(t,e,n){return e=e.toLowerCase(),t+(n?r(e):e)});t.exports=i},function(t,e,n){var r=n(52),i=n(188);t.exports=function(t){return i(r(t).toLowerCase())}},function(t,e,n){var r=n(426),i=n(52),o=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,s=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");t.exports=function(t){return(t=i(t))&&t.replace(o,r).replace(s,"")}},function(t,e,n){var r=n(425)(n(478));t.exports=r},function(t,e,n){var r=n(397),i=n(116),o=n(487),s=Math.max;t.exports=function(t,e,n){var a=null==t?0:t.length;if(!a)return-1;var u=null==n?0:o(n);return u<0&&(u=s(a+u,0)),r(t,i(e,3),u)}},function(t,e,n){var r=n(174);t.exports=function(t,e,n){var i=null==t?void 0:r(t,e);return void 0===i?n:i}},function(t,e,n){var r=n(401),i=n(435);t.exports=function(t,e){return null!=t&&i(t,e,r)}},function(t,e){t.exports=function(t){return t}},function(t,e,n){var r=n(410),i=n(411),o=n(118),s=n(76);t.exports=function(t){return o(t)?r(s(t)):i(t)}},function(t,e,n){var r=n(173),i=n(116),o=n(414),s=n(8),a=n(442);t.exports=function(t,e,n){var u=s(t)?r:o;return n&&a(t,e,n)&&(e=void 0),u(t,i(e,3))}},function(t,e){t.exports=function(){return[]}},function(t,e){t.exports=function(){return!1}},function(t,e,n){var r=n(488),i=1/0,o=1.7976931348623157e308;t.exports=function(t){return t?(t=r(t))===i||t===-i?(t<0?-1:1)*o:t==t?t:0:0===t?t:0}},function(t,e,n){var r=n(486);t.exports=function(t){var e=r(t),n=e%1;return e==e?n?e-n:e:0}},function(t,e,n){var r=n(50),i=n(79),o=NaN,s=/^\s+|\s+$/g,a=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,c=/^0o[0-7]+$/i,l=parseInt;t.exports=function(t){if("number"==typeof t)return t;if(i(t))return o;if(r(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=r(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(s,"");var n=u.test(t);return n||c.test(t)?l(t.slice(2),n?2:8):a.test(t)?o:+t}},function(t,e,n){var r=n(395),i=n(436),o=n(52),s=n(473);t.exports=function(t,e,n){return t=o(t),void 0===(e=n?void 0:e)?i(t)?s(t):r(t):t.match(e)||[]}},function(t,e,n){"use strict";var r=n(20),i=Object.create,o=Object.prototype.hasOwnProperty;t.exports=function(t){var e,n=0,s=1,a=i(null),u=i(null),c=0;return t=r(t),{hit:function(r){var i=u[r],l=++c;if(a[l]=r,u[r]=l,!i){if(++n<=t)return;return r=a[s],e(r),r}if(delete a[i],s===i)for(;!o.call(a,++s);)continue},delete:e=function(t){var e=u[t];if(e&&(delete a[e],delete u[t],--n,s===e)){if(!n)return c=0,void(s=1);for(;!o.call(a,++s);)continue}},clear:function(){n=0,s=1,a=i(null),u=i(null),c=0}}}},function(t,e,n){"use strict";var r=n(111),i=n(163),o=n(164),s=n(160),a=n(120),u=Array.prototype.slice,c=Function.prototype.apply,l=Object.create,h=Object.prototype.hasOwnProperty;n(22).async=function(t,e){var n,f,p,d=l(null),m=l(null),v=e.memoized,y=e.original;e.memoized=s(function(t){var e=arguments,r=e[e.length-1];return"function"==typeof r&&(n=r,e=u.call(e,0,-1)),v.apply(f=this,p=e)},v);try{o(e.memoized,v)}catch(t){}e.on("get",function(t){var r,i,o;if(n){if(d[t])return"function"==typeof d[t]?d[t]=[d[t],n]:d[t].push(n),void(n=null);r=n,i=f,o=p,n=f=p=null,a(function(){var s;h.call(m,t)?(s=m[t],e.emit("getasync",t,o,i),c.call(r,s.context,s.args)):(n=r,f=i,p=o,v.apply(i,o))})}}),e.original=function(){var t,i,o,s;return n?(t=r(arguments),i=function t(n){var i,o,u=t.id;if(null!=u){if(delete t.id,i=d[u],delete d[u],i)return o=r(arguments),e.has(u)&&(n?e.delete(u):(m[u]={context:this,args:o},e.emit("setasync",u,"function"==typeof i?1:i.length))),"function"==typeof i?s=c.call(i,this,o):i.forEach(function(t){s=c.call(t,this,o)},this),s}else a(c.bind(t,this,arguments))},o=n,n=f=p=null,t.push(i),s=c.call(y,this,t),i.cb=o,n=i,s):c.call(y,this,arguments)},e.on("set",function(t){n?(d[t]?"function"==typeof d[t]?d[t]=[d[t],n.cb]:d[t].push(n.cb):d[t]=n.cb,delete n.cb,n.id=t,n=null):e.delete(t)}),e.on("delete",function(t){var n;h.call(d,t)||m[t]&&(n=m[t],delete m[t],e.emit("deleteasync",t,u.call(n.args,1)))}),e.on("clear",function(){var t=m;m=l(null),e.emit("clearasync",i(t,function(t){return u.call(t.args,1)}))})}},function(t,e,n){"use strict";var r=n(12),i=n(67),o=n(22),s=Function.prototype.apply;o.dispose=function(t,e,n){var a;if(r(t),n.async&&o.async||n.promise&&o.promise)return e.on("deleteasync",a=function(e,n){s.call(t,null,n)}),void e.on("clearasync",function(t){i(t,function(t,e){a(e,t)})});e.on("delete",a=function(e,n){t(n)}),e.on("clear",function(t){i(t,function(t,e){a(e,t)})})}},function(t,e,n){"use strict";var r=n(111),i=n(67),o=n(120),s=n(168),a=n(533),u=n(22),c=Function.prototype,l=Math.max,h=Math.min,f=Object.create;u.maxAge=function(t,e,n){var p,d,m,v;(t=a(t))&&(p=f(null),d=n.async&&u.async||n.promise&&u.promise?"async":"",e.on("set"+d,function(n){p[n]=setTimeout(function(){e.delete(n)},t),v&&(v[n]&&"nextTick"!==v[n]&&clearTimeout(v[n]),v[n]=setTimeout(function(){delete v[n]},m))}),e.on("delete"+d,function(t){clearTimeout(p[t]),delete p[t],v&&("nextTick"!==v[t]&&clearTimeout(v[t]),delete v[t])}),n.preFetch&&(m=!0===n.preFetch||isNaN(n.preFetch)?.333:l(h(Number(n.preFetch),1),0))&&(v={},m=(1-m)*t,e.on("get"+d,function(t,i,a){v[t]||(v[t]="nextTick",o(function(){var o;"nextTick"===v[t]&&(delete v[t],e.delete(t),n.async&&(i=r(i)).push(c),o=e.memoized.apply(a,i),n.promise&&s(o)&&("function"==typeof o.done?o.done(c,c):o.then(c,c)))}))})),e.on("clear"+d,function(){i(p,function(t){clearTimeout(t)}),p={},v&&(i(v,function(t){"nextTick"!==t&&clearTimeout(t)}),v={})}))}},function(t,e,n){"use strict";var r=n(20),i=n(490),o=n(22);o.max=function(t,e,n){var s,a,u;(t=r(t))&&(a=i(t),s=n.async&&o.async||n.promise&&o.promise?"async":"",e.on("set"+s,u=function(t){void 0!==(t=a.hit(t))&&e.delete(t)}),e.on("get"+s,u),e.on("delete"+s,a.delete),e.on("clear"+s,a.clear))}},function(t,e,n){"use strict";var r=n(163),i=n(168),o=n(120),s=Object.create,a=Object.prototype.hasOwnProperty;n(22).promise=function(t,e){var n=s(null),u=s(null),c=s(null);e.on("set",function(r,s,a){if(!i(a))return u[r]=a,void e.emit("setasync",r,1);n[r]=1,c[r]=a;var l=function(t){var i=n[r];i&&(delete n[r],u[r]=t,e.emit("setasync",r,i))},h=function(){n[r]&&(delete n[r],delete c[r],e.delete(r))};"then"!==t&&"function"==typeof a.done?"done"!==t&&"function"==typeof a.finally?(a.done(l),a.finally(h)):a.done(l,h):a.then(function(t){o(l.bind(this,t))},function(){o(h)})}),e.on("get",function(t,r,s){var a;if(n[t])++n[t];else{a=c[t];var u=function(){e.emit("getasync",t,r,s)};i(a)?"function"==typeof a.done?a.done(u):a.then(function(){o(u)}):u()}}),e.on("delete",function(t){if(delete c[t],n[t])delete n[t];else if(a.call(u,t)){var r=u[t];delete u[t],e.emit("deleteasync",t,[r])}}),e.on("clear",function(){var t=u;u=s(null),n=s(null),c=s(null),e.emit("clearasync",r(t,function(t){return[t]}))})}},function(t,e,n){"use strict";var r=n(66),i=n(22),o=Object.create,s=Object.defineProperties;i.refCounter=function(t,e,n){var a,u;a=o(null),u=n.async&&i.async||n.promise&&i.promise?"async":"",e.on("set"+u,function(t,e){a[t]=e||1}),e.on("get"+u,function(t){++a[t]}),e.on("delete"+u,function(t){delete a[t]}),e.on("clear"+u,function(){a={}}),s(e.memoized,{deleteRef:r(function(){var t=e.get(arguments);return null===t?null:a[t]?!--a[t]&&(e.delete(t),!0):null}),getRefCount:r(function(){var t=e.get(arguments);return null===t?0:a[t]?a[t]:0})})}},function(t,e,n){"use strict";var r=n(165),i=n(189),o=n(506);t.exports=function(t){var e,s=r(arguments[1]);return s.normalizer||0!==(e=s.length=i(s.length,t.length,s.async))&&(s.primitive?!1===e?s.normalizer=n(505):e>1&&(s.normalizer=n(503)(e)):s.normalizer=!1===e?n(504)():1===e?n(501)():n(502)(e)),s.async&&n(491),s.promise&&n(495),s.dispose&&n(492),s.maxAge&&n(493),s.max&&n(494),s.refCounter&&n(496),o(t,s)}},function(t,e,n){"use strict";var r=n(331),i=n(160),o=n(66),s=n(359).methods,a=n(500),u=n(499),c=Function.prototype.apply,l=Function.prototype.call,h=Object.create,f=Object.prototype.hasOwnProperty,p=Object.defineProperties,d=s.on,m=s.emit;t.exports=function(t,e,n){var s,v,y,g,x,b,D,E,w,_,S,A,C,k=h(null);return v=!1!==e?e:isNaN(t.length)?1:t.length,n.normalizer&&(E=u(n.normalizer),y=E.get,g=E.set,x=E.delete,b=E.clear),null!=n.resolvers&&(C=a(n.resolvers)),A=y?i(function(e){var n,i,o=arguments;if(C&&(o=C(o)),null!==(n=y(o))&&f.call(k,n))return w&&s.emit("get",n,o,this),k[n];if(i=1===o.length?l.call(t,this,o[0]):c.call(t,this,o),null===n){if(null!==(n=y(o)))throw r("Circular invocation","CIRCULAR_INVOCATION");n=g(o)}else if(f.call(k,n))throw r("Circular invocation","CIRCULAR_INVOCATION");return k[n]=i,_&&s.emit("set",n,null,i),i},v):0===e?function(){var e;if(f.call(k,"data"))return w&&s.emit("get","data",arguments,this),k.data;if(e=arguments.length?c.call(t,this,arguments):l.call(t,this),f.call(k,"data"))throw r("Circular invocation","CIRCULAR_INVOCATION");return k.data=e,_&&s.emit("set","data",null,e),e}:function(e){var n,i,o=arguments;if(C&&(o=C(arguments)),i=String(o[0]),f.call(k,i))return w&&s.emit("get",i,o,this),k[i];if(n=1===o.length?l.call(t,this,o[0]):c.call(t,this,o),f.call(k,i))throw r("Circular invocation","CIRCULAR_INVOCATION");return k[i]=n,_&&s.emit("set",i,null,n),n},s={original:t,memoized:A,get:function(t){return C&&(t=C(t)),y?y(t):String(t[0])},has:function(t){return f.call(k,t)},delete:function(t){var e;f.call(k,t)&&(x&&x(t),e=k[t],delete k[t],S&&s.emit("delete",t,e))},clear:function(){var t=k;b&&b(),k=h(null),s.emit("clear",t)},on:function(t,e){return"get"===t?w=!0:"set"===t?_=!0:"delete"===t&&(S=!0),d.call(this,t,e)},emit:m,updateEnv:function(){t=s.original}},D=y?i(function(t){var e,n=arguments;C&&(n=C(n)),null!==(e=y(n))&&s.delete(e)},v):0===e?function(){return s.delete("data")}:function(t){return C&&(t=C(arguments)[0]),s.delete(t)},p(A,{__memoized__:o(!0),delete:o(D),clear:o(s.clear)}),s}},function(t,e,n){"use strict";var r=n(12);t.exports=function(t){var e;return"function"==typeof t?{set:t,get:t}:(e={get:r(t.get)},void 0!==t.set?(e.set=r(t.set),e.delete=r(t.delete),e.clear=r(t.clear),e):(e.set=e.get,e))}},function(t,e,n){"use strict";var r,i=n(330),o=n(12),s=Array.prototype.slice;r=function(t){return this.map(function(e,n){return e?e(t[n]):t[n]}).concat(s.call(t,this.length))},t.exports=function(t){return(t=i(t)).forEach(function(t){null!=t&&o(t)}),r.bind(t)}},function(t,e,n){"use strict";var r=n(110);t.exports=function(){var t=0,e=[],n=[];return{get:function(t){var i=r.call(e,t[0]);return-1===i?null:n[i]},set:function(r){return e.push(r[0]),n.push(++t),t},delete:function(t){var i=r.call(n,t);-1!==i&&(e.splice(i,1),n.splice(i,1))},clear:function(){e=[],n=[]}}}},function(t,e,n){"use strict";var r=n(110),i=Object.create;t.exports=function(t){var e=0,n=[[],[]],o=i(null);return{get:function(e){for(var i,o=0,s=n;o<t-1;){if(-1===(i=r.call(s[0],e[o])))return null;s=s[1][i],++o}return-1===(i=r.call(s[0],e[o]))?null:s[1][i]||null},set:function(i){for(var s,a=0,u=n;a<t-1;)-1===(s=r.call(u[0],i[a]))&&(s=u[0].push(i[a])-1,u[1].push([[],[]])),u=u[1][s],++a;return-1===(s=r.call(u[0],i[a]))&&(s=u[0].push(i[a])-1),u[1][s]=++e,o[e]=i,e},delete:function(e){for(var i,s=0,a=n,u=[],c=o[e];s<t-1;){if(-1===(i=r.call(a[0],c[s])))return;u.push(a,i),a=a[1][i],++s}if(-1!==(i=r.call(a[0],c[s]))){for(e=a[1][i],a[0].splice(i,1),a[1].splice(i,1);!a[0].length&&u.length;)i=u.pop(),(a=u.pop())[0].splice(i,1),a[1].splice(i,1);delete o[e]}},clear:function(){n=[[],[]],o=i(null)}}}},function(t,e,n){"use strict";t.exports=function(t){return t?function(e){for(var n=String(e[0]),r=0,i=t;--i;)n+=""+e[++r];return n}:function(){return""}}},function(t,e,n){"use strict";var r=n(110),i=Object.create;t.exports=function(){var t=0,e=[],n=i(null);return{get:function(t){var n,i=0,o=e,s=t.length;if(0===s)return o[s]||null;if(o=o[s]){for(;i<s-1;){if(-1===(n=r.call(o[0],t[i])))return null;o=o[1][n],++i}return-1===(n=r.call(o[0],t[i]))?null:o[1][n]||null}return null},set:function(i){var o,s=0,a=e,u=i.length;if(0===u)a[u]=++t;else{for(a[u]||(a[u]=[[],[]]),a=a[u];s<u-1;)-1===(o=r.call(a[0],i[s]))&&(o=a[0].push(i[s])-1,a[1].push([[],[]])),a=a[1][o],++s;-1===(o=r.call(a[0],i[s]))&&(o=a[0].push(i[s])-1),a[1][o]=++t}return n[t]=i,t},delete:function(t){var i,o=0,s=e,a=n[t],u=a.length,c=[];if(0===u)delete s[u];else if(s=s[u]){for(;o<u-1;){if(-1===(i=r.call(s[0],a[o])))return;c.push(s,i),s=s[1][i],++o}if(-1===(i=r.call(s[0],a[o])))return;for(t=s[1][i],s[0].splice(i,1),s[1].splice(i,1);!s[0].length&&c.length;)i=c.pop(),(s=c.pop())[0].splice(i,1),s[1].splice(i,1)}delete n[t]},clear:function(){e=[],n=i(null)}}}},function(t,e,n){"use strict";t.exports=function(t){var e,n,r=t.length;if(!r)return"";for(e=String(t[n=0]);--r;)e+=""+t[++n];return e}},function(t,e,n){"use strict";var r=n(12),i=n(67),o=n(22),s=n(498),a=n(189),u=Object.prototype.hasOwnProperty;t.exports=function t(e){var n,c,l;if(r(e),(n=Object(arguments[1])).async&&n.promise)throw new Error("Options 'async' and 'promise' cannot be used together");return u.call(e,"__memoized__")&&!n.force?e:(c=a(n.length,e.length,n.async&&o.async),l=s(e,c,n),i(o,function(t,e){n[e]&&t(n[e],l,n)}),t.__profiler__&&t.__profiler__(l),l.updateEnv(),l.memoized)}},function(t,e,n){"use strict";t.exports=function(t,e,n,r,i){}},function(t,e,n){"use strict";var r=n(510);t.exports=function(t){return r(t,!1)}},function(t,e,n){"use strict";var r=n(68),i=n(21),o=n(191);t.exports=function(){function t(t,e,n,r,s,a){a!==o&&i(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function e(){return t}t.isRequired=t;var n={array:t,bool:t,func:t,number:t,object:t,string:t,symbol:t,any:t,arrayOf:e,element:t,instanceOf:e,node:t,objectOf:e,oneOf:e,oneOfType:e,shape:e,exact:e};return n.checkPropTypes=r,n.PropTypes=n,n}},function(t,e,n){"use strict";var r=n(68),i=n(21),o=n(69),s=n(53),a=n(191),u=n(507);t.exports=function(t,e){var n="function"==typeof Symbol&&Symbol.iterator,c="@@iterator";var l="<<anonymous>>",h={array:m("array"),bool:m("boolean"),func:m("function"),number:m("number"),object:m("object"),string:m("string"),symbol:m("symbol"),any:d(r.thatReturnsNull),arrayOf:function(t){return d(function(e,n,r,i,o){if("function"!=typeof t)return new p("Property `"+o+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var s=e[n];if(!Array.isArray(s)){var u=y(s);return new p("Invalid "+i+" `"+o+"` of type `"+u+"` supplied to `"+r+"`, expected an array.")}for(var c=0;c<s.length;c++){var l=t(s,c,r,i,o+"["+c+"]",a);if(l instanceof Error)return l}return null})},element:function(){return d(function(e,n,r,i,o){var s=e[n];if(!t(s)){var a=y(s);return new p("Invalid "+i+" `"+o+"` of type `"+a+"` supplied to `"+r+"`, expected a single ReactElement.")}return null})}(),instanceOf:function(t){return d(function(e,n,r,i,o){if(!(e[n]instanceof t)){var s=t.name||l,a=function(t){if(!t.constructor||!t.constructor.name)return l;return t.constructor.name}(e[n]);return new p("Invalid "+i+" `"+o+"` of type `"+a+"` supplied to `"+r+"`, expected instance of `"+s+"`.")}return null})},node:function(){return d(function(t,e,n,r,i){if(!v(t[e]))return new p("Invalid "+r+" `"+i+"` supplied to `"+n+"`, expected a ReactNode.");return null})}(),objectOf:function(t){return d(function(e,n,r,i,o){if("function"!=typeof t)return new p("Property `"+o+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var s=e[n],u=y(s);if("object"!==u)return new p("Invalid "+i+" `"+o+"` of type `"+u+"` supplied to `"+r+"`, expected an object.");for(var c in s)if(s.hasOwnProperty(c)){var l=t(s,c,r,i,o+"."+c,a);if(l instanceof Error)return l}return null})},oneOf:function(t){if(!Array.isArray(t))return r.thatReturnsNull;return d(function(e,n,r,i,o){for(var s=e[n],a=0;a<t.length;a++)if(f(s,t[a]))return null;var u=JSON.stringify(t);return new p("Invalid "+i+" `"+o+"` of value `"+s+"` supplied to `"+r+"`, expected one of "+u+".")})},oneOfType:function(t){if(!Array.isArray(t))return r.thatReturnsNull;for(var e=0;e<t.length;e++){var n=t[e];if("function"!=typeof n)return o(!1,"Invalid argument supplied to oneOfType. Expected an array of check functions, but received %s at index %s.",x(n),e),r.thatReturnsNull}return d(function(e,n,r,i,o){for(var s=0;s<t.length;s++){var u=t[s];if(null==u(e,n,r,i,o,a))return null}return new p("Invalid "+i+" `"+o+"` supplied to `"+r+"`.")})},shape:function(t){return d(function(e,n,r,i,o){var s=e[n],u=y(s);if("object"!==u)return new p("Invalid "+i+" `"+o+"` of type `"+u+"` supplied to `"+r+"`, expected `object`.");for(var c in t){var l=t[c];if(l){var h=l(s,c,r,i,o+"."+c,a);if(h)return h}}return null})},exact:function(t){return d(function(e,n,r,i,o){var u=e[n],c=y(u);if("object"!==c)return new p("Invalid "+i+" `"+o+"` of type `"+c+"` supplied to `"+r+"`, expected `object`.");var l=s({},e[n],t);for(var h in l){var f=t[h];if(!f)return new p("Invalid "+i+" `"+o+"` key `"+h+"` supplied to `"+r+"`.\nBad object: "+JSON.stringify(e[n],null," ")+"\nValid keys: "+JSON.stringify(Object.keys(t),null," "));var d=f(u,h,r,i,o+"."+h,a);if(d)return d}return null})}};function f(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}function p(t){this.message=t,this.stack=""}function d(t){function n(n,r,o,s,u,c,h){(s=s||l,c=c||o,h!==a)&&(e&&i(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types"));return null==r[o]?n?null===r[o]?new p("The "+u+" `"+c+"` is marked as required in `"+s+"`, but its value is `null`."):new p("The "+u+" `"+c+"` is marked as required in `"+s+"`, but its value is `undefined`."):null:t(r,o,s,u,c)}var r=n.bind(null,!1);return r.isRequired=n.bind(null,!0),r}function m(t){return d(function(e,n,r,i,o,s){var a=e[n];return y(a)!==t?new p("Invalid "+i+" `"+o+"` of type `"+g(a)+"` supplied to `"+r+"`, expected `"+t+"`."):null})}function v(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(v);if(null===e||t(e))return!0;var r=function(t){var e=t&&(n&&t[n]||t[c]);if("function"==typeof e)return e}(e);if(!r)return!1;var i,o=r.call(e);if(r!==e.entries){for(;!(i=o.next()).done;)if(!v(i.value))return!1}else for(;!(i=o.next()).done;){var s=i.value;if(s&&!v(s[1]))return!1}return!0;default:return!1}}function y(t){var e=typeof t;return Array.isArray(t)?"array":t instanceof RegExp?"object":function(t,e){return"symbol"===t||"Symbol"===e["@@toStringTag"]||"function"==typeof Symbol&&e instanceof Symbol}(e,t)?"symbol":e}function g(t){if(void 0===t||null===t)return""+t;var e=y(t);if("object"===e){if(t instanceof Date)return"date";if(t instanceof RegExp)return"regexp"}return e}function x(t){var e=g(t);switch(e){case"array":case"object":return"an "+e;case"boolean":case"date":case"regexp":return"a "+e;default:return e}}return p.prototype=Error.prototype,h.checkPropTypes=u,h.PropTypes=h,h}},function(t,e){t.exports='---\nurl: "http://petstore.swagger.io/v2/swagger.json"\ndom_id: "#swagger-ui"\nvalidatorUrl: "https://online.swagger.io/validator"\noauth2RedirectUrl: "http://localhost:3200/oauth2-redirect.html"\n'},function(t,e,n){"use strict";var r={escape:function(t){var e={"=":"=0",":":"=2"};return"$"+(""+t).replace(/[=:]/g,function(t){return e[t]})},unescape:function(t){var e={"=0":"=","=2":":"};return(""+("."===t[0]&&"$"===t[1]?t.substring(2):t.substring(1))).replace(/(=0|=2)/g,function(t){return e[t]})}};t.exports=r},function(t,e,n){"use strict";var r=n(83),i=(n(21),function(t){if(this.instancePool.length){var e=this.instancePool.pop();return this.call(e,t),e}return new this(t)}),o=function(t){t instanceof this||r("25"),t.destructor(),this.instancePool.length<this.poolSize&&this.instancePool.push(t)},s=i,a={addPoolingTo:function(t,e){var n=t;return n.instancePool=[],n.getPooled=e||s,n.poolSize||(n.poolSize=10),n.release=o,n},oneArgumentPooler:i,twoArgumentPooler:function(t,e){if(this.instancePool.length){var n=this.instancePool.pop();return this.call(n,t,e),n}return new this(t,e)},threeArgumentPooler:function(t,e,n){if(this.instancePool.length){var r=this.instancePool.pop();return this.call(r,t,e,n),r}return new this(t,e,n)},fourArgumentPooler:function(t,e,n,r){if(this.instancePool.length){var i=this.instancePool.pop();return this.call(i,t,e,n,r),i}return new this(t,e,n,r)}};t.exports=a},function(t,e,n){"use strict";var r=n(53),i=n(192),o=n(515),s=n(516),a=n(37),u=n(517),c=n(518),l=n(519),h=n(522),f=a.createElement,p=a.createFactory,d=a.cloneElement,m=r,v=function(t){return t},y={Children:{map:o.map,forEach:o.forEach,count:o.count,toArray:o.toArray,only:h},Component:i.Component,PureComponent:i.PureComponent,createElement:f,cloneElement:d,isValidElement:a.isValidElement,PropTypes:u,createClass:l,createFactory:p,createMixin:v,DOM:s,version:c,__spread:m};t.exports=y},function(t,e,n){"use strict";var r=n(513),i=n(37),o=n(68),s=n(523),a=r.twoArgumentPooler,u=r.fourArgumentPooler,c=/\/+/g;function l(t){return(""+t).replace(c,"$&/")}function h(t,e){this.func=t,this.context=e,this.count=0}function f(t,e,n){var r=t.func,i=t.context;r.call(i,e,t.count++)}function p(t,e,n,r){this.result=t,this.keyPrefix=e,this.func=n,this.context=r,this.count=0}function d(t,e,n){var r=t.result,s=t.keyPrefix,a=t.func,u=t.context,c=a.call(u,e,t.count++);Array.isArray(c)?m(c,r,n,o.thatReturnsArgument):null!=c&&(i.isValidElement(c)&&(c=i.cloneAndReplaceKey(c,s+(!c.key||e&&e.key===c.key?"":l(c.key)+"/")+n)),r.push(c))}function m(t,e,n,r,i){var o="";null!=n&&(o=l(n)+"/");var a=p.getPooled(e,o,r,i);s(t,d,a),p.release(a)}function v(t,e,n){return null}h.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},r.addPoolingTo(h,a),p.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},r.addPoolingTo(p,u);var y={forEach:function(t,e,n){if(null==t)return t;var r=h.getPooled(e,n);s(t,f,r),h.release(r)},map:function(t,e,n){if(null==t)return t;var r=[];return m(t,r,null,e,n),r},mapIntoWithKeyPrefixInternal:m,count:function(t,e){return s(t,v,null)},toArray:function(t){var e=[];return m(t,e,null,o.thatReturnsArgument),e}};t.exports=y},function(t,e,n){"use strict";var r=n(37).createFactory,i={a:r("a"),abbr:r("abbr"),address:r("address"),area:r("area"),article:r("article"),aside:r("aside"),audio:r("audio"),b:r("b"),base:r("base"),bdi:r("bdi"),bdo:r("bdo"),big:r("big"),blockquote:r("blockquote"),body:r("body"),br:r("br"),button:r("button"),canvas:r("canvas"),caption:r("caption"),cite:r("cite"),code:r("code"),col:r("col"),colgroup:r("colgroup"),data:r("data"),datalist:r("datalist"),dd:r("dd"),del:r("del"),details:r("details"),dfn:r("dfn"),dialog:r("dialog"),div:r("div"),dl:r("dl"),dt:r("dt"),em:r("em"),embed:r("embed"),fieldset:r("fieldset"),figcaption:r("figcaption"),figure:r("figure"),footer:r("footer"),form:r("form"),h1:r("h1"),h2:r("h2"),h3:r("h3"),h4:r("h4"),h5:r("h5"),h6:r("h6"),head:r("head"),header:r("header"),hgroup:r("hgroup"),hr:r("hr"),html:r("html"),i:r("i"),iframe:r("iframe"),img:r("img"),input:r("input"),ins:r("ins"),kbd:r("kbd"),keygen:r("keygen"),label:r("label"),legend:r("legend"),li:r("li"),link:r("link"),main:r("main"),map:r("map"),mark:r("mark"),menu:r("menu"),menuitem:r("menuitem"),meta:r("meta"),meter:r("meter"),nav:r("nav"),noscript:r("noscript"),object:r("object"),ol:r("ol"),optgroup:r("optgroup"),option:r("option"),output:r("output"),p:r("p"),param:r("param"),picture:r("picture"),pre:r("pre"),progress:r("progress"),q:r("q"),rp:r("rp"),rt:r("rt"),ruby:r("ruby"),s:r("s"),samp:r("samp"),script:r("script"),section:r("section"),select:r("select"),small:r("small"),source:r("source"),span:r("span"),strong:r("strong"),style:r("style"),sub:r("sub"),summary:r("summary"),sup:r("sup"),table:r("table"),tbody:r("tbody"),td:r("td"),textarea:r("textarea"),tfoot:r("tfoot"),th:r("th"),thead:r("thead"),time:r("time"),title:r("title"),tr:r("tr"),track:r("track"),u:r("u"),ul:r("ul"),var:r("var"),video:r("video"),wbr:r("wbr"),circle:r("circle"),clipPath:r("clipPath"),defs:r("defs"),ellipse:r("ellipse"),g:r("g"),image:r("image"),line:r("line"),linearGradient:r("linearGradient"),mask:r("mask"),path:r("path"),pattern:r("pattern"),polygon:r("polygon"),polyline:r("polyline"),radialGradient:r("radialGradient"),rect:r("rect"),stop:r("stop"),svg:r("svg"),text:r("text"),tspan:r("tspan")};t.exports=i},function(t,e,n){"use strict";var r=n(37).isValidElement,i=n(508);t.exports=i(r)},function(t,e,n){"use strict";t.exports="15.6.2"},function(t,e,n){"use strict";var r=n(192).Component,i=n(37).isValidElement,o=n(195),s=n(326);t.exports=s(r,i,o)},function(t,e,n){"use strict";var r="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";t.exports=function(t){var e=t&&(r&&t[r]||t[i]);if("function"==typeof e)return e}},function(t,e,n){"use strict";var r=function(){};t.exports=r},function(t,e,n){"use strict";var r=n(83),i=n(37);n(21);t.exports=function(t){return i.isValidElement(t)||r("143"),t}},function(t,e,n){"use strict";var r=n(83),i=(n(193),n(194)),o=n(520),s=(n(21),n(512)),a=(n(69),"."),u=":";function c(t,e){return t&&"object"==typeof t&&null!=t.key?s.escape(t.key):e.toString(36)}t.exports=function(t,e,n){return null==t?0:function t(e,n,l,h){var f,p=typeof e;if("undefined"!==p&&"boolean"!==p||(e=null),null===e||"string"===p||"number"===p||"object"===p&&e.$$typeof===i)return l(h,e,""===n?a+c(e,0):n),1;var d=0,m=""===n?a:n+u;if(Array.isArray(e))for(var v=0;v<e.length;v++)d+=t(f=e[v],m+c(f,v),l,h);else{var y=o(e);if(y){var g,x=y.call(e);if(y!==e.entries)for(var b=0;!(g=x.next()).done;)d+=t(f=g.value,m+c(f,b++),l,h);else for(;!(g=x.next()).done;){var D=g.value;D&&(d+=t(f=D[1],m+s.escape(D[0])+u+c(f,0),l,h))}}else if("object"===p){var E="",w=String(e);r("31","[object Object]"===w?"object with keys {"+Object.keys(e).join(", ")+"}":w,E)}}return d}(t,"",e,n)}},function(t,e,n){t.exports=n(23)},function(t,e,n){"use strict";t.exports=o;var r=n(199),i=n(45);function o(t){if(!(this instanceof o))return new o(t);r.call(this,t)}i.inherits=n(32),i.inherits(o,r),o.prototype._transform=function(t,e,n){n(null,t)}},function(t,e,n){"use strict";var r=n(84).Buffer,i=n(539);t.exports=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},t.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},t.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},t.prototype.clear=function(){this.head=this.tail=null,this.length=0},t.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,n=""+e.data;e=e.next;)n+=t+e.data;return n},t.prototype.concat=function(t){if(0===this.length)return r.alloc(0);if(1===this.length)return this.head.data;for(var e,n,i,o=r.allocUnsafe(t>>>0),s=this.head,a=0;s;)e=s.data,n=o,i=a,e.copy(n,i),a+=s.data.length,s=s.next;return o},t}(),i&&i.inspect&&i.inspect.custom&&(t.exports.prototype[i.inspect.custom]=function(){var t=i.inspect({length:this.length});return this.constructor.name+" "+t})},function(t,e,n){t.exports=n(122).PassThrough},function(t,e,n){t.exports=n(122).Transform},function(t,e,n){t.exports=n(121)},function(t,e,n){(function(t,e){!function(t,n){"use strict";if(!t.setImmediate){var r,i,o,s,a,u=1,c={},l=!1,h=t.document,f=Object.getPrototypeOf&&Object.getPrototypeOf(t);f=f&&f.setTimeout?f:t,"[object process]"==={}.toString.call(t.process)?r=function(t){e.nextTick(function(){d(t)})}:!function(){if(t.postMessage&&!t.importScripts){var e=!0,n=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=n,e}}()?t.MessageChannel?((o=new MessageChannel).port1.onmessage=function(t){d(t.data)},r=function(t){o.port2.postMessage(t)}):h&&"onreadystatechange"in h.createElement("script")?(i=h.documentElement,r=function(t){var e=h.createElement("script");e.onreadystatechange=function(){d(t),e.onreadystatechange=null,i.removeChild(e),e=null},i.appendChild(e)}):r=function(t){setTimeout(d,0,t)}:(s="setImmediate$"+Math.random()+"$",a=function(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(s)&&d(+e.data.slice(s.length))},t.addEventListener?t.addEventListener("message",a,!1):t.attachEvent("onmessage",a),r=function(e){t.postMessage(s+e,"*")}),f.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var i={callback:t,args:e};return c[u]=i,r(u),u++},f.clearImmediate=p}function p(t){delete c[t]}function d(t){if(l)setTimeout(d,0,t);else{var e=c[t];if(e){l=!0;try{!function(t){var e=t.callback,r=t.args;switch(r.length){case 0:e();break;case 1:e(r[0]);break;case 2:e(r[0],r[1]);break;case 3:e(r[0],r[1],r[2]);break;default:e.apply(n,r)}}(e)}finally{p(t),l=!1}}}}}("undefined"==typeof self?void 0===t?this:t:self)}).call(e,n(13),n(36))},function(t,e,n){t.exports=i;var r=n(112).EventEmitter;function i(){r.call(this)}n(32)(i,r),i.Readable=n(122),i.Writable=n(529),i.Duplex=n(524),i.Transform=n(528),i.PassThrough=n(527),i.Stream=i,i.prototype.pipe=function(t,e){var n=this;function i(e){t.writable&&!1===t.write(e)&&n.pause&&n.pause()}function o(){n.readable&&n.resume&&n.resume()}n.on("data",i),t.on("drain",o),t._isStdio||e&&!1===e.end||(n.on("end",a),n.on("close",u));var s=!1;function a(){s||(s=!0,t.end())}function u(){s||(s=!0,"function"==typeof t.destroy&&t.destroy())}function c(t){if(l(),0===r.listenerCount(this,"error"))throw t}function l(){n.removeListener("data",i),t.removeListener("drain",o),n.removeListener("end",a),n.removeListener("close",u),n.removeListener("error",c),t.removeListener("error",c),n.removeListener("end",l),n.removeListener("close",l),t.removeListener("close",l)}return n.on("error",c),t.on("error",c),n.on("end",l),n.on("close",l),t.on("close",l),t.emit("pipe",n),t}},function(t,e,n){"use strict";t.exports=2147483647},function(t,e,n){"use strict";var r=n(20),i=n(532);t.exports=function(t){if((t=r(t))>i)throw new TypeError(t+" exceeds maximum possible timeout");return t}},function(t,e){t.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAMAAAAM7l6QAAAAYFBMVEUAAABUfwBUfwBUfwBUfwBUfwBUfwBUfwBUfwBUfwBUfwBUfwBUfwBUfwBUfwB0lzB/n0BfhxBpjyC0x4////+qv4CJp1D09++ft3C/z5/K16/U379UfwDf58/q79+Ur2D2RCk9AAAAHXRSTlMAEEAwn9//z3Agv4/vYID/////////////////UMeji1kAAAD8SURBVHgBlZMFAoQwDATRxbXB7f+vPKnlXAZn6k2cf3A9z/PfOC8IIYni5FmmABM8FMhwT17c9hnhiZL1CwvEL1tmPD0qSKq6gaStW/kMXanVmAVRDUlH1OvuuTINo6k90Sxf8qsOtF6g4ff1osP3OnMcV7d4pzdIUtu1oA4V0DZoKmxmlEYvtDUjjS3tmKmqB+pYy8pD1VPf7jPE0I40HHcaBwnue6fGzgyS5tXIU96PV7rkDWHNLV0DK4FkoKmFpN5oUnvi8KoeA2/JXsmXQuokx0siR1G8tLkN6eB9sLwJp/yymcyaP/TrP+RPmbMMixcJVgTR1aUZ93oGXsgXQAaG6EwAAAAASUVORK5CYII="},function(t,e,n){(function(e){function n(t){try{if(!e.localStorage)return!1}catch(t){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=function(t,e){if(n("noDeprecation"))return t;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(e);n("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}}}).call(e,n(13))},function(t,e){var n={"&":"&",'"':""","'":"'","<":"<",">":">"};t.exports=function(t){return t&&t.replace?t.replace(/([&"<>'])/g,function(t,e){return n[e]}):t}},function(t,e,n){(function(e){var r=n(536),i=n(531).Stream,o=" ";function s(t,e,n){n=n||0;var i,o,a=(i=e,new Array(n||0).join(i||"")),u=t;if("object"==typeof t&&((u=t[o=Object.keys(t)[0]])&&u._elem))return u._elem.name=o,u._elem.icount=n,u._elem.indent=e,u._elem.indents=a,u._elem.interrupt=u,u._elem;var c,l=[],h=[];function f(t){Object.keys(t).forEach(function(e){l.push(function(t,e){return t+'="'+r(e)+'"'}(e,t[e]))})}switch(typeof u){case"object":if(null===u)break;u._attr&&f(u._attr),u._cdata&&h.push(("<![CDATA["+u._cdata).replace(/\]\]>/g,"]]]]><![CDATA[>")+"]]>"),u.forEach&&(c=!1,h.push(""),u.forEach(function(t){"object"==typeof t?"_attr"==Object.keys(t)[0]?f(t._attr):h.push(s(t,e,n+1)):(h.pop(),c=!0,h.push(r(t)))}),c||h.push(""));break;default:h.push(r(u))}return{name:o,interrupt:!1,attributes:l,content:h,icount:n,indents:a,indent:e}}function a(t,e,n){if("object"!=typeof e)return t(!1,e);var r=e.interrupt?1:e.content.length;function i(){for(;e.content.length;){var i=e.content.shift();if(void 0!==i){if(o(i))return;a(t,i)}}t(!1,(r>1?e.indents:"")+(e.name?"</"+e.name+">":"")+(e.indent&&!n?"\n":"")),n&&n()}function o(e){return!!e.interrupt&&(e.interrupt.append=t,e.interrupt.end=i,e.interrupt=!1,t(!0),!0)}if(t(!1,e.indents+(e.name?"<"+e.name:"")+(e.attributes.length?" "+e.attributes.join(" "):"")+(r?e.name?">":"":e.name?"/>":"")+(e.indent&&r>1?"\n":"")),!r)return t(!1,e.indent?"\n":"");o(e)||i()}t.exports=function(t,n){"object"!=typeof n&&(n={indent:n});var r,u,c=n.stream?new i:null,l="",h=!1,f=n.indent?!0===n.indent?o:n.indent:"",p=!0;function d(t){p?e.nextTick(t):t()}function m(t,e){if(void 0!==e&&(l+=e),t&&!h&&(c=c||new i,h=!0),t&&h){var n=l;d(function(){c.emit("data",n)}),l=""}}function v(t,e){a(m,s(t,f,f?1:0),e)}function y(){if(c){var t=l;d(function(){c.emit("data",t),c.emit("end"),c.readable=!1,c.emit("close")})}}return d(function(){p=!1}),n.declaration&&(r=n.declaration,u={version:"1.0",encoding:r.encoding||"UTF-8"},r.standalone&&(u.standalone=r.standalone),v({"?xml":{_attr:u}}),l=l.replace("/>","?>")),t&&t.forEach?t.forEach(function(e,n){var r;n+1===t.length&&(r=y),v(e,r)}):v(t,y),c?(c.readable=!0,c):l},t.exports.element=t.exports.Element=function(){var t={_elem:s(Array.prototype.slice.call(arguments)),push:function(t){if(!this.append)throw new Error("not assigned to a parent!");var e=this,n=this._elem.indent;a(this.append,s(t,n,this._elem.icount+(n?1:0)),function(){e.append(!0)})},close:function(t){void 0!==t&&this.push(t),this.end&&this.end()}};return t}}).call(e,n(36))},function(t,e){},function(t,e){},function(t,e,n){n(205),t.exports=n(206)}])});
//# sourceMappingURL=swagger-ui-standalone-preset.js.map |
examples/js/column-filter/date-filter-programmatically.js | echaouchna/react-bootstrap-tab | /* eslint max-len: 0 */
/* eslint no-unused-vars: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
const startDate = new Date(2015, 0, 1);
const endDate = new Date();
for (let i = 0; i < quantity; i++) {
const date = new Date(startDate.getTime() + Math.random() * (endDate.getTime() - startDate.getTime()));
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
inStockDate: date
});
}
}
addProducts(5);
function dateFormatter(cell, row) {
return `${('0' + cell.getDate()).slice(-2)}/${('0' + (cell.getMonth() + 1)).slice(-2)}/${cell.getFullYear()}`;
}
export default class ProgrammaticallyDateFilter extends React.Component {
handleBtnClick = () => {
this.refs.nameCol.applyFilter({
date: products[2].inStockDate,
comparator: '='
});
}
render() {
return (
<div>
<button onClick={ this.handleBtnClick } className='btn btn-default'>Click to apply select filter</button>
<BootstrapTable data={ products }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn ref='nameCol' dataField='inStockDate' dataFormat={ dateFormatter } filter={ { type: 'DateFilter' } }>In Stock From</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
}
|
app/components/ComingSoon/ComingSoon.js | saelili/F3C_Website | import React from 'react'
import PropTypes from 'prop-types'
const ComingSoon = ({ title }) => (
<div
style={{
width: '100%',
minHeight: '100vh',
display: 'flex',
justifyContent: 'center',
alignItems: 'center' }}>
{title} Page Coming Soon.
</div>
)
ComingSoon.propTypes = {
title: PropTypes.string,
}
export default ComingSoon
|
app/index.js | gilbertgede/RepYourself | import { persistStore, } from 'redux-persist'
import { render, } from 'react-dom'
import React from 'react'
import shortid from 'shortid'
import { ACTIONS, } from './constants/Constants'
import { newUser, } from './utils/backendRequests'
import { configureStore } from './store/configureStore'
import App from './containers/App.jsx'
// Service Worker setup
import * as OfflinePluginRuntime from 'offline-plugin/runtime';
OfflinePluginRuntime.install();
// "borrowed" from:
// https://philipwalton.com/articles/loading-polyfills-only-when-needed/
function browserSupportsAllFeatures() {
return window.Promise && window.fetch;
}
function loadScript(src, done) {
console.log("executed loadScript")
var js = document.createElement('script');
js.src = src;
js.onload = function() {
done();
};
js.onerror = function() {
done(new Error('Failed to load script ' + src));
};
document.head.appendChild(js);
}
if (browserSupportsAllFeatures()) {
main()
} else {
loadScript('polyfills.js', main)
console.log("loading polyfills")
}
function main() {
let temp = ""
if (window.location.protocol.search('file') == -1) {
temp = window.location.search.split("?s=").slice(-1)[0]
history.pushState({}, null, "/")
}
const store = configureStore()
store.dispatch({
type: ACTIONS.ADDED_PARENT_ID,
data: temp
})
const persistor = persistStore(
store,
{},
() => {
let state = store.getState()
if (state.userID == "") {
let newUserID = shortid.generate()
store.dispatch({type: ACTIONS.ADDED_USER_ID, data: newUserID})
newUser(newUserID, state.parentID).then(data=>{
store.dispatch({type: ACTIONS.ADDED_USER_ID, data: data})
})
}
}
)
const rootElement = document.getElementById('root')
render( <App store={store} />, rootElement )
} |
ajax/libs/forerunnerdb/1.3.749/fdb-all.js | Amomo/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'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
Grid = _dereq_('../lib/Grid'),
NodeApiClient = _dereq_('../lib/NodeApiClient'),
BinaryLog = _dereq_('../lib/BinaryLog');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/BinaryLog":4,"../lib/CollectionGroup":8,"../lib/Document":11,"../lib/Grid":13,"../lib/Highchart":14,"../lib/NodeApiClient":30,"../lib/Overview":33,"../lib/Persist":35,"../lib/View":42,"./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":9,"../lib/Shim.IE8":41}],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":34,"./Shared":40}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
ReactorIO,
Collection,
CollectionInit,
Db,
DbInit,
BinaryLog;
Shared = _dereq_('./Shared');
BinaryLog = function () {
this.init.apply(this, arguments);
};
BinaryLog.prototype.init = function (parent) {
var self = this;
self._logCounter = 0;
self._parent = parent;
self.size(1000);
};
Shared.addModule('BinaryLog', BinaryLog);
Shared.mixin(BinaryLog.prototype, 'Mixin.Common');
Shared.mixin(BinaryLog.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryLog.prototype, 'Mixin.Events');
Collection = Shared.modules.Collection;
Db = Shared.modules.Db;
ReactorIO = Shared.modules.ReactorIO;
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
Shared.synthesize(BinaryLog.prototype, 'name');
Shared.synthesize(BinaryLog.prototype, 'size');
BinaryLog.prototype.attachIO = function () {
var self = this;
if (!self._io) {
self._log = new Collection(self._parent.name() + '-BinaryLog', {capped: true, size: self.size()});
// Override the log collection's id generator so it is linear
self._log.objectId = function (id) {
if (!id) {
id = ++self._logCounter;
}
return id;
};
self._io = new ReactorIO(self._parent, self, function (chainPacket) {
self._log.insert({
type: chainPacket.type,
data: chainPacket.data
});
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
}
};
BinaryLog.prototype.detachIO = function () {
var self = this;
if (self._io) {
self._log.drop();
self._io.drop();
delete self._log;
delete self._io;
}
};
Collection.prototype.init = function () {
CollectionInit.apply(this, arguments);
this._binaryLog = new BinaryLog(this);
};
Shared.finishModule('BinaryLog');
module.exports = BinaryLog;
},{"./Shared":40}],5:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param 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":34,"./Shared":40}],6:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],7:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
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._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback.call(this, false, true); }
return true;
}
} else {
if (callback) { callback.call(this, false, true); }
return true;
}
if (callback) { callback.call(this, false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @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.call(this); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* 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.call(this); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback.call(this); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback.call(this); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @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.call(this, false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback.call(this, resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {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.call(this, 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.call(this, 'Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
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) {
if (options.type) {
// Check if the specified type is available
if (Shared.index[options.type]) {
// We found the type, generate it
index = new Shared.index[options.type](keys, options, this);
} else {
throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)');
}
} else {
// Create default index type
index = new IndexHashMap(keys, options, this);
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
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":15,"./IndexBinaryTree":16,"./IndexHashMap":17,"./KeyValueStore":18,"./Metrics":19,"./Overload":32,"./Path":34,"./ReactorIO":38,"./Shared":40}],8:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {String=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Remove old data
this._data.remove(chainPacket.data.oldData);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
/**
* Creates a new collectionGroup instance or returns an existing
* instance if one already exists with the passed name.
* @func collectionGroup
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.collectionGroup = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof CollectionGroup) {
return name;
}
if (this._collectionGroup && this._collectionGroup[name]) {
return this._collectionGroup[name];
}
this._collectionGroup[name] = new CollectionGroup(name).db(this);
self.emit('create', self._collectionGroup[name], 'collectionGroup', name);
return this._collectionGroup[name];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":7,"./Shared":40}],9:[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":10,"./Metrics.js":19,"./Overload":32,"./Shared":40}],10:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":6,"./Collection.js":7,"./Metrics.js":19,"./Overload":32,"./Shared":40}],11:[function(_dereq_,module,exports){
"use strict";
// TODO: Remove the _update* methods because we are already mixing them
// TODO: in now via Mixin.Updating and update autobind to extend the _update*
// TODO: methods like we already do with collection
var Shared,
Collection,
Db;
Shared = _dereq_('./Shared');
/**
* Creates a new Document instance. Documents allow you to create individual
* objects that can have standard ForerunnerDB CRUD operations run against
* them, as well as data-binding if the AutoBind module is included in your
* project.
* @name Document
* @class Document
* @constructor
*/
var FdbDocument = function () {
this.init.apply(this, arguments);
};
FdbDocument.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', FdbDocument);
Shared.mixin(FdbDocument.prototype, 'Mixin.Common');
Shared.mixin(FdbDocument.prototype, 'Mixin.Events');
Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor');
Shared.mixin(FdbDocument.prototype, 'Mixin.Constants');
Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers');
Shared.mixin(FdbDocument.prototype, 'Mixin.Matching');
Shared.mixin(FdbDocument.prototype, 'Mixin.Updating');
Shared.mixin(FdbDocument.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @func state
* @memberof Document
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Document
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'db');
/**
* Gets / sets the document name.
* @func name
* @memberof Document
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'name');
/**
* Sets the data for the document.
* @func setData
* @memberof Document
* @param data
* @param options
* @returns {Document}
*/
FdbDocument.prototype.setData = function (data, options) {
var i,
$unset;
if (data) {
options = options || {
$decouple: true
};
if (options && options.$decouple === true) {
data = this.decouple(data);
}
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)});
}
return this;
};
/**
* Gets the document's data returned as a single object.
* @func find
* @memberof Document
* @param {Object} query The query object - currently unused, just
* provide a blank object e.g. {}
* @param {Object=} options An options object.
* @returns {Object} The document's data object.
*/
FdbDocument.prototype.find = function (query, options) {
var result;
if (options && options.$decouple === false) {
result = this._data;
} else {
result = this.decouple(this._data);
}
return result;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
* @func update
* @memberof Document
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
FdbDocument.prototype.update = function (query, update, options) {
var result = this.updateObject(this._data, update, query, options);
if (result) {
this.deferEmit('change', {type: 'update', data: this.decouple(this._data)});
}
};
/**
* Internal method for document updating.
* @func updateObject
* @memberof Document
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
FdbDocument.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @func _isPositionalKey
* @memberof Document
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
FdbDocument.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @func _updateProperty
* @memberof Document
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
FdbDocument.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @func _updateIncrement
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
FdbDocument.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @func _updateSpliceMove
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @func _updateSplicePush
* @memberof Document
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @func _updatePush
* @memberof Document
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @func _updatePull
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
FdbDocument.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @func _updateMultiply
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
FdbDocument.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @func _updateRename
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
FdbDocument.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @func _updateUnset
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
FdbDocument.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Drops the document.
* @func drop
* @memberof Document
* @returns {boolean} True if successful, false if not.
*/
FdbDocument.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
this._state = 'dropped';
delete this._db._document[this._name];
delete this._data;
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
return true;
}
}
} else {
return true;
}
return false;
};
/**
* Creates a new document instance or returns an existing
* instance if one already exists with the passed name.
* @func document
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.document = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof FdbDocument) {
if (name.state() !== 'droppped') {
return name;
} else {
name = name.name();
}
}
if (this._document && this._document[name]) {
return this._document[name];
}
this._document = this._document || {};
this._document[name] = new FdbDocument(name).db(this);
self.emit('create', self._document[name], 'document', name);
return this._document[name];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @func documents
* @memberof Db
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Db.prototype.documents = function () {
var arr = [],
item,
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
item = this._document[i];
arr.push({
name: i,
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = FdbDocument;
},{"./Collection":7,"./Shared":40}],12:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - rob@irrelon.com
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],13:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
View,
CollectionInit,
DbInit,
ReactorIO;
//Shared = ForerunnerDB.shared;
Shared = _dereq_('./Shared');
/**
* Creates a new grid instance.
* @name Grid
* @class Grid
* @param {String} selector jQuery selector.
* @param {String} template The template selector.
* @param {Object=} options The options object to apply to the grid.
* @constructor
*/
var Grid = function (selector, template, options) {
this.init.apply(this, arguments);
};
Grid.prototype.init = function (selector, template, options) {
var self = this;
this._selector = selector;
this._template = template;
this._options = options || {};
this._debug = {};
this._id = this.objectId();
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Grid', Grid);
Shared.mixin(Grid.prototype, 'Mixin.Common');
Shared.mixin(Grid.prototype, 'Mixin.ChainReactor');
Shared.mixin(Grid.prototype, 'Mixin.Constants');
Shared.mixin(Grid.prototype, 'Mixin.Triggers');
Shared.mixin(Grid.prototype, 'Mixin.Events');
Shared.mixin(Grid.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
View = _dereq_('./View');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @func state
* @memberof Grid
* @param {String=} val The name of the state to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'state');
/**
* Gets / sets the current name.
* @func name
* @memberof Grid
* @param {String=} val The name to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'name');
/**
* Executes an insert against the grid's underlying data-source.
* @func insert
* @memberof Grid
*/
Grid.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the grid's underlying data-source.
* @func update
* @memberof Grid
*/
Grid.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the grid's underlying data-source.
* @func updateById
* @memberof Grid
*/
Grid.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the grid's underlying data-source.
* @func remove
* @memberof Grid
*/
Grid.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Sets the collection from which the grid will assemble its data.
* @func from
* @memberof Grid
* @param {Collection} collection The collection to use to assemble grid data.
* @returns {Grid}
*/
Grid.prototype.from = function (collection) {
//var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
this.refresh();
}
return this;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Grid
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Grid.prototype, 'db', function (db) {
if (db) {
// Apply the same debug settings
this.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
Grid.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from grid
delete this._from;
}
};
/**
* Drops a grid and all it's stored data from the database.
* @func drop
* @memberof Grid
* @returns {boolean} True on success, false on failure.
*/
Grid.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
// Remove data-binding
this._from.unlink(this._selector, this.template());
// Kill listeners and references
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping grid ' + this._selector);
}
this._state = 'dropped';
if (this._db && this._selector) {
delete this._db._grid[this._selector];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._selector;
delete this._template;
delete this._from;
delete this._db;
delete this._listeners;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the grid's HTML template to use when rendering.
* @func template
* @memberof Grid
* @param {Selector} template The template's jQuery selector.
* @returns {*}
*/
Grid.prototype.template = function (template) {
if (template !== undefined) {
this._template = template;
return this;
}
return this._template;
};
Grid.prototype._sortGridClick = function (e) {
var elem = window.jQuery(e.currentTarget),
sortColText = elem.attr('data-grid-sort') || '',
sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1,
sortCols = sortColText.split(','),
sortObj = {},
i;
// Remove all grid sort tags from the grid
window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir');
// Flip the sort direction
elem.attr('data-grid-dir', sortColDir);
for (i = 0; i < sortCols.length; i++) {
sortObj[sortCols] = sortColDir;
}
Shared.mixin(sortObj, this._options.$orderBy);
this._from.orderBy(sortObj);
this.emit('sort', sortObj);
};
/**
* Refreshes the grid data such as ordering etc.
* @func refresh
* @memberof Grid
*/
Grid.prototype.refresh = function () {
if (this._from) {
if (this._from.link) {
var self = this,
elem = window.jQuery(this._selector),
sortClickListener = function () {
self._sortGridClick.apply(self, arguments);
};
// Clear the container
elem.html('');
if (self._from.orderBy) {
// Remove listeners
elem.off('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Remove listeners
elem.off('click', '[data-grid-filter]', sortClickListener);
}
// Set wrap name if none is provided
self._options.$wrap = self._options.$wrap || 'gridRow';
// Auto-bind the data to the grid template
self._from.link(self._selector, self.template(), self._options);
// Check if the data source (collection or view) has an
// orderBy method (usually only views) and if so activate
// the sorting system
if (self._from.orderBy) {
// Listen for sort requests
elem.on('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Listen for filter requests
var queryObj = {};
elem.find('[data-grid-filter]').each(function (index, filterElem) {
filterElem = window.jQuery(filterElem);
var filterField = filterElem.attr('data-grid-filter'),
filterVarType = filterElem.attr('data-grid-vartype'),
filterSort = {},
title = filterElem.html(),
dropDownButton,
dropDownMenu,
template,
filterQuery,
filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField);
filterSort[filterField] = 1;
filterQuery = {
$distinct: filterSort
};
filterView
.query(filterQuery)
.orderBy(filterSort)
.from(self._from._from);
template = [
'<div class="dropdown" id="' + self._id + '_' + filterField + '">',
'<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">',
title + ' <span class="caret"></span>',
'</button>',
'</div>'
];
dropDownButton = window.jQuery(template.join(''));
dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>');
dropDownButton.append(dropDownMenu);
filterElem.html(dropDownButton);
// Data-link the underlying data to the grid filter drop-down
filterView.link(dropDownMenu, {
template: [
'<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">',
'<input type="search" class="form-control gridFilterSearch" placeholder="Search...">',
'<span class="input-group-btn">',
'<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',
'</span>',
'</li>',
'<li role="presentation" class="divider"></li>',
'<li role="presentation" data-val="$all">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox" checked> All',
'</a>',
'</li>',
'<li role="presentation" class="divider"></li>',
'{^{for options}}',
'<li role="presentation" data-link="data-val{:' + filterField + '}">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox"> {^{:' + filterField + '}}',
'</a>',
'</li>',
'{{/for}}'
].join('')
}, {
$wrap: 'options'
});
elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) {
var elem = window.jQuery(this),
query = filterView.query(),
search = elem.val();
if (search) {
query[filterField] = new RegExp(search, 'gi');
} else {
delete query[filterField];
}
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) {
// Clear search text box
window.jQuery(this).parents('li').find('.gridFilterSearch').val('');
// Clear view query
var query = filterView.query();
delete query[filterField];
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) {
e.stopPropagation();
var fieldValue,
elem = $(this),
checkbox = elem.find('input[type="checkbox"]'),
checked,
addMode = true,
fieldInArr,
liElem,
i;
// If the checkbox is not the one clicked on
if (!window.jQuery(e.target).is('input')) {
// Set checkbox to opposite of current value
checkbox.prop('checked', !checkbox.prop('checked'));
checked = checkbox.is(':checked');
} else {
checkbox.prop('checked', checkbox.prop('checked'));
checked = checkbox.is(':checked');
}
liElem = window.jQuery(this);
fieldValue = liElem.attr('data-val');
// Check if the selection is the "all" option
if (fieldValue === '$all') {
// Remove the field from the query
delete queryObj[filterField];
// Clear all other checkboxes
liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false);
} else {
// Clear the "all" checkbox
liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false);
// Check if the type needs casting
switch (filterVarType) {
case 'integer':
fieldValue = parseInt(fieldValue, 10);
break;
case 'float':
fieldValue = parseFloat(fieldValue);
break;
default:
}
// Check if the item exists already
queryObj[filterField] = queryObj[filterField] || {
$in: []
};
fieldInArr = queryObj[filterField].$in;
for (i = 0; i < fieldInArr.length; i++) {
if (fieldInArr[i] === fieldValue) {
// Item already exists
if (checked === false) {
// Remove the item
fieldInArr.splice(i, 1);
}
addMode = false;
break;
}
}
if (addMode && checked) {
fieldInArr.push(fieldValue);
}
if (!fieldInArr.length) {
// Remove the field from the query
delete queryObj[filterField];
}
}
// Set the view query
self._from.queryData(queryObj);
if (self._from.pageFirst) {
self._from.pageFirst();
}
});
});
}
self.emit('refresh');
} else {
throw('Grid requires the AutoBind module in order to operate!');
}
}
return this;
};
/**
* Returns the number of documents currently in the grid.
* @func count
* @memberof Grid
* @returns {Number}
*/
Grid.prototype.count = function () {
return this._from.count();
};
/**
* Creates a grid and assigns the collection as its data source.
* @func grid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.grid = View.prototype.grid = function (selector, template, options) {
if (this._db && this._db._grid ) {
if (selector !== undefined) {
if (template !== undefined) {
if (!this._db._grid[selector]) {
var grid = new Grid(selector, template, options)
.db(this._db)
.from(this);
this._grid = this._grid || [];
this._grid.push(grid);
this._db._grid[selector] = grid;
return grid;
} else {
throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector);
}
}
return this._db._grid[selector];
}
return this._db._grid;
}
};
/**
* Removes a grid safely from the DOM. Must be called when grid is
* no longer required / is being removed from DOM otherwise references
* will stick around and cause memory leaks.
* @func unGrid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) {
var i,
grid;
if (this._db && this._db._grid ) {
if (selector && template) {
if (this._db._grid[selector]) {
grid = this._db._grid[selector];
delete this._db._grid[selector];
return grid.drop();
} else {
throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name);
}
} else {
// No parameters passed, remove all grids from this module
for (i in this._db._grid) {
if (this._db._grid.hasOwnProperty(i)) {
grid = this._db._grid[i];
delete this._db._grid[i];
grid.drop();
if (this.debug()) {
console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"');
}
}
}
this._db._grid = {};
}
}
};
/**
* Adds a grid to the internal grid lookup.
* @func _addGrid
* @memberof Collection
* @param {Grid} grid The grid to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) {
if (grid !== undefined) {
this._grid = this._grid || [];
this._grid.push(grid);
}
return this;
};
/**
* Removes a grid from the internal grid lookup.
* @func _removeGrid
* @memberof Collection
* @param {Grid} grid The grid to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) {
if (grid !== undefined && this._grid) {
var index = this._grid.indexOf(grid);
if (index > -1) {
this._grid.splice(index, 1);
}
}
return this;
};
// Extend DB with grids init
Db.prototype.init = function () {
this._grid = {};
DbInit.apply(this, arguments);
};
/**
* Determine if a grid with the passed name already exists.
* @func gridExists
* @memberof Db
* @param {String} selector The jQuery selector to bind the grid to.
* @returns {boolean}
*/
Db.prototype.gridExists = function (selector) {
return Boolean(this._grid[selector]);
};
/**
* Creates a grid based on the passed arguments.
* @func grid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.grid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Removes a grid based on the passed arguments.
* @func unGrid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.unGrid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Returns an array of grids the DB currently has.
* @func grids
* @memberof Db
* @returns {Array} An array of objects containing details of each grid
* the database is currently managing.
*/
Db.prototype.grids = function () {
var arr = [],
item,
i;
for (i in this._grid) {
if (this._grid.hasOwnProperty(i)) {
item = this._grid[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Grid');
module.exports = Grid;
},{"./Collection":7,"./CollectionGroup":8,"./ReactorIO":38,"./Shared":40,"./View":42}],14:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy,
this._options
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Common');
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
sData,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
if (xAxis.categories) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
} else {
seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]);
}
}
sData = {
name: seriesName,
data: seriesValues
};
if (options.seriesOptions) {
for (k in options.seriesOptions) {
if (options.seriesOptions.hasOwnProperty(k)) {
sData[k] = options.seriesOptions[k];
}
}
}
seriesData.push(sData);
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () {
self._changeListener.apply(self, arguments);
});
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () {
self.drop.apply(self);
});
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if (typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy,
self._options
);
if (seriesData.xAxis.categories) {
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
}
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
if (callback) {
callback(false, true);
}
delete this._listeners;
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @func pieChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func pieChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via selector.
* @func lineChart
* @memberof Highchart
* @param {String} selector The chart selector.
* @returns {*}
*/
'string': function (selector) {
return this._highcharts[selector];
},
/**
* Chart via options object.
* @func lineChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func lineChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @func areaChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func areaChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @func columnChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func columnChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @func barChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func barChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @func stackedBarChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func stackedBarChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @memberof Collection
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":32,"./Shared":40}],15:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
/**
* Create the index.
* @param {Object} keys The object with the keys that the user wishes the index
* to operate on.
* @param {Object} options Can be undefined, if passed is an object with arbitrary
* options keys and values.
* @param {Collection} collection The collection the index should be created for.
*/
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
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;
};
// Register this index on the shared object
Shared.index['2d'] = Index2d;
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":5,"./GeoHash":12,"./Path":34,"./Shared":40}],16:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* 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;
};
// Register this index on the shared object
Shared.index.btree = IndexBinaryTree;
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":5,"./Path":34,"./Shared":40}],17:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.hashed = IndexHashMap;
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":34,"./Shared":40}],18:[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":40}],19:[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":31,"./Shared":40}],20:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],21:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index,
dataCopy = this.decouple(data, count);
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, dataCopy[index], options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],22:[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":32,"./Serialiser":39}],23:[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;
},{}],24:[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":32}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
if (sourceType === 'object' && source === null) {
sourceType = 'null';
}
if (testType === 'object' && test === null) {
testType = 'null';
}
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number' || sourceType === 'null' || testType === 'null') {
// Number or null comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],26:[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;
},{}],27:[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;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
self.triggerStack = {};
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
/**
* Tells the current instance to fire or ignore all triggers whether they
* are enabled or not.
* @param {Boolean} val Set to true to ignore triggers or false to not
* ignore them.
* @returns {*}
*/
ignoreTriggers: function (val) {
if (val !== undefined) {
this._ignoreTriggers = val;
return this;
}
return this._ignoreTriggers;
},
/**
* Generates triggers that fire in the after phase for all CRUD ops
* that automatically transform data back and forth and keep both
* import and export collections in sync with each other.
* @param {String} id The unique id for this link IO.
* @param {Object} ioData The settings for the link IO.
*/
addLinkIO: function (id, ioData) {
var self = this,
matchAll,
exportData,
importData,
exportTriggerMethod,
importTriggerMethod,
exportTo,
importFrom,
allTypes,
i;
// Store the linkIO
self._linkIO = self._linkIO || {};
self._linkIO[id] = ioData;
exportData = ioData['export'];
importData = ioData['import'];
if (exportData) {
exportTo = self.db().collection(exportData.to);
}
if (importData) {
importFrom = self.db().collection(importData.from);
}
allTypes = [
self.TYPE_INSERT,
self.TYPE_UPDATE,
self.TYPE_REMOVE
];
matchAll = function (data, callback) {
// Match all
callback(false, true);
};
if (exportData) {
// Check for export match method
if (!exportData.match) {
// No match method found, use the match all method
exportData.match = matchAll;
}
// Check for export types
if (!exportData.types) {
exportData.types = allTypes;
}
exportTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
exportData.match(newDoc, function (err, doExport) {
if (!err && doExport) {
// Get data to upsert (if any)
exportData.data(newDoc, operation.type, function (err, data, callback) {
if (!err && data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
exportTo.upsert(data, callback);
} else {
// Do remove
exportTo.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (importData) {
// Check for import match method
if (!importData.match) {
// No match method found, use the match all method
importData.match = matchAll;
}
// Check for import types
if (!importData.types) {
importData.types = allTypes;
}
importTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
importData.match(newDoc, function (err, doExport) {
if (!err && doExport) {
// Get data to upsert (if any)
importData.data(newDoc, operation.type, function (err, data, callback) {
if (!err && data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
self.upsert(data, callback);
} else {
// Do remove
self.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod);
}
}
if (importData) {
for (i = 0; i < importData.types.length; i++) {
importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod);
}
}
},
/**
* Removes a previously added link IO via it's ID.
* @param {String} id The id of the link IO to remove.
* @returns {boolean} True if successful, false if the link IO
* was not found.
*/
removeLinkIO: function (id) {
var self = this,
linkIO = self._linkIO[id],
exportData,
importData,
importFrom,
i;
if (linkIO) {
exportData = linkIO['export'];
importData = linkIO['import'];
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER);
}
}
if (importData) {
importFrom = self.db().collection(importData.from);
for (i = 0; i < importData.types.length; i++) {
importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER);
}
}
delete self._linkIO[id];
return true;
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response,
typeName,
phaseName;
if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (self.debug()) {
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Check if the trigger is already in the stack, if it is,
// don't fire it again (this is so we avoid infinite loops
// where a trigger triggers another trigger which calls this
// one and so on)
if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) {
// The trigger is already in the stack, do not fire the trigger again
if (self.debug()) {
console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!');
}
continue;
}
// Add the trigger to the stack so we don't go down an endless
// trigger loop
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = true;
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Remove the trigger from the stack
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = false;
// Check the response for a non-expected result (anything other than
// [undefined, true or false] is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":32}],29:[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;
},{}],30:[function(_dereq_,module,exports){
"use strict";
// Tell JSHint about EventSource
/*global
EventSource
*/
// Import external names locally
var Shared = _dereq_('./Shared'),
Core,
CoreInit,
Collection,
NodeApiClient,
Overload;
NodeApiClient = function () {
this.init.apply(this, arguments);
};
/**
* The init method that can be overridden or extended.
* @param {Core} core The ForerunnerDB core instance.
*/
NodeApiClient.prototype.init = function (core) {
var self = this;
self._core = core;
self.rootPath('/fdb');
};
Shared.addModule('NodeApiClient', NodeApiClient);
Shared.mixin(NodeApiClient.prototype, 'Mixin.Common');
Shared.mixin(NodeApiClient.prototype, 'Mixin.Events');
Shared.mixin(NodeApiClient.prototype, 'Mixin.ChainReactor');
Core = Shared.modules.Core;
CoreInit = Core.prototype.init;
Collection = Shared.modules.Collection;
Overload = Shared.overload;
Shared.synthesize(NodeApiClient.prototype, 'rootPath');
/**
* Set the url of the server to use for API.
* @name server
* @param {String} host The server host name including protocol. E.g.
* "https://0.0.0.0".
* @param {String} port The server port number e.g. "8080".
*/
NodeApiClient.prototype.server = function (host, port) {
if (host !== undefined) {
if (host.substr(host.length - 1, 1) === '/') {
// Strip trailing /
host = host.substr(0, host.length - 1);
}
if (port !== undefined) {
this._server = host + ":" + port;
} else {
this._server = host;
}
this._host = host;
this._port = port;
return this;
}
if (port !== undefined) {
return {
host: this._host,
port: this._port,
url: this._server
};
} else {
return this._server;
}
};
NodeApiClient.prototype.http = function (method, url, data, options, callback) {
var self = this,
finalUrl,
sessionData,
bodyData,
xmlHttp = new XMLHttpRequest();
method = method.toUpperCase();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
// Tell the callback about success
if (xmlHttp.responseText) {
callback(false, self.jParse(xmlHttp.responseText));
} else {
callback(false, {});
}
} else if (xmlHttp.status === 204) {
callback(false, {});
} else {
// Tell the callback about the error
callback(xmlHttp.status, xmlHttp.responseText);
// Emit the error code
self.emit('httpError', xmlHttp.status, xmlHttp.responseText);
}
}
};
switch (method) {
case 'GET':
case 'DELETE':
case 'HEAD':
// Check for global auth
if (this._sessionData) {
data = data !== undefined ? data : {};
// Add the session data to the key specified
data[this._sessionData.key] = this._sessionData.obj;
}
finalUrl = url + (data !== undefined ? '?' + self.jStringify(data) : '');
bodyData = null;
break;
case 'POST':
case 'PUT':
case 'PATCH':
// Check for global auth
if (this._sessionData) {
sessionData = {};
// Add the session data to the key specified
sessionData[this._sessionData.key] = this._sessionData.obj;
}
finalUrl = url + (sessionData !== undefined ? '?' + self.jStringify(sessionData) : '');
bodyData = (data !== undefined ? self.jStringify(data) : null);
break;
default:
return false;
}
xmlHttp.open(method, finalUrl, true);
xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlHttp.send(bodyData);
return this;
};
// Define HTTP helper methods
NodeApiClient.prototype.head = new Overload({
'string, function': function (path, callback) {
return this.$main.call(this, path, undefined, {}, callback);
},
'string, *, function': function (path, data, callback) {
return this.$main.call(this, path, data, {}, callback);
},
'string, *, object, function': function (path, data, options, callback) {
return this.$main.call(this, path, data, options, callback);
},
'$main': function (path, data, options, callback) {
return this.http('HEAD', this.server() + this._rootPath + path, data, options, callback);
}
});
NodeApiClient.prototype.get = new Overload({
'string, function': function (path, callback) {
return this.$main.call(this, path, undefined, {}, callback);
},
'string, *, function': function (path, data, callback) {
return this.$main.call(this, path, data, {}, callback);
},
'string, *, object, function': function (path, data, options, callback) {
return this.$main.call(this, path, data, options, callback);
},
'$main': function (path, data, options, callback) {
return this.http('GET', this.server() + this._rootPath + path, data, options, callback);
}
});
NodeApiClient.prototype.put = new Overload({
'string, function': function (path, callback) {
return this.$main.call(this, path, undefined, {}, callback);
},
'string, *, function': function (path, data, callback) {
return this.$main.call(this, path, data, {}, callback);
},
'string, *, object, function': function (path, data, options, callback) {
return this.$main.call(this, path, data, options, callback);
},
'$main': function (path, data, options, callback) {
return this.http('PUT', this.server() + this._rootPath + path, data, options, callback);
}
});
NodeApiClient.prototype.post = new Overload({
'string, function': function (path, callback) {
return this.$main.call(this, path, undefined, {}, callback);
},
'string, *, function': function (path, data, callback) {
return this.$main.call(this, path, data, {}, callback);
},
'string, *, object, function': function (path, data, options, callback) {
return this.$main.call(this, path, data, options, callback);
},
'$main': function (path, data, options, callback) {
return this.http('POST', this.server() + this._rootPath + path, data, options, callback);
}
});
NodeApiClient.prototype.patch = new Overload({
'string, function': function (path, callback) {
return this.$main.call(this, path, undefined, {}, callback);
},
'string, *, function': function (path, data, callback) {
return this.$main.call(this, path, data, {}, callback);
},
'string, *, object, function': function (path, data, options, callback) {
return this.$main.call(this, path, data, options, callback);
},
'$main': function (path, data, options, callback) {
return this.http('PATCH', this.server() + this._rootPath + path, data, options, callback);
}
});
NodeApiClient.prototype.postPatch = function (path, id, data, options, callback) {
var self = this;
// Determine if the item exists or not
this.head(path + '/' + id, undefined, {}, function (err, headData) {
if (err) {
if (err === 404) {
// Item does not exist, run post
return self.http('POST', self.server() + self._rootPath + path, data, options, callback);
} else {
callback(err, data);
}
} else {
// Item already exists, run patch
return self.http('PATCH', self.server() + self._rootPath + path + '/' + id, data, options, callback);
}
});
};
NodeApiClient.prototype.delete = new Overload({
'string, function': function (path, callback) {
return this.$main.call(this, path, undefined, {}, callback);
},
'string, *, function': function (path, data, callback) {
return this.$main.call(this, path, data, {}, callback);
},
'string, *, object, function': function (path, data, options, callback) {
return this.$main.call(this, path, data, options, callback);
},
'$main': function (path, data, options, callback) {
return this.http('DELETE', this.server() + this._rootPath + path, data, options, callback);
}
});
/**
* Gets/ sets a global object that will be sent up with client
* requests to the API or REST server.
* @param {String} key The key to send the session object up inside.
* @param {*} obj The object / value to send up with all requests. If
* a request has its own data to send up, this session data will be
* mixed in to the request data under the specified key.
*/
NodeApiClient.prototype.session = function (key, obj) {
if (key !== undefined && obj !== undefined) {
this._sessionData = {
key: key,
obj: obj
};
return this;
}
return this._sessionData;
};
/**
* Initiates a client connection to the API server.
* @param collectionInstance
* @param path
* @param query
* @param options
* @param callback
*/
NodeApiClient.prototype.sync = function (collectionInstance, path, query, options, callback) {
var self = this,
source,
finalPath,
queryParams,
queryString = '',
connecting = true;
if (this.debug()) {
console.log(this.logIdentifier() + ' Connecting to API server ' + this.server() + this._rootPath + path);
}
finalPath = this.server() + this._rootPath + path + '/_sync';
// Check for global auth
if (this._sessionData) {
queryParams = queryParams || {};
if (this._sessionData.key) {
// Add the session data to the key specified
queryParams[this._sessionData.key] = this._sessionData.obj;
} else {
// Add the session data to the root query object
Shared.mixin(queryParams, this._sessionData.obj);
}
}
if (query) {
queryParams = queryParams || {};
queryParams.$query = query;
}
if (options) {
queryParams = queryParams || {};
if (options.$initialData === undefined) {
options.$initialData = true;
}
queryParams.$options = options;
}
if (queryParams) {
queryString = this.jStringify(queryParams);
finalPath += '?' + queryString;
}
source = new EventSource(finalPath);
collectionInstance.__apiConnection = source;
source.addEventListener('open', function (e) {
if (!options || (options && options.$initialData)) {
// The connection is open, grab the initial data
self.get(path, queryParams, function (err, data) {
if (!err) {
collectionInstance.upsert(data);
}
});
}
}, false);
source.addEventListener('error', function (e) {
if (source.readyState === 2) {
// The connection is dead, remove the connection
collectionInstance.unSync();
}
if (connecting) {
connecting = false;
callback(e);
}
}, false);
source.addEventListener('insert', function(e) {
var data = self.jParse(e.data);
collectionInstance.insert(data.dataSet);
}, false);
source.addEventListener('update', function(e) {
var data = self.jParse(e.data);
collectionInstance.update(data.query, data.update);
}, false);
source.addEventListener('remove', function(e) {
var data = self.jParse(e.data);
collectionInstance.remove(data.query);
}, false);
if (callback) {
source.addEventListener('connected', function (e) {
if (connecting) {
connecting = false;
callback(false);
}
}, false);
}
};
Collection.prototype.sync = new Overload({
/**
* Sync with this collection on the server-side.
* @param {Function} callback The callback method to call once
* the connection to the server has been established.
*/
'function': function (callback) {
this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), null, null, callback);
},
/**
* Sync with this collection on the server-side.
* @param {String} collectionName The collection to sync from.
* @param {Function} callback The callback method to call once
* the connection to the server has been established.
*/
'string, function': function (collectionName, callback) {
this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, null, null, callback);
},
/**
* Sync with this collection on the server-side.
* @param {Object} query A query object.
* @param {Function} callback The callback method to call once
* the connection to the server has been established.
*/
'object, function': function (query, callback) {
this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), query, null, callback);
},
/**
* Sync with this collection on the server-side.
* @param {String} objectType The type of object to sync to e.g.
* "collection" or "view".
* @param {String} objectName The name of the object to sync from.
* @param {Function} callback The callback method to call once
* the connection to the server has been established.
*/
'string, string, function': function (objectType, objectName, callback) {
this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, null, null, callback);
},
/**
* Sync with this collection on the server-side.
* @param {String} collectionName The collection to sync from.
* @param {Object} query A query object.
* @param {Function} callback The callback method to call once
* the connection to the server has been established.
*/
'string, object, function': function (collectionName, query, callback) {
this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, query, null, callback);
},
/**
* Sync with this collection on the server-side.
* @param {String} objectType The type of object to sync to e.g.
* "collection" or "view".
* @param {String} objectName The name of the object to sync from.
* @param {Object} query A query object.
* @param {Function} callback The callback method to call once
* the connection to the server has been established.
*/
'string, string, object, function': function (objectType, objectName, query, callback) {
this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, query, null, callback);
},
/**
* Sync with this collection on the server-side.
* @param {Object} query A query object.
* @param {Object} options An options object.
* @param {Function} callback The callback method to call once
* the connection to the server has been established.
*/
'object, object, function': function (query, options, callback) {
this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), query, options, callback);
},
/**
* Sync with this collection on the server-side.
* @param {String} collectionName The collection to sync from.
* @param {Object} query A query object.
* @param {Object} options An options object.
* @param {Function} callback The callback method to call once
* the connection to the server has been established.
*/
'string, object, object, function': function (collectionName, query, options, callback) {
this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, query, options, callback);
},
/**
* Sync with this collection on the server-side.
* @param {String} objectType The type of object to sync to e.g.
* "collection" or "view".
* @param {String} objectName The name of the object to sync from.
* @param {Object} query A query object.
* @param {Object} options An options object.
* @param {Function} callback The callback method to call once
* the connection to the server has been established.
*/
'string, string, object, object, function': function (objectType, objectName, query, options, callback) {
this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, query, options, callback);
},
'$main': function (path, query, options, callback) {
var self = this;
if (this._db && this._db._core) {
// Kill any existing sync connection
this.unSync();
// Create new sync connection
this._db._core.api.sync(this, path, query, options, callback);
// Hook on drop to call unsync
this.on('drop', function () {
self.unSync();
});
} else {
throw(this.logIdentifier() + ' Cannot sync for an anonymous collection! (Collection must be attached to a database)');
}
}
});
/**
* Disconnects an existing connection to a sync server.
* @returns {boolean} True if a connection existed, false
* if no connection existed.
*/
Collection.prototype.unSync = function () {
if (this.__apiConnection) {
if (this.__apiConnection.readyState !== 2) {
this.__apiConnection.close();
}
delete this.__apiConnection;
return true;
}
return false;
};
Collection.prototype.http = new Overload({
'string, function': function (method, callback) {
this.$main.call(this, method, '/' + this._db.name() + '/collection/' + this.name(), undefined, undefined, {}, callback);
},
'$main': function (method, path, queryObj, queryOptions, options, callback) {
if (this._db && this._db._core) {
return this._db._core.api.http('GET', this._db._core.api.server() + this._rootPath + path, {"$query": queryObj, "$options": queryOptions}, options, callback);
} else {
throw(this.logIdentifier() + ' Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)');
}
}
});
Collection.prototype.autoHttp = new Overload({
'string, function': function (method, callback) {
this.$main.call(this, method, '/' + this._db.name() + '/collection/' + this.name(), undefined, undefined, {}, callback);
},
'string, string, function': function (method, collectionName, callback) {
this.$main.call(this, method, '/' + this._db.name() + '/collection/' + collectionName, undefined, undefined, {}, callback);
},
'string, string, string, function': function (method, objType, objName, callback) {
this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, undefined, undefined, {}, callback);
},
'string, string, string, object, function': function (method, objType, objName, queryObj, callback) {
this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, queryObj, undefined, {}, callback);
},
'string, string, string, object, object, function': function (method, objType, objName, queryObj, queryOptions, callback) {
this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, queryObj, queryOptions, {}, callback);
},
'$main': function (method, path, queryObj, queryOptions, options, callback) {
var self = this;
if (this._db && this._db._core) {
return this._db._core.api.http('GET', this._db._core.api.server() + this._db._core.api._rootPath + path, {"$query": queryObj, "$options": queryOptions}, options, function (err, data) {
var i;
if (!err && data) {
// Check the type of method we used and operate on the collection accordingly
switch (method) {
// Find insert
case 'GET':
self.insert(data);
break;
// Insert
case 'POST':
if (data.inserted && data.inserted.length) {
self.insert(data.inserted);
}
break;
// Update overwrite
case 'PUT':
case 'PATCH':
if (data instanceof Array) {
// Update each document
for (i = 0; i < data.length; i++) {
self.updateById(data[i]._id, {$overwrite: data[i]});
}
} else {
// Update single document
self.updateById(data._id, {$overwrite: data});
}
break;
// Remove
case 'DELETE':
self.remove(data);
break;
default:
// Nothing to do with this method
break;
}
}
// Send the data back to the callback
callback(err, data);
});
} else {
throw(this.logIdentifier() + ' Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)');
}
}
});
// Override the Core init to instantiate the plugin
Core.prototype.init = function () {
CoreInit.apply(this, arguments);
this.api = new NodeApiClient(this);
};
Shared.finishModule('NodeApiClient');
module.exports = NodeApiClient;
},{"./Shared":40}],31:[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":34,"./Shared":40}],32:[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;
},{}],33:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._sources = [];
this._sourceDroppedWrap = function () {
self._sourceDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Shared.mixin(Overview.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (source) {
if (source !== undefined) {
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
this._setFrom(source);
return this;
}
return this._sources;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
/**
* Executes and returns the response from the current reduce method
* assigned to the overview.
* @returns {*}
*/
Overview.prototype.exec = function () {
var reduceFunc = this.reduce();
return reduceFunc ? reduceFunc.apply(this) : undefined;
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._setFrom = function (source) {
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
this._addSource(source);
return this;
};
Overview.prototype._addSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
if (this._sources.indexOf(source) === -1) {
this._sources.push(source);
source.chain(this);
source.on('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
var sourceIndex = this._sources.indexOf(source);
if (sourceIndex > -1) {
this._sources.splice(source, 1);
source.unChain(this);
source.off('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._sourceDropped = function (source) {
if (source) {
// Source was dropped, remove from overview
this._removeSource(source);
}
};
Overview.prototype._refresh = function () {
if (!this.isDropped()) {
if (this._sources && this._sources[0]) {
this._collData.primaryKey(this._sources[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._sources.length; i++) {
tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce.apply(this);
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
delete this._sources;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
}
return true;
};
Db.prototype.overview = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof Overview) {
return name;
}
if (this._overview && this._overview[name]) {
return this._overview[name];
}
this._overview = this._overview || {};
this._overview[name] = new Overview(name).db(this);
self.emit('create', self._overview[name], 'overview', name);
return this._overview[name];
} else {
// Return an object of collection data
return this._overview || {};
}
};
/**
* Returns an array of overviews the DB currently has.
* @returns {Array} An array of objects containing details of each overview
* the database is currently managing.
*/
Db.prototype.overviews = function () {
var arr = [],
item,
i;
for (i in this._overview) {
if (this._overview.hasOwnProperty(i)) {
item = this._overview[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":7,"./Document":11,"./Shared":40}],34:[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":40}],35:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the auto flag which determines if the persistence module
* will automatically load data for collections the first time they are
* accessed and save data whenever it changes. This is disabled by
* default.
* @param {Boolean} val Set to true to enable, false to disable
* @returns {*}
*/
Shared.synthesize(Persist.prototype, 'auto', function (val) {
var self = this;
if (val !== undefined) {
if (val) {
// Hook db events
this._db.on('create', function () { self._autoLoad.apply(self, arguments); });
this._db.on('change', function () { self._autoSave.apply(self, arguments); });
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save enabled');
}
} else {
// Un-hook db events
this._db.off('create', this._autoLoad);
this._db.off('change', this._autoSave);
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save disbled');
}
}
}
return this.$super.call(this, val);
});
Persist.prototype._autoLoad = function (obj, objType, name) {
var self = this;
if (typeof obj.load === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name);
}
obj.load(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic load failed:', err);
}
self.emit('load', err, data);
});
} else {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping');
}
}
};
Persist.prototype._autoSave = function (obj, objType, name) {
var self = this;
if (typeof obj.save === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name);
}
obj.save(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic save failed:', err);
}
self.emit('save', err, data);
});
}
};
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
if (!err) {
localforage.setItem(key, data).then(function (data) {
if (callback) {
callback(false, data, tableStats);
}
}, function (err) {
if (callback) {
callback(err);
}
});
} else {
callback(err);
}
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name);
this._db.persist.drop(this._db._name + '-' + this._name + '-metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name, function () {
self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); }
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) {
if (callback) { callback(err, data, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
//self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) { callback(err, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
/**
* Gets the data that represents this collection for easy storage using
* a third-party method / plugin instead of using the standard persistent
* storage system.
* @param {Function} callback The method to call with the data response.
*/
Collection.prototype.saveCustom = function (callback) {
var self = this,
myData = {},
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.data = {
name: self._db._name + '-' + self._name,
store: data,
tableStats: tableStats
};
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.metaData = {
name: self._db._name + '-' + self._name + '-metaData',
store: data,
tableStats: tableStats
};
callback(false, myData);
} else {
callback(err);
}
});
} else {
callback(err);
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads custom data loaded by a third-party plugin into the collection.
* @param {Object} myData Data object previously saved by using saveCustom()
* @param {Function} callback A callback method to receive notification when
* data has loaded.
*/
Collection.prototype.loadCustom = function (myData, callback) {
var self = this;
if (self._name) {
if (self._db) {
if (myData.data && myData.data.store) {
if (myData.metaData && myData.metaData.store) {
self.decode(myData.data.store, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
self.decode(myData.metaData.store, function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
if (callback) { callback(err, tableStats, metaStats); }
}
} else {
callback(err);
}
});
}
} else {
callback(err);
}
});
} else {
callback('No "metaData" key found in passed object!');
}
} else {
callback('No "data" key found in passed object!');
}
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
Db.prototype.load = new Overload({
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (myData, callback) {
this.$main.call(this, myData, callback);
},
'$main': function (myData, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) {
callback(false);
}
}
} else {
if (callback) {
callback(err);
}
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
if (!myData) {
obj[index].load(loadCallback);
} else {
obj[index].loadCustom(myData, loadCallback);
}
}
}
}
});
Db.prototype.save = new Overload({
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (options, callback) {
this.$main.call(this, options, callback);
},
'$main': function (options, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
if (!options.custom) {
obj[index].save(saveCallback);
} else {
obj[index].saveCustom(saveCallback);
}
}
}
}
});
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":7,"./CollectionGroup":8,"./PersistCompress":36,"./PersistCrypto":37,"./Shared":40,"async":43,"localforage":78}],36:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":40,"pako":79}],37:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":40,"crypto-js":52}],38:[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":40}],39:[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;
},{}],40:[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.749',
modules: {},
plugins: {},
index: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":20,"./Mixin.ChainReactor":21,"./Mixin.Common":22,"./Mixin.Constants":23,"./Mixin.Events":24,"./Mixin.Matching":25,"./Mixin.Sorting":26,"./Mixin.Tags":27,"./Mixin.Triggers":28,"./Mixin.Updating":29,"./Overload":32}],41:[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 = {};
},{}],42:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload'),
Path,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.Matching');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Path = Shared.modules.Path;
sharedPathSolver = new Path();
View.prototype.init = function (name, query, options) {
var self = this;
this.sharedPathSolver = sharedPathSolver;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._data = new Collection(this.name() + '_internal');
};
/**
* This reactor IO node is given data changes from source data and
* then acts as a firewall process between the source and view data.
* Data needs to meet the requirements this IO node imposes before
* the data is passed down the reactor chain (to the view). This
* allows us to intercept data changes from the data source and act
* on them such as applying transforms, checking the data matches
* the view's query, applying joins to the data etc before sending it
* down the reactor chain via the this.chainSend() calls.
*
* Update packets are especially complex to handle because an update
* on the underlying source data could translate into an insert,
* update or remove call on the view. Take a scenario where the view's
* query limits the data see from the source. If the source data is
* updated and the data now falls inside the view's query limitations
* the data is technically now an insert on the view, not an update.
* The same is true in reverse where the update becomes a remove. If
* the updated data already exists in the view and will still exist
* after the update operation then the update can remain an update.
* @param {Object} chainPacket The chain reactor packet representing the
* data operation that has just been processed on the source data.
* @param {View} self The reference to the view we are operating for.
* @private
*/
View.prototype._handleChainIO = function (chainPacket, self) {
var type = chainPacket.type,
hasActiveJoin,
hasActiveQuery,
hasTransformIn,
sharedData;
// NOTE: "self" in this context is the view instance.
// NOTE: "this" in this context is the ReactorIO node sitting in
// between the source (sender) and the destination (listener) and
// in this case the source is the view's "from" data source and the
// destination is the view's _data collection. This means
// that "this.chainSend()" is asking the ReactorIO node to send the
// packet on to the destination listener.
// EARLY EXIT: Check that the packet is not a CRUD operation
if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') {
// This packet is NOT a CRUD operation packet so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We only need to check packets under three conditions
// 1) We have a limiting query on the view "active query",
// 2) We have a query options with a $join clause on the view "active join"
// 3) We have a transformIn operation registered on the view.
// If none of these conditions exist we can just allow the chain
// packet to proceed as normal
hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join);
hasActiveQuery = Boolean(self._querySettings.query);
hasTransformIn = self._data._transformIn !== undefined;
// EARLY EXIT: Check for any complex operation flags and if none
// exist, send the packet on and exit early
if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) {
// We don't have any complex operation flags so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We have either an active query, active join or a transformIn
// function registered on the view
// We create a shared data object here so that the disparate method
// calls can share data with each other via this object whilst
// still remaining separate methods to keep code relatively clean.
sharedData = {
dataArr: [],
removeArr: []
};
// Check the packet type to get the data arrays to work on
if (chainPacket.type === 'insert') {
// Check if the insert data is an array
if (chainPacket.data.dataSet instanceof Array) {
// Use the insert data array
sharedData.dataArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single insert object
sharedData.dataArr = [chainPacket.data.dataSet];
}
} else if (chainPacket.type === 'update') {
// Use the dataSet array
sharedData.dataArr = chainPacket.data.dataSet;
} else if (chainPacket.type === 'remove') {
if (chainPacket.data.dataSet instanceof Array) {
// Use the remove data array
sharedData.removeArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single remove object
sharedData.removeArr = [chainPacket.data.dataSet];
}
}
// Safety check
if (!(sharedData.dataArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!');
sharedData.dataArr = [];
}
if (!(sharedData.removeArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!');
sharedData.removeArr = [];
}
// We need to operate in this order:
// 1) Check if there is an active join - active joins are operated
// against the SOURCE data. The joined data can potentially be
// utilised by any active query or transformIn so we do this step first.
// 2) Check if there is an active query - this is a query that is run
// against the SOURCE data after any active joins have been resolved
// on the source data. This allows an active query to operate on data
// that would only exist after an active join has been executed.
// If the source data does not fall inside the limiting factors of the
// active query then we add it to a removal array. If it does fall
// inside the limiting factors when we add it to an upsert array. This
// is because data that falls inside the query could end up being
// either new data or updated data after a transformIn operation.
// 3) Check if there is a transformIn function. If a transformIn function
// exist we run it against the data after doing any active join and
// active query.
if (hasActiveJoin) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
self._handleChainIO_ActiveJoin(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
}
if (hasActiveQuery) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
self._handleChainIO_ActiveQuery(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
}
if (hasTransformIn) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
self._handleChainIO_TransformIn(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
}
// Check if we still have data to operate on and exit
// if there is none left
if (!sharedData.dataArr.length && !sharedData.removeArr.length) {
// There is no more data to operate on, exit without
// sending any data down the chain reactor (return true
// will tell reactor to exit without continuing)!
return true;
}
// Grab the public data collection's primary key
sharedData.pk = self._data.primaryKey();
// We still have data left, let's work out how to handle it
// first let's loop through the removals as these are easy
if (sharedData.removeArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
self._handleChainIO_RemovePackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
}
if (sharedData.dataArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
self._handleChainIO_UpsertPackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
}
// Now return true to tell the chain reactor not to propagate
// the data itself as we have done all that work here
return true;
};
View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) {
var dataArr = sharedData.dataArr,
removeArr;
// Since we have an active join, all we need to do is operate
// the join clause on each item in the packet's data array.
removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {});
// Now that we've run our join keep in mind that joins can exclude data
// if there is no matching joined data and the require: true clause in
// the join options is enabled. This means we have to store a removal
// array that tells us which items from the original data we sent to
// join did not match the join data and were set with a require flag.
// Now that we have our array of items to remove, let's run through the
// original data and remove them from there.
this.spliceArrayByIndexList(dataArr, removeArr);
// Make sure we add any items we removed to the shared removeArr
sharedData.removeArr = sharedData.removeArr.concat(removeArr);
};
View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
i;
// Now we need to run the data against the active query to
// see if the data should be in the final data list or not,
// so we use the _match method.
// Loop backwards so we can safely splice from the array
// while we are looping
for (i = dataArr.length - 1; i >= 0; i--) {
if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
// The data didn't match the active query, add it
// to the shared removeArr
sharedData.removeArr.push(dataArr[i]);
// Now remove it from the shared dataArr
dataArr.splice(i, 1);
}
}
};
View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
removeArr = sharedData.removeArr,
dataIn = self._data._transformIn,
i;
// At this stage we take the remaining items still left in the data
// array and run our transformIn method on each one, modifying it
// from what it was to what it should be on the view. We also have
// to run this on items we want to remove too because transforms can
// affect primary keys and therefore stop us from identifying the
// correct items to run removal operations on.
// It is important that these are transformed BEFORE they are passed
// to the CRUD methods because we use the CU data to check the position
// of the item in the array and that can only happen if it is already
// pre-transformed. The removal stuff also needs pre-transformed
// because ids can be modified by a transform.
for (i = 0; i < dataArr.length; i++) {
// Assign the new value
dataArr[i] = dataIn(dataArr[i]);
}
for (i = 0; i < removeArr.length; i++) {
// Assign the new value
removeArr[i] = dataIn(removeArr[i]);
}
};
View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) {
var $or = [],
pk = sharedData.pk,
removeArr = sharedData.removeArr,
packet = {
dataSet: removeArr,
query: {
$or: $or
}
},
orObj,
i;
for (i = 0; i < removeArr.length; i++) {
orObj = {};
orObj[pk] = removeArr[i][pk];
$or.push(orObj);
}
ioObj.chainSend('remove', packet);
};
View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) {
var data = this._data,
primaryIndex = data._primaryIndex,
primaryCrc = data._primaryCrc,
pk = sharedData.pk,
dataArr = sharedData.dataArr,
arrItem,
insertArr = [],
updateArr = [],
query,
i;
// Let's work out what type of operation this data should
// generate between an insert or an update.
for (i = 0; i < dataArr.length; i++) {
arrItem = dataArr[i];
// Check if the data already exists in the data
if (primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) {
// The document exists in the data collection but data differs, update required
updateArr.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
insertArr.push(arrItem);
}
}
if (insertArr.length) {
ioObj.chainSend('insert', {
dataSet: insertArr
});
}
if (updateArr.length) {
for (i = 0; i < updateArr.length; i++) {
arrItem = updateArr[i];
query = {};
query[pk] = arrItem[pk];
ioObj.chainSend('update', {
query: query,
update: arrItem,
dataSet: [arrItem]
});
}
}
};
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this._data.findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this._data.findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._data;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
// Remove the current reference to the _from since we
// are about to replace it with a new one
delete this._from;
}
// Check if we have an existing reactor io that links the
// previous _from source to the view's internal data
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
// Check if we were passed a source name rather than a
// reference to a source object
if (typeof(source) === 'string') {
// We were passed a name, assume it is a collection and
// get the reference to the collection of that name
source = this._db.collection(source);
}
// Check if we were passed a reference to a view rather than
// a collection. Views need to be handled slightly differently
// since their data is stored in an internal data collection
// rather than actually being a direct data source themselves.
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source._data;
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
// Assign the new data source as the view's _from
this._from = source;
// Hook the new data source's drop event so we can unhook
// it as a data source if it gets dropped. This is important
// so that we don't run into problems using a dropped source
// for active data.
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's _from source and determines how they should be interpreted by
// this view. See the _handleChainIO() method which does all the chain packet
// processing for the view.
this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); });
// Set the view's internal data primary key to the same as the
// current active _from data source
this._data.primaryKey(source.primaryKey());
// Do the initial data lookup and populate the view's internal data
// since at this point we don't actually have any data in the view
// yet.
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData, {}, callback);
// If we have an active query and that query has an $orderBy clause,
// update our active bucket which allows us to keep track of where
// data should be placed in our internal data array. This is about
// ordering of data and making sure that we maintain an ordered array
// so that if we have data-binding we can place an item in the data-
// bound view at the correct location. Active buckets use quick-sort
// algorithms to quickly determine the position of an item inside an
// existing array based on a sort protocol.
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type);
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData);
// Rebuild active bucket as well
this.rebuildActiveBucket(this._querySettings.options);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Make sure we are working with an array
if (!(chainPacket.data.dataSet instanceof Array)) {
chainPacket.data.dataSet = [chainPacket.data.dataSet];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._data._insertHandle(arr[index], insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._data._data.length;
this._data._insertHandle(chainPacket.data.dataSet, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"');
}
primaryKey = this._data.primaryKey();
// Do the update
updates = this._data._handleUpdate(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._data._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"');
}
this._data.remove(chainPacket.data.query, chainPacket.options);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the dataSet and remove the objects from the ActiveBucket
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
this._activeBucket.remove(arr[index]);
}
}
break;
default:
break;
}
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._data.ensureIndex.apply(this._data, arguments);
};
/**
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._data.on.apply(this._data, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._data.off.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._data.emit.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::deferEmit()
*/
View.prototype.deferEmit = function () {
return this._data.deferEmit.apply(this._data, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
return this._data.distinct(key, query, options);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._data.primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._data) {
this._data.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._data;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
}
});
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
// TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first!
this.rebuildActiveBucket(options.$orderBy);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
return this;
}
return this._querySettings.options;
};
/**
* Clears the existing active bucket and builds a new one based
* on the passed orderBy object (if one is passed).
* @param {Object=} orderBy The orderBy object describing how to
* order any data.
*/
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._data._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._data.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
var self = this,
refreshResults,
joinArr,
i, k;
if (this._from) {
// Clear the private data collection which will propagate to the public data
// collection automatically via the chain reactor node between them
this._data.remove();
// Grab all the data from the underlying data source
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
// Insert the underlying data into the private data collection
this._data.insert(refreshResults);
// Store the current cursor data
this._data._data.$cursor = refreshResults.$cursor;
this._data._data.$cursor = refreshResults.$cursor;
}
if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) {
// Define the change handler method
self.__joinChange = self.__joinChange || function () {
self._joinChange();
};
// Check for existing join collections
if (this._joinCollections && this._joinCollections.length) {
// Loop the join collections and remove change listeners
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange);
}
}
// Now start hooking any new / existing joins
joinArr = this._querySettings.options.$join;
this._joinCollections = [];
// Loop the joined collections and hook change events
for (i = 0; i < joinArr.length; i++) {
for (k in joinArr[i]) {
if (joinArr[i].hasOwnProperty(k)) {
this._joinCollections.push(k);
}
}
}
if (this._joinCollections.length) {
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange);
}
}
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Handles when a change has occurred on a collection that is joined
* by query to this view.
* @param objName
* @param objType
* @private
*/
View.prototype._joinChange = function (objName, objType) {
this.emit('joinChange');
// TODO: This is a really dirty solution because it will require a complete
// TODO: rebuild of the view data. We need to implement an IO handler to
// TODO: selectively update the data of the view based on the joined
// TODO: collection data operation.
// FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call
this.refresh();
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
return this._data.count.apply(this._data, arguments);
};
// Call underlying
View.prototype.subset = function () {
return this._data.subset.apply(this._data, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn"
* and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var currentSettings,
newSettings;
currentSettings = this._data.transform();
this._data.transform(obj);
newSettings = this._data.transform();
// Check if transforms are enabled, a dataIn method is set and these
// settings did not match the previous transform settings
if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) {
// The data in the view is now stale, refresh it
this.refresh();
}
return newSettings;
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return this._data.filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.data = function () {
return this._data;
};
/**
* @see Collection.indexOf
* @returns {*}
*/
View.prototype.indexOf = function () {
return this._data.indexOf.apply(this._data, arguments);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this._data.db(db);
// Apply the same debug settings
this.debug(db.debug());
this._data.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} name The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (name) {
var self = this;
// Handle being passed an instance
if (name instanceof View) {
return name;
}
if (this._view[name]) {
return this._view[name];
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + name);
}
this._view[name] = new View(name).db(this);
self.emit('create', self._view[name], 'view', name);
return this._view[name];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} name The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (name) {
return Boolean(this._view[name]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":3,"./Collection":7,"./CollectionGroup":8,"./Overload":32,"./ReactorIO":38,"./Shared":40}],43:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (typeof arguments[1] === 'function') {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var hasError = false;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
if (hasError) return;
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
hasError = true;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has nonexistent dependency in ' + requires.join(', '));
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback.apply(null, [null].concat(args));
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
while(!q.paused && workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
var has = Object.prototype.hasOwnProperty;
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (has.call(memo, key)) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (has.call(queues, key)) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":95}],44:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],45:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":46}],46:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],47:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
var bitsCombined = bits1 | bits2;
words[nBytes >>> 2] |= (bitsCombined) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":46}],48:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":46}],49:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":46,"./hmac":51,"./sha1":70}],50:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":45,"./core":46}],51:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":46}],52:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":44,"./cipher-core":45,"./core":46,"./enc-base64":47,"./enc-utf16":48,"./evpkdf":49,"./format-hex":50,"./hmac":51,"./lib-typedarrays":53,"./md5":54,"./mode-cfb":55,"./mode-ctr":57,"./mode-ctr-gladman":56,"./mode-ecb":58,"./mode-ofb":59,"./pad-ansix923":60,"./pad-iso10126":61,"./pad-iso97971":62,"./pad-nopadding":63,"./pad-zeropadding":64,"./pbkdf2":65,"./rabbit":67,"./rabbit-legacy":66,"./rc4":68,"./ripemd160":69,"./sha1":70,"./sha224":71,"./sha256":72,"./sha3":73,"./sha384":74,"./sha512":75,"./tripledes":76,"./x64-core":77}],53:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":46}],54:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":46}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":45,"./core":46}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":45,"./core":46}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":45,"./core":46}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":45,"./core":46}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":45,"./core":46}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":45,"./core":46}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":45,"./core":46}],62:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":45,"./core":46}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":45,"./core":46}],64:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":45,"./core":46}],65:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":46,"./hmac":51,"./sha1":70}],66:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],67:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],68:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],69:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":46}],70:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":46}],71:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":46,"./sha256":72}],72:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":46}],73:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":46,"./x64-core":77}],74:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":46,"./sha512":75,"./x64-core":77}],75:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":46,"./x64-core":77}],76:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],77:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":46}],78:[function(_dereq_,module,exports){
(function (process,global){
/*!
localForage -- Offline Storage, Improved
Version 1.4.0
https://mozilla.github.io/localForage
(c) 2013-2015 Mozilla, Apache License 2.0
*/
(function() {
var define, requireModule, _dereq_, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = _dereq_ = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
define("promise/all",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
var isFunction = __dependency1__.isFunction;
/**
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The return promise
is fulfilled with an array that gives all the values in the order they were
passed in the `promises` array argument.
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.resolve(2);
var promise3 = RSVP.resolve(3);
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `RSVP.all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.reject(new Error("2"));
var promise3 = RSVP.reject(new Error("3"));
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@for RSVP
@param {Array} promises
@param {String} label
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
*/
function all(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to all.');
}
return new Promise(function(resolve, reject) {
var results = [], remaining = promises.length,
promise;
if (remaining === 0) {
resolve([]);
}
function resolver(index) {
return function(value) {
resolveAll(index, value);
};
}
function resolveAll(index, value) {
results[index] = value;
if (--remaining === 0) {
resolve(results);
}
}
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && isFunction(promise.then)) {
promise.then(resolver(i), reject);
} else {
resolveAll(i, promise);
}
}
});
}
__exports__.all = all;
});
define("promise/asap",
["exports"],
function(__exports__) {
"use strict";
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this);
// node
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useSetTimeout() {
return function() {
local.setTimeout(flush, 1);
};
}
var queue = [];
function flush() {
for (var i = 0; i < queue.length; i++) {
var tuple = queue[i];
var callback = tuple[0], arg = tuple[1];
callback(arg);
}
queue = [];
}
var scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else {
scheduleFlush = useSetTimeout();
}
function asap(callback, arg) {
var length = queue.push([callback, arg]);
if (length === 1) {
// If length is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
scheduleFlush();
}
}
__exports__.asap = asap;
});
define("promise/config",
["exports"],
function(__exports__) {
"use strict";
var config = {
instrument: false
};
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
__exports__.config = config;
__exports__.configure = configure;
});
define("promise/polyfill",
["./promise","./utils","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/*global self*/
var RSVPPromise = __dependency1__.Promise;
var isFunction = __dependency2__.isFunction;
function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof window !== 'undefined' && window.document) {
local = window;
} else {
local = self;
}
var es6PromiseSupport =
"Promise" in local &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"resolve" in local.Promise &&
"reject" in local.Promise &&
"all" in local.Promise &&
"race" in local.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new local.Promise(function(r) { resolve = r; });
return isFunction(resolve);
}());
if (!es6PromiseSupport) {
local.Promise = RSVPPromise;
}
}
__exports__.polyfill = polyfill;
});
define("promise/promise",
["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) {
"use strict";
var config = __dependency1__.config;
var configure = __dependency1__.configure;
var objectOrFunction = __dependency2__.objectOrFunction;
var isFunction = __dependency2__.isFunction;
var now = __dependency2__.now;
var all = __dependency3__.all;
var race = __dependency4__.race;
var staticResolve = __dependency5__.resolve;
var staticReject = __dependency6__.reject;
var asap = __dependency7__.asap;
var counter = 0;
config.async = asap; // default async is asap;
function Promise(resolver) {
if (!isFunction(resolver)) {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
if (!(this instanceof Promise)) {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
this._subscribers = [];
invokeResolver(resolver, this);
}
function invokeResolver(resolver, promise) {
function resolvePromise(value) {
resolve(promise, value);
}
function rejectPromise(reason) {
reject(promise, reason);
}
try {
resolver(resolvePromise, rejectPromise);
} catch(e) {
rejectPromise(e);
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
try {
value = callback(detail);
succeeded = true;
} catch(e) {
failed = true;
error = e;
}
} else {
value = detail;
succeeded = true;
}
if (handleThenable(promise, value)) {
return;
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
resolve(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
var PENDING = void 0;
var SEALED = 0;
var FULFILLED = 1;
var REJECTED = 2;
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
}
function publish(promise, settled) {
var child, callback, subscribers = promise._subscribers, detail = promise._detail;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
invokeCallback(settled, child, callback, detail);
}
promise._subscribers = null;
}
Promise.prototype = {
constructor: Promise,
_state: undefined,
_detail: undefined,
_subscribers: undefined,
then: function(onFulfillment, onRejection) {
var promise = this;
var thenPromise = new this.constructor(function() {});
if (this._state) {
var callbacks = arguments;
config.async(function invokePromiseCallback() {
invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
});
} else {
subscribe(this, thenPromise, onFulfillment, onRejection);
}
return thenPromise;
},
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
Promise.all = all;
Promise.race = race;
Promise.resolve = staticResolve;
Promise.reject = staticReject;
function handleThenable(promise, value) {
var then = null,
resolved;
try {
if (promise === value) {
throw new TypeError("A promises callback cannot return that same promise.");
}
if (objectOrFunction(value)) {
then = value.then;
if (isFunction(then)) {
then.call(value, function(val) {
if (resolved) { return true; }
resolved = true;
if (value !== val) {
resolve(promise, val);
} else {
fulfill(promise, val);
}
}, function(val) {
if (resolved) { return true; }
resolved = true;
reject(promise, val);
});
return true;
}
}
} catch (error) {
if (resolved) { return true; }
reject(promise, error);
return true;
}
return false;
}
function resolve(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (!handleThenable(promise, value)) {
fulfill(promise, value);
}
}
function fulfill(promise, value) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = value;
config.async(publishFulfillment, promise);
}
function reject(promise, reason) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = reason;
config.async(publishRejection, promise);
}
function publishFulfillment(promise) {
publish(promise, promise._state = FULFILLED);
}
function publishRejection(promise) {
publish(promise, promise._state = REJECTED);
}
__exports__.Promise = Promise;
});
define("promise/race",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
/**
`RSVP.race` allows you to watch a series of promises and act as soon as the
first promise given to the `promises` argument fulfills or rejects.
Example:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 2");
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// result === "promise 2" because it was resolved before promise1
// was resolved.
});
```
`RSVP.race` is deterministic in that only the state of the first completed
promise matters. For example, even if other promises given to the `promises`
array argument are resolved, but the first completed promise has become
rejected before the other promises became fulfilled, the returned promise
will become rejected:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error("promise 2"));
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// Code here never runs because there are rejected promises!
}, function(reason){
// reason.message === "promise2" because promise 2 became rejected before
// promise 1 became fulfilled
});
```
@method race
@for RSVP
@param {Array} promises array of promises to observe
@param {String} label optional string for describing the promise returned.
Useful for tooling.
@return {Promise} a promise that becomes fulfilled with the value the first
completed promises is resolved with if the first completed promise was
fulfilled, or rejected with the reason that the first completed promise
was rejected with.
*/
function race(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to race.');
}
return new Promise(function(resolve, reject) {
var results = [], promise;
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && typeof promise.then === 'function') {
promise.then(resolve, reject);
} else {
resolve(promise);
}
}
});
}
__exports__.race = race;
});
define("promise/reject",
["exports"],
function(__exports__) {
"use strict";
/**
`RSVP.reject` returns a promise that will become rejected with the passed
`reason`. `RSVP.reject` is essentially shorthand for the following:
```javascript
var promise = new RSVP.Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
var promise = RSVP.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@for RSVP
@param {Any} reason value that the returned promise will be rejected with.
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become rejected with the given
`reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Promise = this;
return new Promise(function (resolve, reject) {
reject(reason);
});
}
__exports__.reject = reject;
});
define("promise/resolve",
["exports"],
function(__exports__) {
"use strict";
function resolve(value) {
/*jshint validthis:true */
if (value && typeof value === 'object' && value.constructor === this) {
return value;
}
var Promise = this;
return new Promise(function(resolve) {
resolve(value);
});
}
__exports__.resolve = resolve;
});
define("promise/utils",
["exports"],
function(__exports__) {
"use strict";
function objectOrFunction(x) {
return isFunction(x) || (typeof x === "object" && x !== null);
}
function isFunction(x) {
return typeof x === "function";
}
function isArray(x) {
return Object.prototype.toString.call(x) === "[object Array]";
}
// Date.now is not available in browsers < IE9
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
var now = Date.now || function() { return new Date().getTime(); };
__exports__.objectOrFunction = objectOrFunction;
__exports__.isFunction = isFunction;
__exports__.isArray = isArray;
__exports__.now = now;
});
requireModule('promise/polyfill').polyfill();
}());(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["localforage"] = factory();
else
root["localforage"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var localForage = (function (globalObject) {
'use strict';
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'];
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
var driverSupport = (function (self) {
var result = {};
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
result[DriverType.INDEXEDDB] = !!(function () {
try {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB;
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) {
return false;
}
return indexedDB && typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.WEBSQL] = !!(function () {
try {
return self.openDatabase;
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function () {
try {
return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem;
} catch (e) {
return false;
}
})();
return result;
})(globalObject);
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var LocalForage = (function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
this.INDEXEDDB = DriverType.INDEXEDDB;
this.LOCALSTORAGE = DriverType.LOCALSTORAGE;
this.WEBSQL = DriverType.WEBSQL;
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver);
}
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof options === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
var namingError = new Error('Custom driver name already in use: ' + driverObject._driver);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function (supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
promise.then(callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var self = this;
var getDriverPromise = (function () {
if (isLibraryDriver(driverName)) {
switch (driverName) {
case self.INDEXEDDB:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(1));
});
case self.LOCALSTORAGE:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(2));
});
case self.WEBSQL:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(4));
});
}
} else if (CustomDrivers[driverName]) {
return Promise.resolve(CustomDrivers[driverName]);
}
return Promise.reject(new Error('Driver not found.'));
})();
getDriverPromise.then(callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
});
if (callback && typeof callback === 'function') {
serializerPromise.then(function (result) {
callback(result);
});
}
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
promise.then(callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
})['catch'](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () {
return Promise.resolve();
}) : Promise.resolve();
this._driverSet = oldDriverSetDone.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})['catch'](function () {
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
});
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
})();
return new LocalForage();
})(typeof window !== 'undefined' ? window : self);
exports['default'] = localForage;
module.exports = exports['default'];
/***/ },
/* 1 */
/***/ function(module, exports) {
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
'use strict';
exports.__esModule = true;
var asyncStorage = (function (globalObject) {
'use strict';
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || globalObject.indexedDB || globalObject.webkitIndexedDB || globalObject.mozIndexedDB || globalObject.OIndexedDB || globalObject.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
var dbContexts;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({ status: xhr.status, response: xhr.response });
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function (resolve, reject) {
var blob = _createBlob([''], { type: 'image/png' });
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function () {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function (e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function (res) {
resolve(!!(res && res.type === 'image/png'));
}, function () {
resolve(false);
}).then(function () {
URL.revokeObjectURL(url);
});
};
};
txn.onerror = txn.onabort = reject;
})['catch'](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type });
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function () {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) {
return dbContext.dbReady;
}
});
promise.then(callback, callback);
return promise;
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Create a deferred object representing the current database operation.
var deferredOperation = {};
deferredOperation.promise = new Promise(function (resolve) {
deferredOperation.resolve = resolve;
});
// Enqueue the deferred operation.
dbContext.deferredOperations.push(deferredOperation);
// Chain its promise to the database readiness.
if (!dbContext.dbReady) {
dbContext.dbReady = deferredOperation.promise;
} else {
dbContext.dbReady = dbContext.dbReady.then(function () {
return deferredOperation.promise;
});
}
}
function _advanceReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Resolve its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.resolve();
}
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Initialize a singleton container for all running localForages.
if (!dbContexts) {
dbContexts = {};
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null,
// Database readiness (promise).
dbReady: null,
// Deferred operations on the database.
deferredOperations: []
};
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(self);
// Replace the default `ready()` function with the specialized one.
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
// Create an array of initialization states of the related localForages.
var initPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== self) {
// Don't wait for itself...
initPromises.push(forage._initReady()['catch'](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise.all(initPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k = 0; k < forages.length; k++) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise(function (resolve, reject) {
if (dbInfo.db) {
if (upgradeNeeded) {
_deferReadiness(dbInfo);
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = indexedDB.open.apply(indexedDB, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function () {
reject(openreq.error);
};
openreq.onsuccess = function () {
resolve(openreq.result);
_advanceReadiness(dbInfo);
};
});
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void 0) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
if (value instanceof Blob) {
return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
if (blobSupport) {
return value;
}
return _encodeBlob(value);
});
}
return value;
}).then(function (value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
var req = store.put(value, key);
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
return asyncStorage;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = asyncStorage;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
'use strict';
exports.__esModule = true;
var localStorageWrapper = (function (globalObject) {
'use strict';
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!globalObject.localStorage || !('setItem' in globalObject.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = globalObject.localStorage;
} catch (e) {
return;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
if (dbInfo.storeName !== self._defaultConfig.storeName) {
dbInfo.keyPrefix += dbInfo.storeName + '/';
}
self._dbInfo = dbInfo;
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
return localStorageWrapper;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = localStorageWrapper;
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var localforageSerializer = (function (globalObject) {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
return localforageSerializer;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = localforageSerializer;
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
'use strict';
exports.__esModule = true;
var webSQLStorage = (function (globalObject) {
'use strict';
var openDatabase = globalObject.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return reject(e);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
});
});
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
return webSQLStorage;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = webSQLStorage;
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":95}],79:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":80,"./lib/inflate":81,"./lib/utils/common":82,"./lib/zlib/constants":85}],80:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var ZStream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
function Deflate(options) {
if (!(this instanceof Deflate)) return new Deflate(options);
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new ZStream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
}
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function (data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function (chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function (status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate algorithm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":82,"./utils/strings":83,"./zlib/deflate":87,"./zlib/messages":92,"./zlib/zstream":94}],81:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var ZStream = _dereq_('./zlib/zstream');
var GZheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
function Inflate(options) {
if (!(this instanceof Inflate)) return new Inflate(options);
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new ZStream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new GZheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
}
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function (data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function (chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function (status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":82,"./utils/strings":83,"./zlib/constants":85,"./zlib/gzheader":88,"./zlib/inflate":90,"./zlib/messages":92,"./zlib/zstream":94}],82:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i = 0; i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function (chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i = 0, l = chunks.length; i < l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i = 0, l = chunks.length; i < l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i = 0; i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function (chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],83:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q = 0; q < 256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i = 0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function (buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function (str) {
var buf = new utils.Buf8(str.length);
for (var i = 0, len = buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len * 2);
for (out = 0, i = 0; i < len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function (buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max - 1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":82}],84:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],85:[function(_dereq_,module,exports){
'use strict';
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],86:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n = 0; n < 256; n++) {
c = n;
for (var k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc ^= -1;
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],87:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2 * L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only(s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH - 1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH - 1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length - 1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH - 1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
function Config(good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
}
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS + 1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":82,"./adler32":84,"./crc32":86,"./messages":92,"./trees":93}],88:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],89:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],90:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function zswap32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window, src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window, src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = zswap32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = { bits: state.lenbits };
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = { bits: state.lenbits };
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = { bits: state.distbits };
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
if ((state.flags ? hold : zswap32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":82,"./adler32":84,"./crc32":86,"./inffast":89,"./inftrees":91}],91:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i = 0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":82}],92:[function(_dereq_,module,exports){
'use strict';
module.exports = {
2: 'need dictionary', /* Z_NEED_DICT 2 */
1: 'stream end', /* Z_STREAM_END 1 */
0: '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],93:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2 * L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
/* eslint-disable comma-spacing,array-bracket-spacing */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* eslint-enable comma-spacing,array-bracket-spacing */
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES + 2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
}
var static_l_desc;
var static_d_desc;
var static_bl_desc;
function TreeDesc(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
}
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short(s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n * 2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n - base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length - 1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m * 2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
tree[m * 2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n * 2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS + 1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES - 1; code++) {
base_length[code] = length;
for (n = 0; n < (1 << extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length - 1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1 << extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n * 2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n * 2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n * 2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n * 2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES + 1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n * 2 + 1]/*.Len*/ = 5;
static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n * 2;
var _m2 = m * 2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code + LITERALS + 1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n * 2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node * 2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count - 3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count - 3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count - 11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes - 1, 5);
send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES << 1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len + 3 + 7) >>> 3;
static_lenb = (s.static_len + 3 + 7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc * 2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize - 1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":82}],94:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}],95:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}]},{},[1]);
|
webpack/scenes/ModuleStreams/Details/Profiles/TableSchema.js | adamruzicka/katello | import React from 'react';
import { translate as __ } from 'foremanReact/common/I18n';
import {
headerFormatter,
cellFormatter,
} from '../../../../move_to_foreman/components/common/table';
import ProfileRpmsCellFormatter from './ProfileRpmsCellFormatter';
const TableSchema = [
{
property: 'name',
header: {
label: __('Name'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
},
{
property: 'rpms',
header: {
label: __('RPMs'),
formatters: [headerFormatter],
},
cell: {
formatters: [
(value, { rowData }) => (
<ProfileRpmsCellFormatter rpms={rowData.rpms} />
),
],
},
},
];
export default TableSchema;
|
src/svg-icons/places/rv-hookup.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesRvHookup = (props) => (
<SvgIcon {...props}>
<path d="M20 17v-6c0-1.1-.9-2-2-2H7V7l-3 3 3 3v-2h4v3H4v3c0 1.1.9 2 2 2h2c0 1.66 1.34 3 3 3s3-1.34 3-3h8v-2h-2zm-9 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm7-6h-4v-3h4v3zM17 2v2H9v2h8v2l3-3z"/>
</SvgIcon>
);
PlacesRvHookup = pure(PlacesRvHookup);
PlacesRvHookup.displayName = 'PlacesRvHookup';
PlacesRvHookup.muiName = 'SvgIcon';
export default PlacesRvHookup;
|
ajax/libs/foundation/4.2.3/js/vendor/jquery.min.js | billpull/cdnjs | !function(a,b){function J(a){var b=a.length,c=u.type(a);return u.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||"function"!==c&&(0===b||"number"==typeof b&&b>0&&b-1 in a)}function L(a){var b=K[a]={};return u.each(a.match(w)||[],function(a,c){b[c]=!0}),b}function O(a,c,d,e){if(u.acceptData(a)){var f,g,h=u.expando,i=a.nodeType,j=i?u.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||d!==b||"string"!=typeof c)return k||(k=i?a[h]=l.pop()||u.guid++:h),j[k]||(j[k]=i?{}:{toJSON:u.noop}),("object"==typeof c||"function"==typeof c)&&(e?j[k]=u.extend(j[k],c):j[k].data=u.extend(j[k].data,c)),g=j[k],e||(g.data||(g.data={}),g=g.data),d!==b&&(g[u.camelCase(c)]=d),"string"==typeof c?(f=g[c],null==f&&(f=g[u.camelCase(c)])):f=g,f}}function P(a,b,c){if(u.acceptData(a)){var d,e,f=a.nodeType,g=f?u.cache:a,h=f?a[u.expando]:u.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){u.isArray(b)?b=b.concat(u.map(b,u.camelCase)):b in d?b=[b]:(b=u.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;for(;e--;)delete d[b[e]];if(c?!R(d):!u.isEmptyObject(d))return}(c||(delete g[h].data,R(g[h])))&&(f?u.cleanData([a],!0):u.support.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}function Q(a,c,d){if(d===b&&1===a.nodeType){var e="data-"+c.replace(N,"-$1").toLowerCase();if(d=a.getAttribute(e),"string"==typeof d){try{d="true"===d?!0:"false"===d?!1:"null"===d?null:+d+""===d?+d:M.test(d)?u.parseJSON(d):d}catch(f){}u.data(a,c,d)}else d=b}return d}function R(a){var b;for(b in a)if(("data"!==b||!u.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function eb(){return!0}function fb(){return!1}function gb(){try{return g.activeElement}catch(a){}}function lb(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}function mb(a,b,c){if(u.isFunction(b))return u.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return u.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(hb.test(b))return u.filter(b,a,c);b=u.filter(b,a)}return u.grep(a,function(a){return u.inArray(a,b)>=0!==c})}function nb(a){var b=ob.split("|"),c=a.createDocumentFragment();if(c.createElement)for(;b.length;)c.createElement(b.pop());return c}function Fb(a,b){return u.nodeName(a,"table")&&u.nodeName(1===b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Gb(a){return a.type=(null!==u.find.attr(a,"type"))+"/"+a.type,a}function Hb(a){var b=Ab.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ib(a,b){for(var c,d=0;null!=(c=a[d]);d++)u._data(c,"globalEval",!b||u._data(b[d],"globalEval"))}function Jb(a,b){if(1===b.nodeType&&u.hasData(a)){var c,d,e,f=u._data(a),g=u._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)u.event.add(b,c,h[c][d])}g.data&&(g.data=u.extend({},g.data))}}function Kb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!u.support.noCloneEvent&&b[u.expando]){e=u._data(b);for(d in e.events)u.removeEvent(b,d,e.handle);b.removeAttribute(u.expando)}"script"===c&&b.text!==a.text?(Gb(b).text=a.text,Hb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),u.support.html5Clone&&a.innerHTML&&!u.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&xb.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}function Lb(a,c){var d,f,g=0,h=typeof a.getElementsByTagName!==e?a.getElementsByTagName(c||"*"):typeof a.querySelectorAll!==e?a.querySelectorAll(c||"*"):b;if(!h)for(h=[],d=a.childNodes||a;null!=(f=d[g]);g++)!c||u.nodeName(f,c)?h.push(f):u.merge(h,Lb(f,c));return c===b||c&&u.nodeName(a,c)?u.merge([a],h):h}function Mb(a){xb.test(a.type)&&(a.defaultChecked=a.checked)}function bc(a,b){if(b in a)return b;for(var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=ac.length;e--;)if(b=ac[e]+c,b in a)return b;return d}function cc(a,b){return a=b||a,"none"===u.css(a,"display")||!u.contains(a.ownerDocument,a)}function dc(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=u._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&cc(d)&&(f[g]=u._data(d,"olddisplay",hc(d.nodeName)))):f[g]||(e=cc(d),(c&&"none"!==c||!e)&&u._data(d,"olddisplay",e?c:u.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function ec(a,b,c){var d=Vb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function fc(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=u.css(a,c+_b[f],!0,e)),d?("content"===c&&(g-=u.css(a,"padding"+_b[f],!0,e)),"margin"!==c&&(g-=u.css(a,"border"+_b[f]+"Width",!0,e))):(g+=u.css(a,"padding"+_b[f],!0,e),"padding"!==c&&(g+=u.css(a,"border"+_b[f]+"Width",!0,e)));return g}function gc(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ob(a),g=u.support.boxSizing&&"border-box"===u.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Pb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Wb.test(e))return e;d=g&&(u.support.boxSizingReliable||e===a.style[b]),e=parseFloat(e)||0}return e+fc(a,b,c||(g?"border":"content"),d,f)+"px"}function hc(a){var b=g,c=Yb[a];return c||(c=ic(a,b),"none"!==c&&c||(Nb=(Nb||u("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(b.documentElement),b=(Nb[0].contentWindow||Nb[0].contentDocument).document,b.write("<!doctype html><html><body>"),b.close(),c=ic(a,b),Nb.detach()),Yb[a]=c),c}function ic(a,b){var c=u(b.createElement(a)).appendTo(b.body),d=u.css(c[0],"display");return c.remove(),d}function oc(a,b,c,d){var e;if(u.isArray(b))u.each(b,function(b,e){c||kc.test(a)?d(a,e):oc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==u.type(b))d(a,b);else for(e in b)oc(a+"["+e+"]",b[e],c,d)}function Fc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(w)||[];if(u.isFunction(c))for(;d=f[e++];)"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Gc(a,b,c,d){function g(h){var i;return e[h]=!0,u.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}var e={},f=a===Cc;return g(b.dataTypes[0])||!e["*"]&&g("*")}function Hc(a,c){var d,e,f=u.ajaxSettings.flatOptions||{};for(e in c)c[e]!==b&&((f[e]?a:d||(d={}))[e]=c[e]);return d&&u.extend(!0,a,d),a}function Ic(a,c,d){for(var e,f,g,h,i=a.contents,j=a.dataTypes;"*"===j[0];)j.shift(),f===b&&(f=a.mimeType||c.getResponseHeader("Content-Type"));if(f)for(h in i)if(i[h]&&i[h].test(f)){j.unshift(h);break}if(j[0]in d)g=j[0];else{for(h in d){if(!j[0]||a.converters[h+" "+j[0]]){g=h;break}e||(e=h)}g=g||e}return g?(g!==j[0]&&j.unshift(g),d[g]):void 0}function Jc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];for(f=k.shift();f;)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}function Qc(){try{return new a.XMLHttpRequest}catch(b){}}function Rc(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function Zc(){return setTimeout(function(){Sc=b}),Sc=u.now()}function $c(a,b,c){for(var d,e=(Yc[b]||[]).concat(Yc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function _c(a,b,c){var d,e,f=0,g=Xc.length,h=u.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Sc||Zc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:u.extend({},b),opts:u.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Sc||Zc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=u.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(ad(k,j.opts.specialEasing);g>f;f++)if(d=Xc[f].call(j,a,k,j.opts))return d;return u.map(k,$c,j),u.isFunction(j.opts.start)&&j.opts.start.call(a,j),u.fx.timer(u.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function ad(a,b){var c,d,e,f,g;for(c in a)if(d=u.camelCase(c),e=b[d],f=a[c],u.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=u.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function bd(a,b,c){var d,e,f,g,h,i,j=this,k={},l=a.style,m=a.nodeType&&cc(a),n=u._data(a,"fxshow");c.queue||(h=u._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,j.always(function(){j.always(function(){h.unqueued--,u.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[l.overflow,l.overflowX,l.overflowY],"inline"===u.css(a,"display")&&"none"===u.css(a,"float")&&(u.support.inlineBlockNeedsLayout&&"inline"!==hc(a.nodeName)?l.zoom=1:l.display="inline-block")),c.overflow&&(l.overflow="hidden",u.support.shrinkWrapBlocks||j.always(function(){l.overflow=c.overflow[0],l.overflowX=c.overflow[1],l.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Uc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(m?"hide":"show"))continue;k[d]=n&&n[d]||u.style(a,d)}if(!u.isEmptyObject(k)){n?"hidden"in n&&(m=n.hidden):n=u._data(a,"fxshow",{}),f&&(n.hidden=!m),m?u(a).show():j.done(function(){u(a).hide()}),j.done(function(){var b;u._removeData(a,"fxshow");for(b in k)u.style(a,b,k[b])});for(d in k)g=$c(m?n[d]:0,d,j),d in n||(n[d]=g.start,m&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function cd(a,b,c,d,e){return new cd.prototype.init(a,b,c,d,e)}function dd(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=_b[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ed(a){return u.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}var c,d,e=typeof b,f=a.location,g=a.document,h=g.documentElement,i=a.jQuery,j=a.$,k={},l=[],m="1.10.1",n=l.concat,o=l.push,p=l.slice,q=l.indexOf,r=k.toString,s=k.hasOwnProperty,t=m.trim,u=function(a,b){return new u.fn.init(a,b,d)},v=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,x=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,y=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,z=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,A=/^[\],:{}\s]*$/,B=/(?:^|:|,)(?:\s*\[)+/g,C=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,D=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,E=/^-ms-/,F=/-([\da-z])/gi,G=function(a,b){return b.toUpperCase()},H=function(a){(g.addEventListener||"load"===a.type||"complete"===g.readyState)&&(I(),u.ready())},I=function(){g.addEventListener?(g.removeEventListener("DOMContentLoaded",H,!1),a.removeEventListener("load",H,!1)):(g.detachEvent("onreadystatechange",H),a.detachEvent("onload",H))};u.fn=u.prototype={jquery:m,constructor:u,init:function(a,c,d){var e,f;if(!a)return this;if("string"==typeof a){if(e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:y.exec(a),!e||!e[1]&&c)return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a);if(e[1]){if(c=c instanceof u?c[0]:c,u.merge(this,u.parseHTML(e[1],c&&c.nodeType?c.ownerDocument||c:g,!0)),z.test(e[1])&&u.isPlainObject(c))for(e in c)u.isFunction(this[e])?this[e](c[e]):this.attr(e,c[e]);return this}if(f=g.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return d.find(a);this.length=1,this[0]=f}return this.context=g,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):u.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),u.makeArray(a,this))},selector:"",length:0,toArray:function(){return p.call(this)},get:function(a){return null==a?this.toArray():0>a?this[this.length+a]:this[a]},pushStack:function(a){var b=u.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return u.each(this,a,b)},ready:function(a){return u.ready.promise().done(a),this},slice:function(){return this.pushStack(p.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},map:function(a){return this.pushStack(u.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:o,sort:[].sort,splice:[].splice},u.fn.init.prototype=u.fn,u.extend=u.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;for("boolean"==typeof h&&(k=h,h=arguments[1]||{},i=2),"object"==typeof h||u.isFunction(h)||(h={}),j===i&&(h=this,--i);j>i;i++)if(null!=(f=arguments[i]))for(e in f)a=h[e],d=f[e],h!==d&&(k&&d&&(u.isPlainObject(d)||(c=u.isArray(d)))?(c?(c=!1,g=a&&u.isArray(a)?a:[]):g=a&&u.isPlainObject(a)?a:{},h[e]=u.extend(k,g,d)):d!==b&&(h[e]=d));return h},u.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),noConflict:function(b){return a.$===u&&(a.$=j),b&&a.jQuery===u&&(a.jQuery=i),u},isReady:!1,readyWait:1,holdReady:function(a){a?u.readyWait++:u.ready(!0)},ready:function(a){if(a===!0?!--u.readyWait:!u.isReady){if(!g.body)return setTimeout(u.ready);u.isReady=!0,a!==!0&&--u.readyWait>0||(c.resolveWith(g,[u]),u.fn.trigger&&u(g).trigger("ready").off("ready"))}},isFunction:function(a){return"function"===u.type(a)},isArray:Array.isArray||function(a){return"array"===u.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return null==a?String(a):"object"==typeof a||"function"==typeof a?k[r.call(a)]||"object":typeof a},isPlainObject:function(a){var c;if(!a||"object"!==u.type(a)||a.nodeType||u.isWindow(a))return!1;try{if(a.constructor&&!s.call(a,"constructor")&&!s.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(d){return!1}if(u.support.ownLast)for(c in a)return s.call(a,c);for(c in a);return c===b||s.call(a,c)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||g;var d=z.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=u.buildFragment([a],b,e),e&&u(e).remove(),u.merge([],d.childNodes))},parseJSON:function(b){return a.JSON&&a.JSON.parse?a.JSON.parse(b):null===b?b:"string"==typeof b&&(b=u.trim(b),b&&A.test(b.replace(C,"@").replace(D,"]").replace(B,"")))?new Function("return "+b)():(u.error("Invalid JSON: "+b),void 0)},parseXML:function(c){var d,e;if(!c||"string"!=typeof c)return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return d&&d.documentElement&&!d.getElementsByTagName("parsererror").length||u.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&u.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(E,"ms-").replace(F,G)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=J(a);if(c){if(g)for(;f>e&&(d=b.apply(a[e],c),d!==!1);e++);else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g)for(;f>e&&(d=b.call(a[e],e,a[e]),d!==!1);e++);else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:t&&!t.call("\ufeff\xa0")?function(a){return null==a?"":t.call(a)}:function(a){return null==a?"":(a+"").replace(x,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(J(Object(a))?u.merge(c,"string"==typeof a?[a]:a):o.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(q)return q.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if("number"==typeof d)for(;d>f;f++)a[e++]=c[f];else for(;c[f]!==b;)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;for(c=!!c;g>f;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,b,c){var d,e=0,f=a.length,g=J(a),h=[];if(g)for(;f>e;e++)d=b(a[e],e,c),null!=d&&(h[h.length]=d);else for(e in a)d=b(a[e],e,c),null!=d&&(h[h.length]=d);return n.apply([],h)},guid:1,proxy:function(a,c){var d,e,f;return"string"==typeof c&&(f=a[c],c=a,a=f),u.isFunction(a)?(d=p.call(arguments,2),e=function(){return a.apply(c||this,d.concat(p.call(arguments)))},e.guid=a.guid=a.guid||u.guid++,e):b},access:function(a,c,d,e,f,g,h){var i=0,j=a.length,k=null==d;if("object"===u.type(d)){f=!0;for(i in d)u.access(a,c,i,d[i],!0,g,h)}else if(e!==b&&(f=!0,u.isFunction(e)||(h=!0),k&&(h?(c.call(a,e),c=null):(k=c,c=function(a,b,c){return k.call(u(a),c)})),c))for(;j>i;i++)c(a[i],d,h?e:e.call(a[i],i,c(a[i],d)));return f?a:k?c.call(a):j?c(a[0],d):g},now:function(){return(new Date).getTime()},swap:function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e}}),u.ready.promise=function(b){if(!c)if(c=u.Deferred(),"complete"===g.readyState)setTimeout(u.ready);else if(g.addEventListener)g.addEventListener("DOMContentLoaded",H,!1),a.addEventListener("load",H,!1);else{g.attachEvent("onreadystatechange",H),a.attachEvent("onload",H);var d=!1;try{d=null==a.frameElement&&g.documentElement}catch(e){}d&&d.doScroll&&function f(){if(!u.isReady){try{d.doScroll("left")}catch(a){return setTimeout(f,50)}I(),u.ready()}}()}return c.promise(b)},u.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){k["[object "+b+"]"]=b.toLowerCase()}),d=u(g),function(a,b){function gb(a,b,c,e){var f,g,h,i,j,k,n,q,r,u;if((b?b.ownerDocument||b:v)!==m&&l(b),b=b||m,c=c||[],!a||"string"!=typeof a)return c;if(1!==(i=b.nodeType)&&9!==i)return[];if(o&&!e){if(f=_.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return c;if(g.id===h)return c.push(g),c}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&s(b,g)&&g.id===h)return c.push(g),c}else{if(f[2])return J.apply(c,b.getElementsByTagName(a)),c;if((h=f[3])&&d.getElementsByClassName&&b.getElementsByClassName)return J.apply(c,b.getElementsByClassName(h)),c}if(d.qsa&&(!p||!p.test(a))){if(q=n=t,r=b,u=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){for(k=tb(a),(n=b.getAttribute("id"))?q=n.replace(cb,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=k.length;j--;)k[j]=q+ub(k[j]);r=V.test(a)&&b.parentNode||b,u=k.join(",")}if(u)try{return J.apply(c,r.querySelectorAll(u)),c}catch(w){}finally{n||b.removeAttribute("id")}}}return Cb(a.replace(S,"$1"),b,c,e)}function hb(a){return $.test(a+"")}function ib(){function b(c,d){return a.push(c+=" ")>f.cacheLength&&delete b[a.shift()],b[c]=d}var a=[];return b}function jb(a){return a[t]=!0,a}function kb(a){var b=m.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function lb(a,b,c){a=a.split("|");for(var d,e=a.length,g=c?null:b;e--;)(d=f.attrHandle[a[e]])&&d!==b||(f.attrHandle[a[e]]=g)}function mb(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:a[b]===!0?b.toLowerCase():null}function nb(a,b){return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}function ob(a){return"input"===a.nodeName.toLowerCase()?a.defaultValue:void 0}function pb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||E)-(~a.sourceIndex||E);if(d)return d;if(c)for(;c=c.nextSibling;)if(c===b)return-1;return a?1:-1}function qb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function rb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function sb(a){return jb(function(b){return b=+b,jb(function(c,d){for(var e,f=a([],c.length,b),g=f.length;g--;)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function tb(a,b){var c,d,e,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);for(h=a,i=[],j=f.preFilter;h;){(!c||(d=T.exec(h)))&&(d&&(h=h.slice(d[0].length)||h),i.push(e=[])),c=!1,(d=U.exec(h))&&(c=d.shift(),e.push({value:c,type:d[0].replace(S," ")}),h=h.slice(c.length));for(g in f.filter)!(d=Z[g].exec(h))||j[g]&&!(d=j[g](d))||(c=d.shift(),e.push({value:c,type:g,matches:d}),h=h.slice(c.length));if(!c)break}return b?h.length:h?gb.error(a):z(a,i).slice(0)}function ub(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function vb(a,b,c){var d=b.dir,f=c&&"parentNode"===d,g=x++;return b.first?function(b,c,e){for(;b=b[d];)if(1===b.nodeType||f)return a(b,c,e)}:function(b,c,h){var i,j,k,l=w+" "+g;if(h){for(;b=b[d];)if((1===b.nodeType||f)&&a(b,c,h))return!0}else for(;b=b[d];)if(1===b.nodeType||f)if(k=b[t]||(b[t]={}),(j=k[d])&&j[0]===l){if((i=j[1])===!0||i===e)return i===!0}else if(j=k[d]=[l],j[1]=a(b,c,h)||e,j[1]===!0)return!0}}function wb(a){return a.length>1?function(b,c,d){for(var e=a.length;e--;)if(!a[e](b,c,d))return!1;return!0}:a[0]}function xb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function yb(a,b,c,d,e,f){return d&&!d[t]&&(d=yb(d)),e&&!e[t]&&(e=yb(e,f)),jb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||Bb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:xb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d)for(j=xb(r,n),d(j,[],h,i),k=j.length;k--;)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l));if(f){if(e||a){if(e){for(j=[],k=r.length;k--;)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}for(k=r.length;k--;)(l=r[k])&&(j=e?L.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=xb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):J.apply(g,r)})}function zb(a){for(var b,c,d,e=a.length,g=f.relative[a[0].type],h=g||f.relative[" "],i=g?1:0,k=vb(function(a){return a===b},h,!0),l=vb(function(a){return L.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];e>i;i++)if(c=f.relative[a[i].type])m=[vb(wb(m),c)];else{if(c=f.filter[a[i].type].apply(null,a[i].matches),c[t]){for(d=++i;e>d&&!f.relative[a[d].type];d++);return yb(i>1&&wb(m),i>1&&ub(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(S,"$1"),c,d>i&&zb(a.slice(i,d)),e>d&&zb(a=a.slice(d)),e>d&&ub(a))}m.push(c)}return wb(m)}function Ab(a,b){var c=0,d=b.length>0,g=a.length>0,h=function(h,i,k,l,n){var o,p,q,r=[],s=0,t="0",u=h&&[],v=null!=n,x=j,y=h||g&&f.find.TAG("*",n&&i.parentNode||i),z=w+=null==x?1:Math.random()||.1;for(v&&(j=i!==m&&i,e=c);null!=(o=y[t]);t++){if(g&&o){for(p=0;q=a[p++];)if(q(o,i,k)){l.push(o);break}v&&(w=z,e=++c)}d&&((o=!q&&o)&&s--,h&&u.push(o))}if(s+=t,d&&t!==s){for(p=0;q=b[p++];)q(u,r,i,k);if(h){if(s>0)for(;t--;)u[t]||r[t]||(r[t]=H.call(l));r=xb(r)}J.apply(l,r),v&&!h&&r.length>0&&s+b.length>1&&gb.uniqueSort(l)}return v&&(w=z,j=x),u};return d?jb(h):h}function Bb(a,b,c){for(var d=0,e=b.length;e>d;d++)gb(a,b[d],c);return c}function Cb(a,b,c,e){var g,h,j,k,l,m=tb(a);if(!e&&1===m.length){if(h=m[0]=m[0].slice(0),h.length>2&&"ID"===(j=h[0]).type&&d.getById&&9===b.nodeType&&o&&f.relative[h[1].type]){if(b=(f.find.ID(j.matches[0].replace(db,eb),b)||[])[0],!b)return c;a=a.slice(h.shift().value.length)}for(g=Z.needsContext.test(a)?0:h.length;g--&&(j=h[g],!f.relative[k=j.type]);)if((l=f.find[k])&&(e=l(j.matches[0].replace(db,eb),V.test(h[0].type)&&b.parentNode||b))){if(h.splice(g,1),a=e.length&&ub(h),!a)return J.apply(c,e),c;break}}return i(a,m)(e,b,!o,c,V.test(a)),c}function Db(){}var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t="sizzle"+-new Date,v=a.document,w=0,x=0,y=ib(),z=ib(),A=ib(),B=!1,C=function(){return 0},D=typeof b,E=1<<31,F={}.hasOwnProperty,G=[],H=G.pop,I=G.push,J=G.push,K=G.slice,L=G.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},M="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",N="[\\x20\\t\\r\\n\\f]",O="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",P=O.replace("w","w#"),Q="\\["+N+"*("+O+")"+N+"*(?:([*^$|!~]?=)"+N+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+P+")|)|)"+N+"*\\]",R=":("+O+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+Q.replace(3,8)+")*)|.*)\\)|)",S=new RegExp("^"+N+"+|((?:^|[^\\\\])(?:\\\\.)*)"+N+"+$","g"),T=new RegExp("^"+N+"*,"+N+"*"),U=new RegExp("^"+N+"*([>+~]|"+N+")"+N+"*"),V=new RegExp(N+"*[+~]"),W=new RegExp("="+N+"*([^\\]'\"]*)"+N+"*\\]","g"),X=new RegExp(R),Y=new RegExp("^"+P+"$"),Z={ID:new RegExp("^#("+O+")"),CLASS:new RegExp("^\\.("+O+")"),TAG:new RegExp("^("+O.replace("w","w*")+")"),ATTR:new RegExp("^"+Q),PSEUDO:new RegExp("^"+R),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+N+"*(even|odd|(([+-]|)(\\d*)n|)"+N+"*(?:([+-]|)"+N+"*(\\d+)|))"+N+"*\\)|)","i"),bool:new RegExp("^(?:"+M+")$","i"),needsContext:new RegExp("^"+N+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+N+"*((?:-\\d)?\\d*)"+N+"*\\)|)(?=[^-]|$)","i")},$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/^(?:input|select|textarea|button)$/i,bb=/^h\d$/i,cb=/'|\\/g,db=new RegExp("\\\\([\\da-f]{1,6}"+N+"?|("+N+")|.)","ig"),eb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(55296|d>>10,56320|1023&d)};try{J.apply(G=K.call(v.childNodes),v.childNodes),G[v.childNodes.length].nodeType}catch(fb){J={apply:G.length?function(a,b){I.apply(a,K.call(b))}:function(a,b){for(var c=a.length,d=0;a[c++]=b[d++];);a.length=c-1}}}h=gb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},d=gb.support={},l=gb.setDocument=function(a){var b=a?a.ownerDocument||a:v,c=b.parentWindow;return b!==m&&9===b.nodeType&&b.documentElement?(m=b,n=b.documentElement,o=!h(b),c&&c.frameElement&&c.attachEvent("onbeforeunload",function(){l()}),d.attributes=kb(function(a){return a.innerHTML="<a href='#'></a>",lb("type|href|height|width",nb,"#"===a.firstChild.getAttribute("href")),lb(M,mb,null==a.getAttribute("disabled")),a.className="i",!a.getAttribute("className")}),d.input=kb(function(a){return a.innerHTML="<input>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")}),lb("value",ob,d.attributes&&d.input),d.getElementsByTagName=kb(function(a){return a.appendChild(b.createComment("")),!a.getElementsByTagName("*").length}),d.getElementsByClassName=kb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),d.getById=kb(function(a){return n.appendChild(a).id=t,!b.getElementsByName||!b.getElementsByName(t).length}),d.getById?(f.find.ID=function(a,b){if(typeof b.getElementById!==D&&o){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},f.filter.ID=function(a){var b=a.replace(db,eb);return function(a){return a.getAttribute("id")===b}}):(delete f.find.ID,f.filter.ID=function(a){var b=a.replace(db,eb);return function(a){var c=typeof a.getAttributeNode!==D&&a.getAttributeNode("id");return c&&c.value===b}}),f.find.TAG=d.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==D?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){for(;c=f[e++];)1===c.nodeType&&d.push(c);return d}return f},f.find.CLASS=d.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==D&&o?b.getElementsByClassName(a):void 0},q=[],p=[],(d.qsa=hb(b.querySelectorAll))&&(kb(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||p.push("\\["+N+"*(?:value|"+M+")"),a.querySelectorAll(":checked").length||p.push(":checked")}),kb(function(a){var c=b.createElement("input");c.setAttribute("type","hidden"),a.appendChild(c).setAttribute("t",""),a.querySelectorAll("[t^='']").length&&p.push("[*^$]="+N+"*(?:''|\"\")"),a.querySelectorAll(":enabled").length||p.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),p.push(",.*:")})),(d.matchesSelector=hb(r=n.webkitMatchesSelector||n.mozMatchesSelector||n.oMatchesSelector||n.msMatchesSelector))&&kb(function(a){d.disconnectedMatch=r.call(a,"div"),r.call(a,"[s!='']:x"),q.push("!=",R)}),p=p.length&&new RegExp(p.join("|")),q=q.length&&new RegExp(q.join("|")),s=hb(n.contains)||n.compareDocumentPosition?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)for(;b=b.parentNode;)if(b===a)return!0;return!1},d.sortDetached=kb(function(a){return 1&a.compareDocumentPosition(b.createElement("div"))}),C=n.compareDocumentPosition?function(a,c){if(a===c)return B=!0,0;var e=c.compareDocumentPosition&&a.compareDocumentPosition&&a.compareDocumentPosition(c);return e?1&e||!d.sortDetached&&c.compareDocumentPosition(a)===e?a===b||s(v,a)?-1:c===b||s(v,c)?1:k?L.call(k,a)-L.call(k,c):0:4&e?-1:1:a.compareDocumentPosition?-1:1}:function(a,c){var d,e=0,f=a.parentNode,g=c.parentNode,h=[a],i=[c];if(a===c)return B=!0,0;if(!f||!g)return a===b?-1:c===b?1:f?-1:g?1:k?L.call(k,a)-L.call(k,c):0;if(f===g)return pb(a,c);for(d=a;d=d.parentNode;)h.unshift(d);for(d=c;d=d.parentNode;)i.unshift(d);for(;h[e]===i[e];)e++;return e?pb(h[e],i[e]):h[e]===v?-1:i[e]===v?1:0},b):m},gb.matches=function(a,b){return gb(a,null,null,b)},gb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==m&&l(a),b=b.replace(W,"='$1']"),!(!d.matchesSelector||!o||q&&q.test(b)||p&&p.test(b)))try{var c=r.call(a,b);if(c||d.disconnectedMatch||a.document&&11!==a.document.nodeType)return c}catch(e){}return gb(b,m,null,[a]).length>0},gb.contains=function(a,b){return(a.ownerDocument||a)!==m&&l(a),s(a,b)},gb.attr=function(a,c){(a.ownerDocument||a)!==m&&l(a);var e=f.attrHandle[c.toLowerCase()],g=e&&F.call(f.attrHandle,c.toLowerCase())?e(a,c,!o):b;return g===b?d.attributes||!o?a.getAttribute(c):(g=a.getAttributeNode(c))&&g.specified?g.value:null:g},gb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},gb.uniqueSort=function(a){var b,c=[],e=0,f=0;if(B=!d.detectDuplicates,k=!d.sortStable&&a.slice(0),a.sort(C),B){for(;b=a[f++];)b===a[f]&&(e=c.push(f));for(;e--;)a.splice(c[e],1)}return a},g=gb.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(1===e||9===e||11===e){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=g(a)}else if(3===e||4===e)return a.nodeValue}else for(;b=a[d];d++)c+=g(b);return c},f=gb.selectors={cacheLength:50,createPseudo:jb,match:Z,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(db,eb),a[3]=(a[4]||a[5]||"").replace(db,eb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||gb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&gb.error(a[0]),a},PSEUDO:function(a){var c,d=!a[5]&&a[2];return Z.CHILD.test(a[0])?null:(a[3]&&a[4]!==b?a[2]=a[4]:d&&X.test(d)&&(c=tb(d,!0))&&(c=d.indexOf(")",d.length-c)-d.length)&&(a[0]=a[0].slice(0,c),a[2]=d.slice(0,c)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(db,eb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+N+")"+a+"("+N+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==D&&a.getAttribute("class")||"")
})},ATTR:function(a,b,c){return function(d){var e=gb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){for(;p;){for(l=b;l=l[p];)if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){for(k=q[t]||(q[t]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];l=++n&&l&&l[p]||(m=n=0)||o.pop();)if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[t]||(b[t]={}))[a])&&j[0]===w)m=j[1];else for(;(l=++n&&l&&l[p]||(m=n=0)||o.pop())&&((h?l.nodeName.toLowerCase()!==r:1!==l.nodeType)||!++m||(s&&((l[t]||(l[t]={}))[a]=[w,m]),l!==b)););return m-=e,m===d||0===m%d&&m/d>=0}}},PSEUDO:function(a,b){var c,d=f.pseudos[a]||f.setFilters[a.toLowerCase()]||gb.error("unsupported pseudo: "+a);return d[t]?d(b):d.length>1?(c=[a,a,"",b],f.setFilters.hasOwnProperty(a.toLowerCase())?jb(function(a,c){for(var e,f=d(a,b),g=f.length;g--;)e=L.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:jb(function(a){var b=[],c=[],d=i(a.replace(S,"$1"));return d[t]?jb(function(a,b,c,e){for(var f,g=d(a,null,e,[]),h=a.length;h--;)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:jb(function(a){return function(b){return gb(a,b).length>0}}),contains:jb(function(a){return function(b){return(b.textContent||b.innerText||g(b)).indexOf(a)>-1}}),lang:jb(function(a){return Y.test(a||"")||gb.error("unsupported lang: "+a),a=a.replace(db,eb).toLowerCase(),function(b){var c;do if(c=o?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===n},focus:function(a){return a===m.activeElement&&(!m.hasFocus||m.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeName>"@"||3===a.nodeType||4===a.nodeType)return!1;return!0},parent:function(a){return!f.pseudos.empty(a)},header:function(a){return bb.test(a.nodeName)},input:function(a){return ab.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||b.toLowerCase()===a.type)},first:sb(function(){return[0]}),last:sb(function(a,b){return[b-1]}),eq:sb(function(a,b,c){return[0>c?c+b:c]}),even:sb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:sb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:sb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:sb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}};for(c in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})f.pseudos[c]=qb(c);for(c in{submit:!0,reset:!0})f.pseudos[c]=rb(c);i=gb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){for(b||(b=tb(a)),c=b.length;c--;)f=zb(b[c]),f[t]?d.push(f):e.push(f);f=A(a,Ab(e,d))}return f},f.pseudos.nth=f.pseudos.eq,Db.prototype=f.filters=f.pseudos,f.setFilters=new Db,d.sortStable=t.split("").sort(C).join("")===t,l(),[0,0].sort(C),d.detectDuplicates=B,u.find=gb,u.expr=gb.selectors,u.expr[":"]=u.expr.pseudos,u.unique=gb.uniqueSort,u.text=gb.getText,u.isXMLDoc=gb.isXML,u.contains=gb.contains}(a);var K={};u.Callbacks=function(a){a="string"==typeof a?K[a]||L(a):u.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){for(d=a.memory&&b,e=!0,g=h||0,h=0,f=i.length,c=!0;i&&f>g;g++)if(i[g].apply(b[0],b[1])===!1&&a.stopOnFalse){d=!1;break}c=!1,i&&(j?j.length&&k(j.shift()):d?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;!function e(b){u.each(b,function(b,c){var d=u.type(c);"function"===d?a.unique&&l.has(c)||i.push(c):c&&c.length&&"string"!==d&&e(c)})}(arguments),c?f=i.length:d&&(h=b,k(d))}return this},remove:function(){return i&&u.each(arguments,function(a,b){for(var d;(d=u.inArray(b,i,d))>-1;)i.splice(d,1),c&&(f>=d&&f--,g>=d&&g--)}),this},has:function(a){return a?u.inArray(a,i)>-1:!(!i||!i.length)},empty:function(){return i=[],f=0,this},disable:function(){return i=j=d=b,this},disabled:function(){return!i},lock:function(){return j=b,d||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],!i||e&&!j||(c?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!e}};return l},u.extend({Deferred:function(a){var b=[["resolve","done",u.Callbacks("once memory"),"resolved"],["reject","fail",u.Callbacks("once memory"),"rejected"],["notify","progress",u.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return u.Deferred(function(c){u.each(b,function(b,f){var g=f[0],h=u.isFunction(a[b])&&a[b];e[f[1]](function(){var a=h&&h.apply(this,arguments);a&&u.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[g+"With"](this===d?c.promise():this,h?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?u.extend(a,d):d}},e={};return d.pipe=d.then,u.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var h,i,j,b=0,c=p.call(arguments),d=c.length,e=1!==d||a&&u.isFunction(a.promise)?d:0,f=1===e?a:u.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?p.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}};if(d>1)for(h=new Array(d),i=new Array(d),j=new Array(d);d>b;b++)c[b]&&u.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e;return e||f.resolveWith(j,c),f.promise()}}),u.support=function(b){var c,d,f,h,i,j,k,l,m,n=g.createElement("div");if(n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*")||[],d=n.getElementsByTagName("a")[0],!d||!d.style||!c.length)return b;h=g.createElement("select"),j=h.appendChild(g.createElement("option")),f=n.getElementsByTagName("input")[0],d.style.cssText="top:1px;float:left;opacity:.5",b.getSetAttribute="t"!==n.className,b.leadingWhitespace=3===n.firstChild.nodeType,b.tbody=!n.getElementsByTagName("tbody").length,b.htmlSerialize=!!n.getElementsByTagName("link").length,b.style=/top/.test(d.getAttribute("style")),b.hrefNormalized="/a"===d.getAttribute("href"),b.opacity=/^0.5/.test(d.style.opacity),b.cssFloat=!!d.style.cssFloat,b.checkOn=!!f.value,b.optSelected=j.selected,b.enctype=!!g.createElement("form").enctype,b.html5Clone="<:nav></:nav>"!==g.createElement("nav").cloneNode(!0).outerHTML,b.inlineBlockNeedsLayout=!1,b.shrinkWrapBlocks=!1,b.pixelPosition=!1,b.deleteExpando=!0,b.noCloneEvent=!0,b.reliableMarginRight=!0,b.boxSizingReliable=!0,f.checked=!0,b.noCloneChecked=f.cloneNode(!0).checked,h.disabled=!0,b.optDisabled=!j.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}f=g.createElement("input"),f.setAttribute("value",""),b.input=""===f.getAttribute("value"),f.value="t",f.setAttribute("type","radio"),b.radioValue="t"===f.value,f.setAttribute("checked","t"),f.setAttribute("name","t"),i=g.createDocumentFragment(),i.appendChild(f),b.appendChecked=f.checked,b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,n.attachEvent&&(n.attachEvent("onclick",function(){b.noCloneEvent=!1}),n.cloneNode(!0).click());for(m in{submit:!0,change:!0,focusin:!0})n.setAttribute(k="on"+m,"t"),b[m+"Bubbles"]=k in a||n.attributes[k].expando===!1;n.style.backgroundClip="content-box",n.cloneNode(!0).style.backgroundClip="",b.clearCloneStyle="content-box"===n.style.backgroundClip;for(m in u(b))break;return b.ownLast="0"!==m,u(function(){var c,d,f,h="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",i=g.getElementsByTagName("body")[0];i&&(c=g.createElement("div"),c.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",i.appendChild(c).appendChild(n),n.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=n.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=0===f[0].offsetHeight,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&0===f[0].offsetHeight,n.innerHTML="",n.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%;",u.swap(i,null!=i.style.zoom?{zoom:1}:{},function(){b.boxSizing=4===n.offsetWidth}),a.getComputedStyle&&(b.pixelPosition="1%"!==(a.getComputedStyle(n,null)||{}).top,b.boxSizingReliable="4px"===(a.getComputedStyle(n,null)||{width:"4px"}).width,d=n.appendChild(g.createElement("div")),d.style.cssText=n.style.cssText=h,d.style.marginRight=d.style.width="0",n.style.width="1px",b.reliableMarginRight=!parseFloat((a.getComputedStyle(d,null)||{}).marginRight)),typeof n.style.zoom!==e&&(n.innerHTML="",n.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=3===n.offsetWidth,n.style.display="block",n.innerHTML="<div></div>",n.firstChild.style.width="5px",b.shrinkWrapBlocks=3!==n.offsetWidth,b.inlineBlockNeedsLayout&&(i.style.zoom=1)),i.removeChild(c),c=n=f=d=null)}),c=h=i=j=d=f=null,b}({});var M=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,N=/([A-Z])/g;u.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?u.cache[a[u.expando]]:a[u.expando],!!a&&!R(a)},data:function(a,b,c){return O(a,b,c)},removeData:function(a,b){return P(a,b)},_data:function(a,b,c){return O(a,b,c,!0)},_removeData:function(a,b){return P(a,b,!0)},acceptData:function(a){if(a.nodeType&&1!==a.nodeType&&9!==a.nodeType)return!1;var b=a.nodeName&&u.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),u.fn.extend({data:function(a,c){var d,e,f=null,g=0,h=this[0];if(a===b){if(this.length&&(f=u.data(h),1===h.nodeType&&!u._data(h,"parsedAttrs"))){for(d=h.attributes;g<d.length;g++)e=d[g].name,0===e.indexOf("data-")&&(e=u.camelCase(e.slice(5)),Q(h,e,f[e]));u._data(h,"parsedAttrs",!0)}return f}return"object"==typeof a?this.each(function(){u.data(this,a)}):arguments.length>1?this.each(function(){u.data(this,a,c)}):h?Q(h,a,u.data(h,a)):null},removeData:function(a){return this.each(function(){u.removeData(this,a)})}}),u.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=u._data(a,b),c&&(!d||u.isArray(c)?d=u._data(a,b,u.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=u.queue(a,b),d=c.length,e=c.shift(),f=u._queueHooks(a,b),g=function(){u.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return u._data(a,c)||u._data(a,c,{empty:u.Callbacks("once memory").add(function(){u._removeData(a,b+"queue"),u._removeData(a,c)})})}}),u.fn.extend({queue:function(a,c){var d=2;return"string"!=typeof a&&(c=a,a="fx",d--),arguments.length<d?u.queue(this[0],a):c===b?this:this.each(function(){var b=u.queue(this,a,c);u._queueHooks(this,a),"fx"===a&&"inprogress"!==b[0]&&u.dequeue(this,a)})},dequeue:function(a){return this.each(function(){u.dequeue(this,a)})},delay:function(a,b){return a=u.fx?u.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=u.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};for("string"!=typeof a&&(c=a,a=b),a=a||"fx";h--;)d=u._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var S,T,U=/[\t\r\n\f]/g,V=/\r/g,W=/^(?:input|select|textarea|button|object)$/i,X=/^(?:a|area)$/i,Y=/^(?:checked|selected)$/i,Z=u.support.getSetAttribute,$=u.support.input;u.fn.extend({attr:function(a,b){return u.access(this,u.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){u.removeAttr(this,a)})},prop:function(a,b){return u.access(this,u.prop,a,b,arguments.length>1)},removeProp:function(a){return a=u.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g=0,h=this.length,i="string"==typeof a&&a;if(u.isFunction(a))return this.each(function(b){u(this).addClass(a.call(this,b,this.className))});if(i)for(b=(a||"").match(w)||[];h>g;g++)if(c=this[g],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(U," "):" ")){for(f=0;e=b[f++];)d.indexOf(" "+e+" ")<0&&(d+=e+" ");c.className=u.trim(d)}return this},removeClass:function(a){var b,c,d,e,f,g=0,h=this.length,i=0===arguments.length||"string"==typeof a&&a;if(u.isFunction(a))return this.each(function(b){u(this).removeClass(a.call(this,b,this.className))});if(i)for(b=(a||"").match(w)||[];h>g;g++)if(c=this[g],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(U," "):"")){for(f=0;e=b[f++];)for(;d.indexOf(" "+e+" ")>=0;)d=d.replace(" "+e+" "," ");c.className=a?u.trim(d):""}return this},toggleClass:function(a,b){var c=typeof a,d="boolean"==typeof b;return u.isFunction(a)?this.each(function(c){u(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if("string"===c)for(var f,g=0,h=u(this),i=b,j=a.match(w)||[];f=j[g++];)i=d?i:!h.hasClass(f),h[i?"addClass":"removeClass"](f);else(c===e||"boolean"===c)&&(this.className&&u._data(this,"__className__",this.className),this.className=this.className||a===!1?"":u._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(U," ").indexOf(b)>=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];{if(arguments.length)return e=u.isFunction(a),this.each(function(c){var f;1===this.nodeType&&(f=e?a.call(this,c,u(this).val()):a,null==f?f="":"number"==typeof f?f+="":u.isArray(f)&&(f=u.map(f,function(a){return null==a?"":a+""})),d=u.valHooks[this.type]||u.valHooks[this.nodeName.toLowerCase()],d&&"set"in d&&d.set(this,f,"value")!==b||(this.value=f))});if(f)return d=u.valHooks[f.type]||u.valHooks[f.nodeName.toLowerCase()],d&&"get"in d&&(c=d.get(f,"value"))!==b?c:(c=f.value,"string"==typeof c?c.replace(V,""):null==c?"":c)}}}),u.extend({valHooks:{option:{get:function(a){var b=u.find.attr(a,"value");return null!=b?b:a.text}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(u.support.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&u.nodeName(c.parentNode,"optgroup"))){if(b=u(c).val(),f)return b;g.push(b)}return g},set:function(a,b){for(var c,d,e=a.options,f=u.makeArray(b),g=e.length;g--;)d=e[g],(d.selected=u.inArray(u(d).val(),f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}},attr:function(a,c,d){var f,g,h=a.nodeType;if(a&&3!==h&&8!==h&&2!==h)return typeof a.getAttribute===e?u.prop(a,c,d):(1===h&&u.isXMLDoc(a)||(c=c.toLowerCase(),f=u.attrHooks[c]||(u.expr.match.bool.test(c)?T:S)),d===b?f&&"get"in f&&null!==(g=f.get(a,c))?g:(g=u.find.attr(a,c),null==g?b:g):null!==d?f&&"set"in f&&(g=f.set(a,d,c))!==b?g:(a.setAttribute(c,d+""),d):(u.removeAttr(a,c),void 0))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(w);if(f&&1===a.nodeType)for(;c=f[e++];)d=u.propFix[c]||c,u.expr.match.bool.test(c)?$&&Z||!Y.test(c)?a[d]=!1:a[u.camelCase("default-"+c)]=a[d]=!1:u.attr(a,c,""),a.removeAttribute(Z?c:d)},attrHooks:{type:{set:function(a,b){if(!u.support.radioValue&&"radio"===b&&u.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(a&&3!==h&&8!==h&&2!==h)return g=1!==h||!u.isXMLDoc(a),g&&(c=u.propFix[c]||c,f=u.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&null!==(e=f.get(a,c))?e:a[c]},propHooks:{tabIndex:{get:function(a){var b=u.find.attr(a,"tabindex");return b?parseInt(b,10):W.test(a.nodeName)||X.test(a.nodeName)&&a.href?0:-1}}}}),T={set:function(a,b,c){return b===!1?u.removeAttr(a,c):$&&Z||!Y.test(c)?a.setAttribute(!Z&&u.propFix[c]||c,c):a[u.camelCase("default-"+c)]=a[c]=!0,c}},u.each(u.expr.match.bool.source.match(/\w+/g),function(a,c){var d=u.expr.attrHandle[c]||u.find.attr;u.expr.attrHandle[c]=$&&Z||!Y.test(c)?function(a,c,e){var f=u.expr.attrHandle[c],g=e?b:(u.expr.attrHandle[c]=b)!=d(a,c,e)?c.toLowerCase():null;return u.expr.attrHandle[c]=f,g}:function(a,c,d){return d?b:a[u.camelCase("default-"+c)]?c.toLowerCase():null}}),$&&Z||(u.attrHooks.value={set:function(a,b,c){return u.nodeName(a,"input")?(a.defaultValue=b,void 0):S&&S.set(a,b,c)}}),Z||(S={set:function(a,c,d){var e=a.getAttributeNode(d);return e||a.setAttributeNode(e=a.ownerDocument.createAttribute(d)),e.value=c+="","value"===d||c===a.getAttribute(d)?c:b}},u.expr.attrHandle.id=u.expr.attrHandle.name=u.expr.attrHandle.coords=function(a,c,d){var e;return d?b:(e=a.getAttributeNode(c))&&""!==e.value?e.value:null},u.valHooks.button={get:function(a,c){var d=a.getAttributeNode(c);return d&&d.specified?d.value:b},set:S.set},u.attrHooks.contenteditable={set:function(a,b,c){S.set(a,""===b?!1:b,c)}},u.each(["width","height"],function(a,b){u.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),u.support.hrefNormalized||u.each(["href","src"],function(a,b){u.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),u.support.style||(u.attrHooks.style={get:function(a){return a.style.cssText||b},set:function(a,b){return a.style.cssText=b+""}}),u.support.optSelected||(u.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),u.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){u.propFix[this.toLowerCase()]=this}),u.support.enctype||(u.propFix.enctype="encoding"),u.each(["radio","checkbox"],function(){u.valHooks[this]={set:function(a,b){return u.isArray(b)?a.checked=u.inArray(u(a).val(),b)>=0:void 0}},u.support.checkOn||(u.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var _=/^(?:input|select|textarea)$/i,ab=/^key/,bb=/^(?:mouse|contextmenu)|click/,cb=/^(?:focusinfocus|focusoutblur)$/,db=/^([^.]*)(?:\.(.+)|)$/;u.event={global:{},add:function(a,c,d,f,g){var h,i,j,k,l,m,n,o,p,q,r,s=u._data(a);if(s){for(d.handler&&(k=d,d=k.handler,g=k.selector),d.guid||(d.guid=u.guid++),(i=s.events)||(i=s.events={}),(m=s.handle)||(m=s.handle=function(a){return typeof u===e||a&&u.event.triggered===a.type?b:u.event.dispatch.apply(m.elem,arguments)},m.elem=a),c=(c||"").match(w)||[""],j=c.length;j--;)h=db.exec(c[j])||[],p=r=h[1],q=(h[2]||"").split(".").sort(),p&&(l=u.event.special[p]||{},p=(g?l.delegateType:l.bindType)||p,l=u.event.special[p]||{},n=u.extend({type:p,origType:r,data:f,handler:d,guid:d.guid,selector:g,needsContext:g&&u.expr.match.needsContext.test(g),namespace:q.join(".")},k),(o=i[p])||(o=i[p]=[],o.delegateCount=0,l.setup&&l.setup.call(a,f,q,m)!==!1||(a.addEventListener?a.addEventListener(p,m,!1):a.attachEvent&&a.attachEvent("on"+p,m))),l.add&&(l.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),g?o.splice(o.delegateCount++,0,n):o.push(n),u.event.global[p]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=u.hasData(a)&&u._data(a);if(q&&(k=q.events)){for(b=(b||"").match(w)||[""],j=b.length;j--;)if(h=db.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){for(l=u.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=k[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;f--;)g=m[f],!e&&p!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||u.removeEvent(a,n,q.handle),delete k[n])}else for(n in k)u.event.remove(a,n+b[j],c,d,!0);u.isEmptyObject(k)&&(delete q.handle,u._removeData(a,"events"))}},trigger:function(c,d,e,f){var h,i,j,k,l,m,n,o=[e||g],p=s.call(c,"type")?c.type:c,q=s.call(c,"namespace")?c.namespace.split("."):[];if(j=m=e=e||g,3!==e.nodeType&&8!==e.nodeType&&!cb.test(p+u.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),i=p.indexOf(":")<0&&"on"+p,c=c[u.expando]?c:new u.Event(p,"object"==typeof c&&c),c.isTrigger=f?2:3,c.namespace=q.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,c.result=b,c.target||(c.target=e),d=null==d?[c]:u.makeArray(d,[c]),l=u.event.special[p]||{},f||!l.trigger||l.trigger.apply(e,d)!==!1)){if(!f&&!l.noBubble&&!u.isWindow(e)){for(k=l.delegateType||p,cb.test(k+p)||(j=j.parentNode);j;j=j.parentNode)o.push(j),m=j;m===(e.ownerDocument||g)&&o.push(m.defaultView||m.parentWindow||a)}for(n=0;(j=o[n++])&&!c.isPropagationStopped();)c.type=n>1?k:l.bindType||p,h=(u._data(j,"events")||{})[c.type]&&u._data(j,"handle"),h&&h.apply(j,d),h=i&&j[i],h&&u.acceptData(j)&&h.apply&&h.apply(j,d)===!1&&c.preventDefault();if(c.type=p,!f&&!c.isDefaultPrevented()&&(!l._default||l._default.apply(o.pop(),d)===!1)&&u.acceptData(e)&&i&&e[p]&&!u.isWindow(e)){m=e[i],m&&(e[i]=null),u.event.triggered=p;try{e[p]()}catch(r){}u.event.triggered=b,m&&(e[i]=m)}return c.result}},dispatch:function(a){a=u.event.fix(a);var c,d,e,f,g,h=[],i=p.call(arguments),j=(u._data(this,"events")||{})[a.type]||[],k=u.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){for(h=u.event.handlers.call(this,a,j),c=0;(f=h[c++])&&!a.isPropagationStopped();)for(a.currentTarget=f.elem,g=0;(e=f.handlers[g++])&&!a.isImmediatePropagationStopped();)(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,d=((u.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),d!==b&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()));return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,c){var d,e,f,g,h=[],i=c.delegateCount,j=a.target;if(i&&j.nodeType&&(!a.button||"click"!==a.type))for(;j!=this;j=j.parentNode||this)if(1===j.nodeType&&(j.disabled!==!0||"click"!==a.type)){for(f=[],g=0;i>g;g++)e=c[g],d=e.selector+" ",f[d]===b&&(f[d]=e.needsContext?u(d,this).index(j)>=0:u.find(d,this,null,[j]).length),f[d]&&f.push(e);f.length&&h.push({elem:j,handlers:f})}return i<c.length&&h.push({elem:this,handlers:c.slice(i)}),h},fix:function(a){if(a[u.expando])return a;var b,c,d,e=a.type,f=a,h=this.fixHooks[e];for(h||(this.fixHooks[e]=h=bb.test(e)?this.mouseHooks:ab.test(e)?this.keyHooks:{}),d=h.props?this.props.concat(h.props):this.props,a=new u.Event(f),b=d.length;b--;)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||g),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,h.filter?h.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,e,f,h=c.button,i=c.fromElement;return null==a.pageX&&null!=c.clientX&&(e=a.target.ownerDocument||g,f=e.documentElement,d=e.body,a.pageX=c.clientX+(f&&f.scrollLeft||d&&d.scrollLeft||0)-(f&&f.clientLeft||d&&d.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||d&&d.scrollTop||0)-(f&&f.clientTop||d&&d.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),a.which||h===b||(a.which=1&h?1:2&h?3:4&h?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==gb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===gb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return u.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return u.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){a.result!==b&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=u.extend(new u.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?u.event.trigger(e,null,b):u.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},u.removeEvent=g.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===e&&(a[d]=null),a.detachEvent(d,c))},u.Event=function(a,b){return this instanceof u.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?eb:fb):this.type=a,b&&u.extend(this,b),this.timeStamp=a&&a.timeStamp||u.now(),this[u.expando]=!0,void 0):new u.Event(a,b)},u.Event.prototype={isDefaultPrevented:fb,isPropagationStopped:fb,isImmediatePropagationStopped:fb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=eb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=eb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=eb,this.stopPropagation()}},u.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){u.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!u.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),u.support.submitBubbles||(u.event.special.submit={setup:function(){return u.nodeName(this,"form")?!1:(u.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=u.nodeName(c,"input")||u.nodeName(c,"button")?c.form:b;d&&!u._data(d,"submitBubbles")&&(u.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),u._data(d,"submitBubbles",!0))}),void 0)},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&u.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return u.nodeName(this,"form")?!1:(u.event.remove(this,"._submit"),void 0)}}),u.support.changeBubbles||(u.event.special.change={setup:function(){return _.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(u.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),u.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),u.event.simulate("change",this,a,!0)})),!1):(u.event.add(this,"beforeactivate._change",function(a){var b=a.target;_.test(b.nodeName)&&!u._data(b,"changeBubbles")&&(u.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||u.event.simulate("change",this.parentNode,a,!0)}),u._data(b,"changeBubbles",!0))}),void 0)},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return u.event.remove(this,"._change"),!_.test(this.nodeName)}}),u.support.focusinBubbles||u.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){u.event.simulate(b,a.target,u.event.fix(a),!0)};u.event.special[b]={setup:function(){0===c++&&g.addEventListener(a,d,!0)},teardown:function(){0===--c&&g.removeEventListener(a,d,!0)}}}),u.fn.extend({on:function(a,c,d,e,f){var g,h;if("object"==typeof a){"string"!=typeof c&&(d=d||c,c=b);for(g in a)this.on(g,c,d,a[g],f);return this}if(null==d&&null==e?(e=c,d=c=b):null==e&&("string"==typeof c?(e=d,d=b):(e=d,d=c,c=b)),e===!1)e=fb;else if(!e)return this;return 1===f&&(h=e,e=function(a){return u().off(a),h.apply(this,arguments)},e.guid=h.guid||(h.guid=u.guid++)),this.each(function(){u.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,u(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if("object"==typeof a){for(f in a)this.off(f,c,a[f]);return this}return(c===!1||"function"==typeof c)&&(d=c,c=b),d===!1&&(d=fb),this.each(function(){u.event.remove(this,a,d,c)})},trigger:function(a,b){return this.each(function(){u.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?u.event.trigger(a,b,c,!0):void 0}});var hb=/^.[^:#\[\.,]*$/,ib=/^(?:parents|prev(?:Until|All))/,jb=u.expr.match.needsContext,kb={children:!0,contents:!0,next:!0,prev:!0};u.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(u(a).filter(function(){for(b=0;e>b;b++)if(u.contains(d[b],this))return!0}));for(b=0;e>b;b++)u.find(a,d[b],c);return c=this.pushStack(e>1?u.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},has:function(a){var b,c=u(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(u.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(mb(this,a||[],!0))},filter:function(a){return this.pushStack(mb(this,a||[],!1))},is:function(a){return!!mb(this,"string"==typeof a&&jb.test(a)?u(a):a||[],!1).length},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=jb.test(a)||"string"!=typeof a?u(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&u.find.matchesSelector(c,a))){c=f.push(c);break}return this.pushStack(f.length>1?u.unique(f):f)},index:function(a){return a?"string"==typeof a?u.inArray(this[0],u(a)):u.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){var c="string"==typeof a?u(a,b):u.makeArray(a&&a.nodeType?[a]:a),d=u.merge(this.get(),c);return this.pushStack(u.unique(d))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}}),u.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u.dir(a,"parentNode")},parentsUntil:function(a,b,c){return u.dir(a,"parentNode",c)},next:function(a){return lb(a,"nextSibling")},prev:function(a){return lb(a,"previousSibling")},nextAll:function(a){return u.dir(a,"nextSibling")},prevAll:function(a){return u.dir(a,"previousSibling")},nextUntil:function(a,b,c){return u.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return u.dir(a,"previousSibling",c)},siblings:function(a){return u.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return u.sibling(a.firstChild)},contents:function(a){return u.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:u.merge([],a.childNodes)
}},function(a,b){u.fn[a]=function(c,d){var e=u.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=u.filter(d,e)),this.length>1&&(kb[a]||(e=u.unique(e)),ib.test(a)&&(e=e.reverse())),this.pushStack(e)}}),u.extend({filter:function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?u.find.matchesSelector(d,a)?[d]:[]:u.find.matches(a,u.grep(b,function(a){return 1===a.nodeType}))},dir:function(a,c,d){for(var e=[],f=a[c];f&&9!==f.nodeType&&(d===b||1!==f.nodeType||!u(f).is(d));)1===f.nodeType&&e.push(f),f=f[c];return e},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}});var ob="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",pb=/ jQuery\d+="(?:null|\d+)"/g,qb=new RegExp("<(?:"+ob+")[\\s/>]","i"),rb=/^\s+/,sb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,tb=/<([\w:]+)/,ub=/<tbody/i,vb=/<|&#?\w+;/,wb=/<(?:script|style|link)/i,xb=/^(?:checkbox|radio)$/i,yb=/checked\s*(?:[^=]|=\s*.checked.)/i,zb=/^$|\/(?:java|ecma)script/i,Ab=/^true\/(.*)/,Bb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Cb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:u.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Db=nb(g),Eb=Db.appendChild(g.createElement("div"));Cb.optgroup=Cb.option,Cb.tbody=Cb.tfoot=Cb.colgroup=Cb.caption=Cb.thead,Cb.th=Cb.td,u.fn.extend({text:function(a){return u.access(this,function(a){return a===b?u.text(this):this.empty().append((this[0]&&this[0].ownerDocument||g).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Fb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Fb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?u.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||u.cleanData(Lb(c)),c.parentNode&&(b&&u.contains(c.ownerDocument,c)&&Ib(Lb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){for(1===a.nodeType&&u.cleanData(Lb(a,!1));a.firstChild;)a.removeChild(a.firstChild);a.options&&u.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return u.clone(this,a,b)})},html:function(a){return u.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return 1===c.nodeType?c.innerHTML.replace(pb,""):b;if(!("string"!=typeof a||wb.test(a)||!u.support.htmlSerialize&&qb.test(a)||!u.support.leadingWhitespace&&rb.test(a)||Cb[(tb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(sb,"<$1></$2>");try{for(;e>d;d++)c=this[d]||{},1===c.nodeType&&(u.cleanData(Lb(c,!1)),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=u.map(this,function(a){return[a.nextSibling,a.parentNode]}),b=0;return this.domManip(arguments,function(c){var d=a[b++],e=a[b++];e&&(d&&d.parentNode!==e&&(d=this.nextSibling),u(this).remove(),e.insertBefore(c,d))},!0),b?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b,c){a=n.apply([],a);var d,e,f,g,h,i,j=0,k=this.length,l=this,m=k-1,o=a[0],p=u.isFunction(o);if(p||!(1>=k||"string"!=typeof o||u.support.checkClone)&&yb.test(o))return this.each(function(d){var e=l.eq(d);p&&(a[0]=o.call(this,d,e.html())),e.domManip(a,b,c)});if(k&&(i=u.buildFragment(a,this[0].ownerDocument,!1,!c&&this),d=i.firstChild,1===i.childNodes.length&&(i=d),d)){for(g=u.map(Lb(i,"script"),Gb),f=g.length;k>j;j++)e=i,j!==m&&(e=u.clone(e,!0,!0),f&&u.merge(g,Lb(e,"script"))),b.call(this[j],e,j);if(f)for(h=g[g.length-1].ownerDocument,u.map(g,Hb),j=0;f>j;j++)e=g[j],zb.test(e.type||"")&&!u._data(e,"globalEval")&&u.contains(h,e)&&(e.src?u._evalUrl(e.src):u.globalEval((e.text||e.textContent||e.innerHTML||"").replace(Bb,"")));i=d=null}return this}}),u.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){u.fn[a]=function(a){for(var c,d=0,e=[],f=u(a),g=f.length-1;g>=d;d++)c=d===g?this:this.clone(!0),u(f[d])[b](c),o.apply(e,c.get());return this.pushStack(e)}}),u.extend({clone:function(a,b,c){var d,e,f,g,h,i=u.contains(a.ownerDocument,a);if(u.support.html5Clone||u.isXMLDoc(a)||!qb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Eb.innerHTML=a.outerHTML,Eb.removeChild(f=Eb.firstChild)),!(u.support.noCloneEvent&&u.support.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||u.isXMLDoc(a)))for(d=Lb(f),h=Lb(a),g=0;null!=(e=h[g]);++g)d[g]&&Kb(e,d[g]);if(b)if(c)for(h=h||Lb(a),d=d||Lb(f),g=0;null!=(e=h[g]);g++)Jb(e,d[g]);else Jb(a,f);return d=Lb(f,"script"),d.length>0&&Ib(d,!i&&Lb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,l=a.length,m=nb(b),n=[],o=0;l>o;o++)if(f=a[o],f||0===f)if("object"===u.type(f))u.merge(n,f.nodeType?[f]:f);else if(vb.test(f)){for(h=h||m.appendChild(b.createElement("div")),i=(tb.exec(f)||["",""])[1].toLowerCase(),k=Cb[i]||Cb._default,h.innerHTML=k[1]+f.replace(sb,"<$1></$2>")+k[2],e=k[0];e--;)h=h.lastChild;if(!u.support.leadingWhitespace&&rb.test(f)&&n.push(b.createTextNode(rb.exec(f)[0])),!u.support.tbody)for(f="table"!==i||ub.test(f)?"<table>"!==k[1]||ub.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;e--;)u.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j);for(u.merge(n,h.childNodes),h.textContent="";h.firstChild;)h.removeChild(h.firstChild);h=m.lastChild}else n.push(b.createTextNode(f));for(h&&m.removeChild(h),u.support.appendChecked||u.grep(Lb(n,"input"),Mb),o=0;f=n[o++];)if((!d||-1===u.inArray(f,d))&&(g=u.contains(f.ownerDocument,f),h=Lb(m.appendChild(f),"script"),g&&Ib(h),c))for(e=0;f=h[e++];)zb.test(f.type||"")&&c.push(f);return h=null,m},cleanData:function(a,b){for(var c,d,f,g,h=0,i=u.expando,j=u.cache,k=u.support.deleteExpando,m=u.event.special;null!=(c=a[h]);h++)if((b||u.acceptData(c))&&(f=c[i],g=f&&j[f])){if(g.events)for(d in g.events)m[d]?u.event.remove(c,d):u.removeEvent(c,d,g.handle);j[f]&&(delete j[f],k?delete c[i]:typeof c.removeAttribute!==e?c.removeAttribute(i):c[i]=null,l.push(f))}},_evalUrl:function(a){return u.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),u.fn.extend({wrapAll:function(a){if(u.isFunction(a))return this.each(function(b){u(this).wrapAll(a.call(this,b))});if(this[0]){var b=u(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){for(var a=this;a.firstChild&&1===a.firstChild.nodeType;)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return u.isFunction(a)?this.each(function(b){u(this).wrapInner(a.call(this,b))}):this.each(function(){var b=u(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=u.isFunction(a);return this.each(function(c){u(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){u.nodeName(this,"body")||u(this).replaceWith(this.childNodes)}).end()}});var Nb,Ob,Pb,Qb=/alpha\([^)]*\)/i,Rb=/opacity\s*=\s*([^)]*)/,Sb=/^(top|right|bottom|left)$/,Tb=/^(none|table(?!-c[ea]).+)/,Ub=/^margin/,Vb=new RegExp("^("+v+")(.*)$","i"),Wb=new RegExp("^("+v+")(?!px)[a-z%]+$","i"),Xb=new RegExp("^([+-])=("+v+")","i"),Yb={BODY:"block"},Zb={position:"absolute",visibility:"hidden",display:"block"},$b={letterSpacing:0,fontWeight:400},_b=["Top","Right","Bottom","Left"],ac=["Webkit","O","Moz","ms"];u.fn.extend({css:function(a,c){return u.access(this,function(a,c,d){var e,f,g={},h=0;if(u.isArray(c)){for(f=Ob(a),e=c.length;e>h;h++)g[c[h]]=u.css(a,c[h],!1,f);return g}return d!==b?u.style(a,c,d):u.css(a,c)},a,c,arguments.length>1)},show:function(){return dc(this,!0)},hide:function(){return dc(this)},toggle:function(a){var b="boolean"==typeof a;return this.each(function(){(b?a:cc(this))?u(this).show():u(this).hide()})}}),u.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Pb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":u.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var f,g,h,i=u.camelCase(c),j=a.style;if(c=u.cssProps[i]||(u.cssProps[i]=bc(j,i)),h=u.cssHooks[c]||u.cssHooks[i],d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];if(g=typeof d,"string"===g&&(f=Xb.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(u.css(a,c)),g="number"),!(null==d||"number"===g&&isNaN(d)||("number"!==g||u.cssNumber[i]||(d+="px"),u.support.clearCloneStyle||""!==d||0!==c.indexOf("background")||(j[c]="inherit"),h&&"set"in h&&(d=h.set(a,d,e))===b)))try{j[c]=d}catch(k){}}},css:function(a,c,d,e){var f,g,h,i=u.camelCase(c);return c=u.cssProps[i]||(u.cssProps[i]=bc(a.style,i)),h=u.cssHooks[c]||u.cssHooks[i],h&&"get"in h&&(g=h.get(a,!0,d)),g===b&&(g=Pb(a,c,e)),"normal"===g&&c in $b&&(g=$b[c]),""===d||d?(f=parseFloat(g),d===!0||u.isNumeric(f)?f||0:g):g}}),a.getComputedStyle?(Ob=function(b){return a.getComputedStyle(b,null)},Pb=function(a,c,d){var e,f,g,h=d||Ob(a),i=h?h.getPropertyValue(c)||h[c]:b,j=a.style;return h&&(""!==i||u.contains(a.ownerDocument,a)||(i=u.style(a,c)),Wb.test(i)&&Ub.test(c)&&(e=j.width,f=j.minWidth,g=j.maxWidth,j.minWidth=j.maxWidth=j.width=i,i=h.width,j.width=e,j.minWidth=f,j.maxWidth=g)),i}):g.documentElement.currentStyle&&(Ob=function(a){return a.currentStyle},Pb=function(a,c,d){var e,f,g,h=d||Ob(a),i=h?h[c]:b,j=a.style;return null==i&&j&&j[c]&&(i=j[c]),Wb.test(i)&&!Sb.test(c)&&(e=j.left,f=a.runtimeStyle,g=f&&f.left,g&&(f.left=a.currentStyle.left),j.left="fontSize"===c?"1em":i,i=j.pixelLeft+"px",j.left=e,g&&(f.left=g)),""===i?"auto":i}),u.each(["height","width"],function(a,b){u.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Tb.test(u.css(a,"display"))?u.swap(a,Zb,function(){return gc(a,b,d)}):gc(a,b,d):void 0},set:function(a,c,d){var e=d&&Ob(a);return ec(a,c,d?fc(a,b,d,u.support.boxSizing&&"border-box"===u.css(a,"boxSizing",!1,e),e):0)}}}),u.support.opacity||(u.cssHooks.opacity={get:function(a,b){return Rb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=u.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===u.trim(f.replace(Qb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Qb.test(f)?f.replace(Qb,e):f+" "+e)}}),u(function(){u.support.reliableMarginRight||(u.cssHooks.marginRight={get:function(a,b){return b?u.swap(a,{display:"inline-block"},Pb,[a,"marginRight"]):void 0}}),!u.support.pixelPosition&&u.fn.position&&u.each(["top","left"],function(a,b){u.cssHooks[b]={get:function(a,c){return c?(c=Pb(a,b),Wb.test(c)?u(a).position()[b]+"px":c):void 0}}})}),u.expr&&u.expr.filters&&(u.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!u.support.reliableHiddenOffsets&&"none"===(a.style&&a.style.display||u.css(a,"display"))},u.expr.filters.visible=function(a){return!u.expr.filters.hidden(a)}),u.each({margin:"",padding:"",border:"Width"},function(a,b){u.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+_b[d]+b]=f[d]||f[d-2]||f[0];return e}},Ub.test(a)||(u.cssHooks[a+b].set=ec)});var jc=/%20/g,kc=/\[\]$/,lc=/\r?\n/g,mc=/^(?:submit|button|image|reset|file)$/i,nc=/^(?:input|select|textarea|keygen)/i;u.fn.extend({serialize:function(){return u.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=u.prop(this,"elements");return a?u.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!u(this).is(":disabled")&&nc.test(this.nodeName)&&!mc.test(a)&&(this.checked||!xb.test(a))}).map(function(a,b){var c=u(this).val();return null==c?null:u.isArray(c)?u.map(c,function(a){return{name:b.name,value:a.replace(lc,"\r\n")}}):{name:b.name,value:c.replace(lc,"\r\n")}}).get()}}),u.param=function(a,c){var d,e=[],f=function(a,b){b=u.isFunction(b)?b():null==b?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(c===b&&(c=u.ajaxSettings&&u.ajaxSettings.traditional),u.isArray(a)||a.jquery&&!u.isPlainObject(a))u.each(a,function(){f(this.name,this.value)});else for(d in a)oc(d,a[d],c,f);return e.join("&").replace(jc,"+")},u.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(a,b){u.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),u.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var pc,qc,rc=u.now(),sc=/\?/,tc=/#.*$/,uc=/([?&])_=[^&]*/,vc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,wc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,xc=/^(?:GET|HEAD)$/,yc=/^\/\//,zc=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Ac=u.fn.load,Bc={},Cc={},Dc="*/".concat("*");try{qc=f.href}catch(Ec){qc=g.createElement("a"),qc.href="",qc=qc.href}pc=zc.exec(qc.toLowerCase())||[],u.fn.load=function(a,c,d){if("string"!=typeof a&&Ac)return Ac.apply(this,arguments);var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),u.isFunction(c)?(d=c,c=b):c&&"object"==typeof c&&(g="POST"),h.length>0&&u.ajax({url:a,type:g,dataType:"html",data:c}).done(function(a){f=arguments,h.html(e?u("<div>").append(u.parseHTML(a)).find(e):a)}).complete(d&&function(a,b){h.each(d,f||[a.responseText,b,a])}),this},u.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){u.fn[b]=function(a){return this.on(b,a)}}),u.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:qc,type:"GET",isLocal:wc.test(pc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":u.parseJSON,"text xml":u.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Hc(Hc(a,u.ajaxSettings),b):Hc(u.ajaxSettings,a)},ajaxPrefilter:Fc(Bc),ajaxTransport:Fc(Cc),ajax:function(a,c){function z(a,c,d,e){var k,r,s,v,w,y=c;2!==t&&(t=2,h&&clearTimeout(h),j=b,g=e||"",x.readyState=a>0?4:0,k=a>=200&&300>a||304===a,d&&(v=Ic(l,x,d)),v=Jc(l,v,x,k),k?(l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(u.lastModified[f]=w),w=x.getResponseHeader("etag"),w&&(u.etag[f]=w)),204===a||"HEAD"===l.type?y="nocontent":304===a?y="notmodified":(y=v.state,r=v.data,s=v.error,k=!s)):(s=y,(a||!y)&&(y="error",0>a&&(a=0))),x.status=a,x.statusText=(c||y)+"",k?o.resolveWith(m,[r,y,x]):o.rejectWith(m,[x,y,s]),x.statusCode(q),q=b,i&&n.trigger(k?"ajaxSuccess":"ajaxError",[x,l,k?r:s]),p.fireWith(m,[x,y]),i&&(n.trigger("ajaxComplete",[x,l]),--u.active||u.event.trigger("ajaxStop")))}"object"==typeof a&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=u.ajaxSetup({},c),m=l.context||l,n=l.context&&(m.nodeType||m.jquery)?u(m):u.event,o=u.Deferred(),p=u.Callbacks("once memory"),q=l.statusCode||{},r={},s={},t=0,v="canceled",x={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!k)for(k={};b=vc.exec(g);)k[b[1].toLowerCase()]=b[2];b=k[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(l.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else x.always(a[x.status]);return this},abort:function(a){var b=a||v;return j&&j.abort(b),z(0,b),this}};if(o.promise(x).complete=p.add,x.success=x.done,x.error=x.fail,l.url=((a||l.url||qc)+"").replace(tc,"").replace(yc,pc[1]+"//"),l.type=c.method||c.type||l.method||l.type,l.dataTypes=u.trim(l.dataType||"*").toLowerCase().match(w)||[""],null==l.crossDomain&&(d=zc.exec(l.url.toLowerCase()),l.crossDomain=!(!d||d[1]===pc[1]&&d[2]===pc[2]&&(d[3]||("http:"===d[1]?"80":"443"))===(pc[3]||("http:"===pc[1]?"80":"443")))),l.data&&l.processData&&"string"!=typeof l.data&&(l.data=u.param(l.data,l.traditional)),Gc(Bc,l,c,x),2===t)return x;i=l.global,i&&0===u.active++&&u.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!xc.test(l.type),f=l.url,l.hasContent||(l.data&&(f=l.url+=(sc.test(f)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=uc.test(f)?f.replace(uc,"$1_="+rc++):f+(sc.test(f)?"&":"?")+"_="+rc++)),l.ifModified&&(u.lastModified[f]&&x.setRequestHeader("If-Modified-Since",u.lastModified[f]),u.etag[f]&&x.setRequestHeader("If-None-Match",u.etag[f])),(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0]?", "+Dc+"; q=0.01":""):l.accepts["*"]);for(e in l.headers)x.setRequestHeader(e,l.headers[e]);if(l.beforeSend&&(l.beforeSend.call(m,x,l)===!1||2===t))return x.abort();v="abort";for(e in{success:1,error:1,complete:1})x[e](l[e]);if(j=Gc(Cc,l,c,x)){x.readyState=1,i&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{t=1,j.send(r,z)}catch(y){if(!(2>t))throw y;z(-1,y)}}else z(-1,"No Transport");return x},getJSON:function(a,b,c){return u.get(a,b,c,"json")},getScript:function(a,c){return u.get(a,b,c,"script")}}),u.each(["get","post"],function(a,c){u[c]=function(a,d,e,f){return u.isFunction(d)&&(f=f||e,e=d,d=b),u.ajax({url:a,type:c,dataType:f,data:d,success:e})}}),u.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return u.globalEval(a),a}}}),u.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),u.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=g.head||u("head")[0]||g.documentElement;return{send:function(b,e){c=g.createElement("script"),c.async=!0,a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,b){(b||!c.readyState||/loaded|complete/.test(c.readyState))&&(c.onload=c.onreadystatechange=null,c.parentNode&&c.parentNode.removeChild(c),c=null,b||e(200,"success"))},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(b,!0)}}}});var Kc=[],Lc=/(=)\?(?=&|$)|\?\?/;u.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Kc.pop()||u.expando+"_"+rc++;return this[a]=!0,a}}),u.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.jsonp!==!1&&(Lc.test(c.url)?"url":"string"==typeof c.data&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&Lc.test(c.data)&&"data");return i||"jsonp"===c.dataTypes[0]?(f=c.jsonpCallback=u.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,i?c[i]=c[i].replace(Lc,"$1"+f):c.jsonp!==!1&&(c.url+=(sc.test(c.url)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||u.error(f+" was not called"),h[0]},c.dataTypes[0]="json",g=a[f],a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,Kc.push(f)),h&&u.isFunction(g)&&g(h[0]),h=g=b}),"script"):void 0});var Mc,Nc,Oc=0,Pc=a.ActiveXObject&&function(){var a;for(a in Mc)Mc[a](b,!0)};u.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&Qc()||Rc()}:Qc,Nc=u.ajaxSettings.xhr(),u.support.cors=!!Nc&&"withCredentials"in Nc,Nc=u.support.ajax=!!Nc,Nc&&u.ajaxTransport(function(c){if(!c.crossDomain||u.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();if(c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async),c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),c.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l;try{if(d&&(e||4===i.readyState))if(d=b,g&&(i.onreadystatechange=u.noop,Pc&&delete Mc[g]),e)4!==i.readyState&&i.abort();else{l={},h=i.status,j=i.getAllResponseHeaders(),"string"==typeof i.responseText&&(l.text=i.responseText);try{k=i.statusText}catch(m){k=""}h||!c.isLocal||c.crossDomain?1223===h&&(h=204):h=l.text?200:404}}catch(n){e||f(-1,n)}l&&f(h,k,l,j)},c.async?4===i.readyState?setTimeout(d):(g=++Oc,Pc&&(Mc||(Mc={},u(a).unload(Pc)),Mc[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(b,!0)}}}});var Sc,Tc,Uc=/^(?:toggle|show|hide)$/,Vc=new RegExp("^(?:([+-])=|)("+v+")([a-z%]*)$","i"),Wc=/queueHooks$/,Xc=[bd],Yc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Vc.exec(b),f=e&&e[3]||(u.cssNumber[a]?"":"px"),g=(u.cssNumber[a]||"px"!==f&&+d)&&Vc.exec(u.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,u.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};u.Animation=u.extend(_c,{tweener:function(a,b){u.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Yc[c]=Yc[c]||[],Yc[c].unshift(b)},prefilter:function(a,b){b?Xc.unshift(a):Xc.push(a)}}),u.Tween=cd,cd.prototype={constructor:cd,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(u.cssNumber[c]?"":"px")},cur:function(){var a=cd.propHooks[this.prop];return a&&a.get?a.get(this):cd.propHooks._default.get(this)},run:function(a){var b,c=cd.propHooks[this.prop];return this.pos=b=this.options.duration?u.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cd.propHooks._default.set(this),this}},cd.prototype.init.prototype=cd.prototype,cd.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=u.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){u.fx.step[a.prop]?u.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[u.cssProps[a.prop]]||u.cssHooks[a.prop])?u.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cd.propHooks.scrollTop=cd.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},u.each(["toggle","show","hide"],function(a,b){var c=u.fn[b];u.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(dd(b,!0),a,d,e)}}),u.fn.extend({fadeTo:function(a,b,c,d){return this.filter(cc).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=u.isEmptyObject(a),f=u.speed(b,c,d),g=function(){var b=_c(this,u.extend({},a),f);(e||u._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return"string"!=typeof a&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=null!=a&&a+"queueHooks",f=u.timers,g=u._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&Wc.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem!==this||null!=a&&f[c].queue!==a||(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&u.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=u._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=u.timers,g=d?d.length:0;for(c.finish=!0,u.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),u.each({slideDown:dd("show"),slideUp:dd("hide"),slideToggle:dd("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){u.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),u.speed=function(a,b,c){var d=a&&"object"==typeof a?u.extend({},a):{complete:c||!c&&b||u.isFunction(a)&&a,duration:a,easing:c&&b||b&&!u.isFunction(b)&&b};return d.duration=u.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in u.fx.speeds?u.fx.speeds[d.duration]:u.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){u.isFunction(d.old)&&d.old.call(this),d.queue&&u.dequeue(this,d.queue)},d},u.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},u.timers=[],u.fx=cd.prototype.init,u.fx.tick=function(){var a,c=u.timers,d=0;for(Sc=u.now();d<c.length;d++)a=c[d],a()||c[d]!==a||c.splice(d--,1);c.length||u.fx.stop(),Sc=b},u.fx.timer=function(a){a()&&u.timers.push(a)&&u.fx.start()},u.fx.interval=13,u.fx.start=function(){Tc||(Tc=setInterval(u.fx.tick,u.fx.interval))},u.fx.stop=function(){clearInterval(Tc),Tc=null},u.fx.speeds={slow:600,fast:200,_default:400},u.fx.step={},u.expr&&u.expr.filters&&(u.expr.filters.animated=function(a){return u.grep(u.timers,function(b){return a===b.elem}).length}),u.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){u.offset.setOffset(this,a,b)});var c,d,f={top:0,left:0},g=this[0],h=g&&g.ownerDocument;if(h)return c=h.documentElement,u.contains(c,g)?(typeof g.getBoundingClientRect!==e&&(f=g.getBoundingClientRect()),d=ed(h),{top:f.top+(d.pageYOffset||c.scrollTop)-(c.clientTop||0),left:f.left+(d.pageXOffset||c.scrollLeft)-(c.clientLeft||0)}):f},u.offset={setOffset:function(a,b,c){var d=u.css(a,"position");"static"===d&&(a.style.position="relative");var l,m,e=u(a),f=e.offset(),g=u.css(a,"top"),h=u.css(a,"left"),i=("absolute"===d||"fixed"===d)&&u.inArray("auto",[g,h])>-1,j={},k={};i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),u.isFunction(b)&&(b=b.call(a,c,f)),null!=b.top&&(j.top=b.top-f.top+l),null!=b.left&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},u.fn.extend({position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===u.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),u.nodeName(a[0],"html")||(c=a.offset()),c.top+=u.css(a[0],"borderTopWidth",!0),c.left+=u.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-u.css(d,"marginTop",!0),left:b.left-c.left-u.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||h;a&&!u.nodeName(a,"html")&&"static"===u.css(a,"position");)a=a.offsetParent;return a||h})}}),u.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);u.fn[a]=function(e){return u.access(this,function(a,e,f){var g=ed(a);return f===b?g?c in g?g[c]:g.document.documentElement[e]:a[e]:(g?g.scrollTo(d?u(g).scrollLeft():f,d?f:u(g).scrollTop()):a[e]=f,void 0)},a,e,arguments.length,null)}}),u.each({Height:"height",Width:"width"},function(a,c){u.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){u.fn[e]=function(e,f){var g=arguments.length&&(d||"boolean"!=typeof e),h=d||(e===!0||f===!0?"margin":"border");return u.access(this,function(c,d,e){var f;return u.isWindow(c)?c.document.documentElement["client"+a]:9===c.nodeType?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?u.css(c,d,h):u.style(c,d,e,h)},c,g?e:b,g,null)}})}),u.fn.size=function(){return this.length},u.fn.andSelf=u.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=u:(a.jQuery=a.$=u,"function"==typeof define&&define.amd&&define("jquery",[],function(){return u}))}(window); |
private/storybook/config.js | SIB-Colombia/biodiversity_catalogue_v2_frontend | // https://github.com/diegohaz/arc/wiki/Storybook
import React from 'react'
import { configure, addDecorator } from '@kadira/storybook'
import { BrowserRouter } from 'react-router-dom'
import { ThemeProvider } from 'styled-components'
import theme from 'components/themes/default'
const req = require.context('components', true, /.stories.js$/)
function loadStories() {
req.keys().forEach(filename => req(filename))
}
addDecorator(story => (
<BrowserRouter>
<ThemeProvider theme={theme}>{story()}</ThemeProvider>
</BrowserRouter>
))
configure(loadStories, module)
|
client/modules/App/components/Footer/Footer.js | moscow-freecodecamp/fluffy-spoon | import React from 'react';
import { FormattedMessage } from 'react-intl';
// Import Style
import styles from './Footer.css';
// Import Images
import bg from '../../header-bk.png';
export function Footer() {
return (
<div style={{ background: `#FFF url(${bg}) center` }} className={styles.footer}>
<p>© 2016 · Hashnode · LinearBytes Inc.</p>
<p><FormattedMessage id="twitterMessage" /> : <a href="https://twitter.com/@mern_io" target="_Blank">@mern_io</a></p>
</div>
);
}
export default Footer;
|
src/components/conversations-tutorial-card.js | colinmegill/polis-admin-console | /*
* Copyright 2012-present, Polis Technology 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 for non-commercial use can be found in the PATENTS file
* in the same directory.
*/
import React from 'react';
import Radium from 'radium';
import Awesome from "react-fontawesome";
// import _ from 'lodash';
// import Flex from './framework/flex';
// import { connect } from 'react-redux';
// import { FOO } from '../actions';
// const style = {
// };
// @connect(state => {
// return state.FOO;
// })
@Radium
class ConversationTutorialCard extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
static propTypes = {
/* react */
// dispatch: React.PropTypes.func,
params: React.PropTypes.object,
routes: React.PropTypes.array,
/* component api */
style: React.PropTypes.object,
title: React.PropTypes.string,
awesome: React.PropTypes.string,
docs: React.PropTypes.bool,
clickHandler: React.PropTypes.func,
// foo: React.PropTypes.string
}
static defaultProps = {
title: "Default Tutorial Title",
awesome: "plus",
docs: false,
}
getStyles() {
return {
container: {
maxWidth: 300,
padding: 20,
cursor: "pointer",
margin: 20,
color: "rgb(100,100,100)",
backgroundColor: "rgb(253,253,253)",
borderRadius: 3,
WebkitBoxShadow: "3px 3px 6px -1px rgba(220,220,220,1)",
BoxShadow: "3px 3px 6px -1px rgba(220,220,220,1)"
},
awesome: {
marginRight: 10
},
heading: {
fontWeight: 700
},
body: {
fontWeight: 300,
lineHeight: 1.7
}
};
}
render() {
const styles = this.getStyles();
return (
<div
onClick={this.props.clickHandler}
style={[
styles.container,
this.props.style
]}>
<p style={styles.heading}>
<Awesome name={this.props.awesome} style={styles.awesome}/>
{this.props.title}
</p>
<p style={styles.body}>
{this.props.body}
</p>
</div>
);
}
}
export default ConversationTutorialCard;
/*
propTypes: {
// You can declare that a prop is a specific JS primitive. By default, these
// are all optional.
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: React.PropTypes.node,
// A React element.
optionalElement: React.PropTypes.element,
// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: React.PropTypes.instanceOf(Message),
// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
// An object that could be one of many types
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Message)
]),
// An array of a certain type
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
// An object with property values of a certain type
optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
// An object taking on a particular shape
optionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),
// You can chain any of the above with `isRequired` to make sure a warning
// is shown if the prop isn't provided.
requiredFunc: React.PropTypes.func.isRequired,
// A value of any data type
requiredAny: React.PropTypes.any.isRequired,
*/
|
ajax/libs/material-ui/4.9.3/esm/Tooltip/Tooltip.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { elementAcceptingRef } from '@material-ui/utils';
import { fade } from '../styles/colorManipulator';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
import Grow from '../Grow';
import Popper from '../Popper';
import useForkRef from '../utils/useForkRef';
import setRef from '../utils/setRef';
import { useIsFocusVisible } from '../utils/focusVisible';
import useControlled from '../utils/useControlled';
import useTheme from '../styles/useTheme';
function round(value) {
return Math.round(value * 1e5) / 1e5;
}
function arrowGenerator() {
return {
'&[x-placement*="bottom"] $arrow': {
flip: false,
top: 0,
left: 0,
marginTop: '-0.95em',
marginLeft: 4,
marginRight: 4,
width: '2em',
height: '1em',
'&::before': {
flip: false,
borderWidth: '0 1em 1em 1em',
borderColor: 'transparent transparent currentcolor transparent'
}
},
'&[x-placement*="top"] $arrow': {
flip: false,
bottom: 0,
left: 0,
marginBottom: '-0.95em',
marginLeft: 4,
marginRight: 4,
width: '2em',
height: '1em',
'&::before': {
flip: false,
borderWidth: '1em 1em 0 1em',
borderColor: 'currentcolor transparent transparent transparent'
}
},
'&[x-placement*="right"] $arrow': {
flip: false,
left: 0,
marginLeft: '-0.95em',
marginTop: 4,
marginBottom: 4,
height: '2em',
width: '1em',
'&::before': {
flip: false,
borderWidth: '1em 1em 1em 0',
borderColor: 'transparent currentcolor transparent transparent'
}
},
'&[x-placement*="left"] $arrow': {
flip: false,
right: 0,
marginRight: '-0.95em',
marginTop: 4,
marginBottom: 4,
height: '2em',
width: '1em',
'&::before': {
flip: false,
borderWidth: '1em 0 1em 1em',
borderColor: 'transparent transparent transparent currentcolor'
}
}
};
}
export var styles = function styles(theme) {
return {
/* Styles applied to the Popper component. */
popper: {
zIndex: theme.zIndex.tooltip,
pointerEvents: 'none',
flip: false // disable jss-rtl plugin
},
/* Styles applied to the Popper component if `interactive={true}`. */
popperInteractive: {
pointerEvents: 'auto'
},
/* Styles applied to the Popper component if `arrow={true}`. */
popperArrow: arrowGenerator(),
/* Styles applied to the tooltip (label wrapper) element. */
tooltip: {
backgroundColor: fade(theme.palette.grey[700], 0.9),
borderRadius: theme.shape.borderRadius,
color: theme.palette.common.white,
fontFamily: theme.typography.fontFamily,
padding: '4px 8px',
fontSize: theme.typography.pxToRem(10),
lineHeight: "".concat(round(14 / 10), "em"),
maxWidth: 300,
wordWrap: 'break-word',
fontWeight: theme.typography.fontWeightMedium
},
/* Styles applied to the tooltip (label wrapper) element if `arrow={true}`. */
tooltipArrow: {
position: 'relative',
margin: '0'
},
/* Styles applied to the arrow element. */
arrow: {
position: 'absolute',
fontSize: 6,
color: fade(theme.palette.grey[700], 0.9),
'&::before': {
content: '""',
margin: 'auto',
display: 'block',
width: 0,
height: 0,
borderStyle: 'solid'
}
},
/* Styles applied to the tooltip (label wrapper) element if the tooltip is opened by touch. */
touch: {
padding: '8px 16px',
fontSize: theme.typography.pxToRem(14),
lineHeight: "".concat(round(16 / 14), "em"),
fontWeight: theme.typography.fontWeightRegular
},
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "left". */
tooltipPlacementLeft: _defineProperty({
transformOrigin: 'right center',
margin: '0 24px '
}, theme.breakpoints.up('sm'), {
margin: '0 14px'
}),
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "right". */
tooltipPlacementRight: _defineProperty({
transformOrigin: 'left center',
margin: '0 24px'
}, theme.breakpoints.up('sm'), {
margin: '0 14px'
}),
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "top". */
tooltipPlacementTop: _defineProperty({
transformOrigin: 'center bottom',
margin: '24px 0'
}, theme.breakpoints.up('sm'), {
margin: '14px 0'
}),
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "bottom". */
tooltipPlacementBottom: _defineProperty({
transformOrigin: 'center top',
margin: '24px 0'
}, theme.breakpoints.up('sm'), {
margin: '14px 0'
})
};
};
var hystersisOpen = false;
var hystersisTimer = null;
export function testReset() {
hystersisOpen = false;
clearTimeout(hystersisTimer);
}
var Tooltip = React.forwardRef(function Tooltip(props, ref) {
var _props$arrow = props.arrow,
arrow = _props$arrow === void 0 ? false : _props$arrow,
children = props.children,
classes = props.classes,
_props$disableFocusLi = props.disableFocusListener,
disableFocusListener = _props$disableFocusLi === void 0 ? false : _props$disableFocusLi,
_props$disableHoverLi = props.disableHoverListener,
disableHoverListener = _props$disableHoverLi === void 0 ? false : _props$disableHoverLi,
_props$disableTouchLi = props.disableTouchListener,
disableTouchListener = _props$disableTouchLi === void 0 ? false : _props$disableTouchLi,
_props$enterDelay = props.enterDelay,
enterDelay = _props$enterDelay === void 0 ? 0 : _props$enterDelay,
_props$enterTouchDela = props.enterTouchDelay,
enterTouchDelay = _props$enterTouchDela === void 0 ? 700 : _props$enterTouchDela,
idProp = props.id,
_props$interactive = props.interactive,
interactive = _props$interactive === void 0 ? false : _props$interactive,
_props$leaveDelay = props.leaveDelay,
leaveDelay = _props$leaveDelay === void 0 ? 0 : _props$leaveDelay,
_props$leaveTouchDela = props.leaveTouchDelay,
leaveTouchDelay = _props$leaveTouchDela === void 0 ? 1500 : _props$leaveTouchDela,
onClose = props.onClose,
onOpen = props.onOpen,
openProp = props.open,
_props$placement = props.placement,
placement = _props$placement === void 0 ? 'bottom' : _props$placement,
PopperProps = props.PopperProps,
title = props.title,
_props$TransitionComp = props.TransitionComponent,
TransitionComponent = _props$TransitionComp === void 0 ? Grow : _props$TransitionComp,
TransitionProps = props.TransitionProps,
other = _objectWithoutProperties(props, ["arrow", "children", "classes", "disableFocusListener", "disableHoverListener", "disableTouchListener", "enterDelay", "enterTouchDelay", "id", "interactive", "leaveDelay", "leaveTouchDelay", "onClose", "onOpen", "open", "placement", "PopperProps", "title", "TransitionComponent", "TransitionProps"]);
var theme = useTheme();
var _React$useState = React.useState(),
childNode = _React$useState[0],
setChildNode = _React$useState[1];
var _React$useState2 = React.useState(null),
arrowRef = _React$useState2[0],
setArrowRef = _React$useState2[1];
var ignoreNonTouchEvents = React.useRef(false);
var closeTimer = React.useRef();
var enterTimer = React.useRef();
var leaveTimer = React.useRef();
var touchTimer = React.useRef();
var _useControlled = useControlled({
controlled: openProp,
default: false,
name: 'Tooltip'
}),
_useControlled2 = _slicedToArray(_useControlled, 2),
openState = _useControlled2[0],
setOpenState = _useControlled2[1];
var open = openState;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
var _React$useRef = React.useRef(openProp !== undefined),
isControlled = _React$useRef.current; // eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(function () {
if (childNode && childNode.disabled && !isControlled && title !== '' && childNode.tagName.toLowerCase() === 'button') {
console.error(['Material-UI: you are providing a disabled `button` child to the Tooltip component.', 'A disabled element does not fire events.', "Tooltip needs to listen to the child element's events to display the title.", '', 'Add a simple wrapper element, such as a `span`.'].join('\n'));
}
}, [title, childNode, isControlled]);
}
var _React$useState3 = React.useState(),
defaultId = _React$useState3[0],
setDefaultId = _React$useState3[1];
var id = idProp || defaultId;
React.useEffect(function () {
if (!open || defaultId) {
return;
} // Fallback to this default id when possible.
// Use the random value for client-side rendering only.
// We can't use it server-side.
setDefaultId("mui-tooltip-".concat(Math.round(Math.random() * 1e5)));
}, [open, defaultId]);
React.useEffect(function () {
return function () {
clearTimeout(closeTimer.current);
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
clearTimeout(touchTimer.current);
};
}, []);
var handleOpen = function handleOpen(event) {
clearTimeout(hystersisTimer);
hystersisOpen = true; // The mouseover event will trigger for every nested element in the tooltip.
// We can skip rerendering when the tooltip is already open.
// We are using the mouseover event instead of the mouseenter event to fix a hide/show issue.
setOpenState(true);
if (onOpen) {
onOpen(event);
}
};
var handleEnter = function handleEnter(event) {
var childrenProps = children.props;
if (event.type === 'mouseover' && childrenProps.onMouseOver && event.currentTarget === childNode) {
childrenProps.onMouseOver(event);
}
if (ignoreNonTouchEvents.current && event.type !== 'touchstart') {
return;
} // Remove the title ahead of time.
// We don't want to wait for the next render commit.
// We would risk displaying two tooltips at the same time (native + this one).
if (childNode) {
childNode.removeAttribute('title');
}
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
if (enterDelay && !hystersisOpen) {
event.persist();
enterTimer.current = setTimeout(function () {
handleOpen(event);
}, enterDelay);
} else {
handleOpen(event);
}
};
var _useIsFocusVisible = useIsFocusVisible(),
isFocusVisible = _useIsFocusVisible.isFocusVisible,
onBlurVisible = _useIsFocusVisible.onBlurVisible,
focusVisibleRef = _useIsFocusVisible.ref;
var _React$useState4 = React.useState(false),
childIsFocusVisible = _React$useState4[0],
setChildIsFocusVisible = _React$useState4[1];
var handleBlur = function handleBlur() {
if (childIsFocusVisible) {
setChildIsFocusVisible(false);
onBlurVisible();
}
};
var handleFocus = function handleFocus(event) {
// Workaround for https://github.com/facebook/react/issues/7769
// The autoFocus of React might trigger the event before the componentDidMount.
// We need to account for this eventuality.
if (!childNode) {
setChildNode(event.currentTarget);
}
if (isFocusVisible(event)) {
setChildIsFocusVisible(true);
handleEnter(event);
}
var childrenProps = children.props;
if (childrenProps.onFocus && event.currentTarget === childNode) {
childrenProps.onFocus(event);
}
};
var handleClose = function handleClose(event) {
clearTimeout(hystersisTimer);
hystersisTimer = setTimeout(function () {
hystersisOpen = false;
}, 500); // Use 500 ms per https://github.com/reach/reach-ui/blob/3b5319027d763a3082880be887d7a29aee7d3afc/packages/tooltip/src/index.js#L214
setOpenState(false);
if (onClose) {
onClose(event);
}
clearTimeout(closeTimer.current);
closeTimer.current = setTimeout(function () {
ignoreNonTouchEvents.current = false;
}, theme.transitions.duration.shortest);
};
var handleLeave = function handleLeave(event) {
var childrenProps = children.props;
if (event.type === 'blur') {
if (childrenProps.onBlur && event.currentTarget === childNode) {
childrenProps.onBlur(event);
}
handleBlur(event);
}
if (event.type === 'mouseleave' && childrenProps.onMouseLeave && event.currentTarget === childNode) {
childrenProps.onMouseLeave(event);
}
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
event.persist();
leaveTimer.current = setTimeout(function () {
handleClose(event);
}, leaveDelay);
};
var handleTouchStart = function handleTouchStart(event) {
ignoreNonTouchEvents.current = true;
var childrenProps = children.props;
if (childrenProps.onTouchStart) {
childrenProps.onTouchStart(event);
}
clearTimeout(leaveTimer.current);
clearTimeout(closeTimer.current);
clearTimeout(touchTimer.current);
event.persist();
touchTimer.current = setTimeout(function () {
handleEnter(event);
}, enterTouchDelay);
};
var handleTouchEnd = function handleTouchEnd(event) {
if (children.props.onTouchEnd) {
children.props.onTouchEnd(event);
}
clearTimeout(touchTimer.current);
clearTimeout(leaveTimer.current);
event.persist();
leaveTimer.current = setTimeout(function () {
handleClose(event);
}, leaveTouchDelay);
};
var handleUseRef = useForkRef(setChildNode, ref);
var handleFocusRef = useForkRef(focusVisibleRef, handleUseRef); // can be removed once we drop support for non ref forwarding class components
var handleOwnRef = React.useCallback(function (instance) {
// #StrictMode ready
setRef(handleFocusRef, ReactDOM.findDOMNode(instance));
}, [handleFocusRef]);
var handleRef = useForkRef(children.ref, handleOwnRef); // There is no point in displaying an empty tooltip.
if (title === '') {
open = false;
} // For accessibility and SEO concerns, we render the title to the DOM node when
// the tooltip is hidden. However, we have made a tradeoff when
// `disableHoverListener` is set. This title logic is disabled.
// It's allowing us to keep the implementation size minimal.
// We are open to change the tradeoff.
var shouldShowNativeTitle = !open && !disableHoverListener;
var childrenProps = _extends({
'aria-describedby': open ? id : null,
title: shouldShowNativeTitle && typeof title === 'string' ? title : null
}, other, {}, children.props, {
className: clsx(other.className, children.props.className)
});
if (!disableTouchListener) {
childrenProps.onTouchStart = handleTouchStart;
childrenProps.onTouchEnd = handleTouchEnd;
}
if (!disableHoverListener) {
childrenProps.onMouseOver = handleEnter;
childrenProps.onMouseLeave = handleLeave;
}
if (!disableFocusListener) {
childrenProps.onFocus = handleFocus;
childrenProps.onBlur = handleLeave;
}
var interactiveWrapperListeners = interactive ? {
onMouseOver: childrenProps.onMouseOver,
onMouseLeave: childrenProps.onMouseLeave,
onFocus: childrenProps.onFocus,
onBlur: childrenProps.onBlur
} : {};
if (process.env.NODE_ENV !== 'production') {
if (children.props.title) {
console.error(['Material-UI: you have provided a `title` prop to the child of <Tooltip />.', "Remove this title prop `".concat(children.props.title, "` or the Tooltip component.")].join('\n'));
}
} // Avoid the creation of a new Popper.js instance at each render.
var popperOptions = React.useMemo(function () {
return {
modifiers: {
arrow: {
enabled: Boolean(arrowRef),
element: arrowRef
}
}
};
}, [arrowRef]);
return React.createElement(React.Fragment, null, React.cloneElement(children, _extends({
ref: handleRef
}, childrenProps)), React.createElement(Popper, _extends({
className: clsx(classes.popper, interactive && classes.popperInteractive, arrow && classes.popperArrow),
placement: placement,
anchorEl: childNode,
open: childNode ? open : false,
id: childrenProps['aria-describedby'],
transition: true,
popperOptions: popperOptions
}, interactiveWrapperListeners, PopperProps), function (_ref) {
var placementInner = _ref.placement,
TransitionPropsInner = _ref.TransitionProps;
return React.createElement(TransitionComponent, _extends({
timeout: theme.transitions.duration.shorter
}, TransitionPropsInner, TransitionProps), React.createElement("div", {
className: clsx(classes.tooltip, classes["tooltipPlacement".concat(capitalize(placementInner.split('-')[0]))], ignoreNonTouchEvents.current && classes.touch, arrow && classes.tooltipArrow)
}, title, arrow ? React.createElement("span", {
className: classes.arrow,
ref: setArrowRef
}) : null));
}));
});
process.env.NODE_ENV !== "production" ? Tooltip.propTypes = {
/**
* If `true`, adds an arrow to the tooltip.
*/
arrow: PropTypes.bool,
/**
* Tooltip reference element.
*/
children: elementAcceptingRef.isRequired,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* Do not respond to focus events.
*/
disableFocusListener: PropTypes.bool,
/**
* Do not respond to hover events.
*/
disableHoverListener: PropTypes.bool,
/**
* Do not respond to long press touch events.
*/
disableTouchListener: PropTypes.bool,
/**
* The number of milliseconds to wait before showing the tooltip.
* This prop won't impact the enter touch delay (`enterTouchDelay`).
*/
enterDelay: PropTypes.number,
/**
* The number of milliseconds a user must touch the element before showing the tooltip.
*/
enterTouchDelay: PropTypes.number,
/**
* This prop is used to help implement the accessibility logic.
* If you don't provide this prop. It falls back to a randomly generated id.
*/
id: PropTypes.string,
/**
* Makes a tooltip interactive, i.e. will not close when the user
* hovers over the tooltip before the `leaveDelay` is expired.
*/
interactive: PropTypes.bool,
/**
* The number of milliseconds to wait before hiding the tooltip.
* This prop won't impact the leave touch delay (`leaveTouchDelay`).
*/
leaveDelay: PropTypes.number,
/**
* The number of milliseconds after the user stops touching an element before hiding the tooltip.
*/
leaveTouchDelay: PropTypes.number,
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* Callback fired when the component requests to be open.
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* If `true`, the tooltip is shown.
*/
open: PropTypes.bool,
/**
* Tooltip placement.
*/
placement: PropTypes.oneOf(['bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),
/**
* Props applied to the [`Popper`](/api/popper/) element.
*/
PopperProps: PropTypes.object,
/**
* Tooltip title. Zero-length titles string are never displayed.
*/
title: PropTypes.node.isRequired,
/**
* The component used for the transition.
* [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
*/
TransitionComponent: PropTypes.elementType,
/**
* Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element.
*/
TransitionProps: PropTypes.object
} : void 0;
export default withStyles(styles, {
name: 'MuiTooltip'
})(Tooltip); |
client/src/components/InfluenceComponent/InfluenceComponent.js | Taidine/masks-character-tracker | import React, { Component } from 'react';
import ReactTooltip from 'react-tooltip';
import EditableInput from '../EditableInput/EditableInput';
import './styles.css';
class InfluenceComponent extends Component {
constructor(props) {
super();
this.state = {
key: '',
};
}
componentWillReceiveProps (newProps, oldProps) {
if (newProps.influence !== oldProps.influence) {
this.setState({key: ''});
}
}
setKey = (key) => {
this.setState({key});
}
addInfluence = (key, name) => {
if (name !== ''){
let newInfluence = {};
newInfluence[key] = this.props.influence[key].concat([name]);
this.props.onSave(Object.assign({}, this.props.influence, newInfluence));
}
}
deleteInfluence = (key, index) => {
let oldInfluence = this.props.influence[key].slice();
oldInfluence.splice(index, 1);
let newInfluence = {};
newInfluence[key] = oldInfluence;
this.props.onSave(Object.assign({}, this.props.influence, newInfluence));
}
generateInfluenceRow = (name, i, key) => {
return (
<div className={i%2 ? "rowHighlight": "rowLowlight"} key={i}>
<span className={"tinyLink"} onClick={this.deleteInfluence.bind(this, key, i)}> [ - ] </span>
<span className={"influenceText"}>{name}</span>
</div>);
}
generateInfluenceFooter = (key) => {
return (
<div className={"influenceFooter"}>
{this.state.key === key
? <EditableInput initialValue={""} onSave={this.addInfluence.bind(this, key)} onRemove={this.setKey.bind(this, '')} />
: <span className={"tinyLink"} onClick={this.setKey.bind(this, key)}>[Add]</span>}
</div>);
}
render() {
return (
<div className={"influenceGroup"}>
<div className={"influenceColumn"}>
<div className={"subheader"}>{'Influence-ees (+1 against):'}</div>
{this.props.influence.on.map((name, i) => this.generateInfluenceRow(name, i, 'on'))}
{this.generateInfluenceFooter('on')}
</div>
<div className={"influenceColumn"}>
<div className={"subheader"}>{'Influencers:'}</div>
{this.props.influence.by.map((name, i) => this.generateInfluenceRow(name, i, 'by'))}
{this.generateInfluenceFooter('by')}
</div>
<div className={"influenceColumn"}>
<div className={"subheader"}>{'Cannot take influence: '}</div>
{this.props.influence.not.map((name, i) => this.generateInfluenceRow(name, i, 'not'))}
{this.generateInfluenceFooter('not')}
</div>
</div>
)
}
}
export default InfluenceComponent;
|
ajax/libs/rxjs/2.3.25/rx.lite.compat.js | CyrusSUEN/cdnjs | // 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(self) { if (self.isDisposed) { throw new Error(objectDisposed); } }
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])]; }
}
// 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;
}
// 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;
};
}
// Fix for Tessel
if (!Object.prototype.propertyIsEnumerable) {
Object.prototype.propertyIsEnumerable = function (key) {
for (var k in this) { if (k === key) { return true; } }
return false;
};
}
if (!Object.keys) {
Object.keys = (function() {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
// 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 = [];
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
}
this.disposables = args;
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;
for(var currentDisposables = [], i = 0, len = this.disposables.length; i < len; i++) { currentDisposables.push(this.disposables[i]); }
this.disposables = [];
this.length = 0;
for (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 () {
for(var currentDisposables = [], ix = 0, len = this.disposables.length; i < len; i++) { currentDisposables.push(this.disposables[i]); }
return currentDisposables;
};
/**
* 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;
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;
})();
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](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));
/** 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 = this.now() + 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) {
while (q.length > 0) {
var item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
!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 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;
}());
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);
})();
/**
* 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 (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 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);
};
/**
* 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 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__);
// 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 setDisposable(s, state) {
var ado = state[0], self = state[1];
try {
ado.setDisposable(fixSubscriber(self.subscribeCore(ado)));
} catch (e) {
if (!ado.fail(e)) { throw e; }
}
}
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 = function(observer) {
throw new Error('Not implemeneted');
}
return ObservableBase;
}(Observable));
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));
/**
* 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(
function (x) { arr.push(x); },
function (e) { observer.onError(e); },
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');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
var list = Object(iterable), it = getIterable(list);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
try {
var next = it.next();
} catch (e) {
observer.onError(e);
return;
}
if (next.done) {
observer.onCompleted();
return;
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
self(i + 1);
});
});
};
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler || currentThreadScheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
var FromArraySink = (function () {
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
function loopRecursive(state, recurse) {
if (state.i < state.len) {
state.observer.onNext(state.args[state.i++]);
recurse(state);
} else {
state.observer.onCompleted();
}
}
FromArraySink.prototype.run = function () {
return this.parent.scheduler.scheduleRecursiveWithState(
{i: 0, args: this.parent.args, len: this.parent.args.length, observer: this.observer },
loopRecursive);
};
return FromArraySink;
}());
/**
* 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) {
return new FromArrayObservable(array, scheduler)
};
/**
* 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 () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return observableOf(null, args);
};
/**
* 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) {
for(var args = [], i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return observableOf(scheduler, args);
};
/**
* 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();
}
});
});
};
/**
* 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.
* @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} 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);
};
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'] = 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 () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(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 () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
var 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);
},
function(e) { observer.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 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).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);
};
/**
* 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 (o) {
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(function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () {
group.remove(subscription);
if (q.length > 0) {
subscribe(q.shift());
} else {
activeCount--;
isStopped && activeCount === 0 && o.onCompleted();
}
}));
}
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, function (e) { o.onError(e); }, function () {
isStopped = true;
activeCount === 0 && o.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 = [], 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();
};
/**
* 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 (o) {
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(function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && o.onCompleted();
}));
}, function (e) { o.onError(e); }, function () {
isStopped = true;
group.length === 1 && o.onCompleted();
}));
return group;
}, sources);
};
/**
* @deprecated use #mergeAll instead.
*/
observableProto.mergeObservable = function () {
//deprecate('mergeObservable', 'mergeAll');
return this.mergeAll.apply(this, arguments);
};
/**
* 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 () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(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 () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
if (Array.isArray(args[0])) { return zipArray.apply(this, args); }
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 () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(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 {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(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);
};
/**
* 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, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
return new AnonymousObservable(function (observer) {
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) {
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) {
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);
};
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; });
};
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(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.index = 0;
this.isStopped = false;
}
MapObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
try {
var result = this.selector(x, this.index++, this.source);
} catch(e) {
return this.observer.onError(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(selector, 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 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 (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 RangeError(argumentOutOfRange); }
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(x, i, o); }, thisArg);
};
return FilterObservable;
}(ObservableBase));
function FilterObserver(observer, predicate, source) {
this.observer = observer;
this.predicate = predicate;
this.source = source;
this.index = 0;
this.isStopped = false;
}
FilterObserver.prototype.onNext = function(x) {
try {
var shouldYield = this.predicate(x, this.index++, this.source);
} catch(e) {
return this.observer.onError(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);
};
/**
* 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 () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return new AnonymousObservable(function (observer) {
function handler() {
var results = arguments;
if (selector) {
try {
results = selector(results);
} catch (err) {
return observer.onError(err);
}
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 () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
for(var results = [], i = 1, len = arguments.length; i < len; i++) { results.push(arguments[i]); }
if (selector) {
try {
results = selector(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 fixEvent(event) {
var stopPropagation = function () {
this.cancelBubble = true;
};
var preventDefault = function () {
this.bubbledKeyCode = this.keyCode;
if (this.ctrlKey) {
try {
this.keyCode = 0;
} catch (e) { }
}
this.defaultPrevented = true;
this.returnValue = false;
this.modified = true;
};
event || (event = root.event);
if (!event.target) {
event.target = event.target || event.srcElement;
if (event.type == 'mouseover') {
event.relatedTarget = event.fromElement;
}
if (event.type == 'mouseout') {
event.relatedTarget = event.toElement;
}
// Adding stopPropogation and preventDefault to IE
if (!event.stopPropagation) {
event.stopPropagation = stopPropagation;
event.preventDefault = preventDefault;
}
// Normalize key events
switch (event.type) {
case 'keypress':
var c = ('charCode' in event ? event.charCode : event.keyCode);
if (c == 10) {
c = 0;
event.keyCode = 13;
} else if (c == 13 || c == 27) {
c = 0;
} else if (c == 3) {
c = 99;
}
event.charCode = c;
event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : '';
break;
}
}
return event;
}
function createListener (element, name, handler) {
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
if (element.attachEvent) {
// IE Specific
var innerHandler = function (event) {
handler(fixEvent(event));
};
element.attachEvent('on' + name, innerHandler);
return disposableCreate(function () {
element.detachEvent('on' + name, innerHandler);
});
}
// Level 1 DOM Events
element['on' + name] = handler;
return disposableCreate(function () {
element['on' + name] = null;
});
}
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
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (!!root.Ember && typeof root.Ember.addListener === 'function') {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, 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) {
observer.onError(err);
return
}
}
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) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* 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);
});
});
};
/**
* 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);
}
/**
* 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 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 within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, window, 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, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
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));
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);
};
/**
* 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);
};
/**
* 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);
};
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;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
(!this.enableQueue || this.queue.length === 0) && this.subject.onCompleted();
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
(!this.enableQueue || this.queue.length === 0) && this.subject.onError(error);
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(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.subject.onNext(this.queue.shift());
numberOfItems--;
}
return this.queue.length !== 0 ?
{ numberOfItems: numberOfItems, returnValue: true } :
{ numberOfItems: numberOfItems, returnValue: false };
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
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);
};
/**
* 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 setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
try {
ado.setDisposable(fixSubscriber(subscribe(ado)));
} catch (e) {
if (!ado.fail(e)) { throw e; }
}
}
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 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));
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 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));
/**
* 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, {
/**
* 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__) {
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 ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : 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));
/**
* 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));
|
src/containers/DevTools.js | dfala/high-club | import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
export default createDevTools(
<DockMonitor
toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q' >
<LogMonitor theme='twilight' />
</DockMonitor>
)
|
node_modules/react-router/es6/RouterContext.js | Cole-Campbell/ReduxIntro | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import invariant from 'invariant';
import React from 'react';
import deprecateObjectProperties from './deprecateObjectProperties';
import getRouteParams from './getRouteParams';
import { isReactChildren } from './RouteUtils';
import warning from './routerWarning';
var _React$PropTypes = React.PropTypes;
var array = _React$PropTypes.array;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <RouterContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
var RouterContext = React.createClass({
displayName: 'RouterContext',
propTypes: {
history: object,
router: object.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired,
createElement: func.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
createElement: React.createElement
};
},
childContextTypes: {
history: object,
location: object.isRequired,
router: object.isRequired
},
getChildContext: function getChildContext() {
var _props = this.props;
var router = _props.router;
var history = _props.history;
var location = _props.location;
if (!router) {
process.env.NODE_ENV !== 'production' ? warning(false, '`<RouterContext>` expects a `router` rather than a `history`') : void 0;
router = _extends({}, history, {
setRouteLeaveHook: history.listenBeforeLeavingRoute
});
delete router.listenBeforeLeavingRoute;
}
if (process.env.NODE_ENV !== 'production') {
location = deprecateObjectProperties(location, '`context.location` is deprecated, please use a route component\'s `props.location` instead. http://tiny.cc/router-accessinglocation');
}
return { history: history, location: location, router: router };
},
createElement: function createElement(component, props) {
return component == null ? null : this.props.createElement(component, props);
},
render: function render() {
var _this = this;
var _props2 = this.props;
var history = _props2.history;
var location = _props2.location;
var routes = _props2.routes;
var params = _props2.params;
var components = _props2.components;
var element = null;
if (components) {
element = components.reduceRight(function (element, components, index) {
if (components == null) return element; // Don't create new children; use the grandchildren.
var route = routes[index];
var routeParams = getRouteParams(route, params);
var props = {
history: history,
location: location,
params: params,
route: route,
routeParams: routeParams,
routes: routes
};
if (isReactChildren(element)) {
props.children = element;
} else if (element) {
for (var prop in element) {
if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop];
}
}
if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') {
var elements = {};
for (var key in components) {
if (Object.prototype.hasOwnProperty.call(components, key)) {
// Pass through the key as a prop to createElement to allow
// custom createElement functions to know which named component
// they're rendering, for e.g. matching up to fetched data.
elements[key] = _this.createElement(components[key], _extends({
key: key }, props));
}
}
return elements;
}
return _this.createElement(components, props);
}, element);
}
!(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0;
return element;
}
});
export default RouterContext; |
vendor/ngReact/karma.config.js | jzinma/jzinma.github.io | module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '.',
frameworks: ['jasmine', 'browserify'],
// list of files / patterns to load in the browser
files: [
'node_modules/angular/angular.js',
'ngReact.js',
'tests/*.js'
],
preprocessors: {
'tests/*.js': ['browserify']
},
browserify: {
debug: true,
transform: [['reactify', {'es6': true}], 'browserify-shim'],
extensions: ['.js']
},
// list of files to exclude
exclude: [ ],
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress'
// CLI --reporters progress
reporters: ['progress'],
// web server port
// CLI --port 9876
port: 9876,
// cli runner port
runnerPort : 9100,
// enable / disable colors in the output (reporters and logs)
// CLI --colors --no-colors
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
// CLI --log-level debug
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
// CLI --browsers Chrome,Firefox,Safari
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// Auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: false,
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
plugins: [
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-browserify'
]
});
}; |
redux/todoList/src/components/todoInput/todoInput.js | yuanzhaokang/myAwesomeSimpleDemo | import { ADD_LIST } from '../todoList/actions';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './todoInput.scss';
class TodoInput extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
}
render() {
return (
<div className='outter'>
<div className='input-outter'>
<div className='title'>ToDoList</div>
<input value={this.state.value}
onChange={(e) => {
this.setState({
value: e.target.value
});
}}
onKeyDown={(e) => {
this.props.onKeyDown(e, this.state.value);
}}
/>
</div>
</div>
);
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onKeyDown: (e, value) => {
if (e.nativeEvent.keyCode == 13) {
dispatch({
type: ADD_LIST,
text: value
});
}
}
}
}
export default connect(
null,
mapDispatchToProps
)(TodoInput); |
src/S1/index.js | raffidil/garnanain | import React from 'react';
import {
IconButton,
Grid,
Cell,
Dialog,
DialogTitle,
DialogContent,
Icon,
Spinner,
} from 'react-mdl';
import { shuffle } from 'underscore';
import Layout from '../../components/Layout';
import ResultDialog from '../../components/ResultDialog';
import s from '../Questionstyles.css';
import AnswerCard from '../../components/AnswerCard';
import history from '../history';
import Timer from '../../components/Timer';
import Questions from './questions';
import time from './time.gif';
export default class Question extends React.Component {
constructor(props) {
super(props);
this.state = {
openDialogCorrect: false,
openDialogWrong: false,
openDialogWait: false,
reveal: false,
pauseTimer: false,
};
}
componentWillMount() {
const id = parseInt(this.props.route.params.id, 10);
this.question = Questions[id];
this.answers = shuffle(this.question.answers);
}
componentDidMount() {
document.title = this.question.id;
}
showResult = (correct) => {
this.setState({
openDialogCorrect: correct,
openDialogWrong: !correct,
openDialogWait: false,
reveal: true,
});
}
answer = (correct) => {
this.setState({ openDialogWait: true, pauseTimer: true });
setTimeout(this.showResult, 2500, correct);
}
gotoScience = () => {
history.push({ pathname: '/science' });
}
render() {
return (
<Layout className={s.content}>
<h1 className={s.fontstyle1} style={{ marginTop: '55px' }}>
<Grid className="demo-grid-1" style={{ marginTop: '20px' }}>
<Cell col={1}>
<IconButton name="arrow_back" colored onClick={this.gotoScience} />
</Cell>
<Cell col={11} className={s.ScienceQuestionFont}>{this.question.text}</Cell>
</Grid>
</h1>
<Grid style={{ fontSize: '30px', marginTop: '50px', marginBottom: '-47px' }} className="demo-grid-1">
<Cell offset={1} col={1} style={{ zIndex: '2' }}>
<Icon style={{ color: '#E91E63', fontSize: '60px', marginLeft: '90px' }} name="looks_one" />
</Cell>
<Cell offset={2} col={1} style={{ zIndex: '2' }}>
<Icon style={{ color: '#E91E63', fontSize: '60px', marginLeft: '90px' }} name="looks_two" />
</Cell>
<Cell offset={2} col={1} style={{ zIndex: '2' }}>
<Icon style={{ color: '#E91E63', fontSize: '60px', marginLeft: '90px' }} name="looks_3" />
</Cell>
<Cell offset={2} col={1} style={{ zIndex: '2' }}>
<Icon style={{ color: '#E91E63', fontSize: '60px', marginLeft: '90px' }} name="looks_4" />
</Cell>
</Grid>
<Grid style={{ marginLeft: '-10px' }} className="demo-grid-1">
{this.answers.map((answer, i) =>
(
<Cell col={3} key={i}>
<AnswerCard
color={(this.state.reveal && answer.correct) ? '#2E7D32' : '#0d47a1'}
text={answer.text}
onClick={() => this.answer(answer.correct)}
fontSize={answer.fontSize}
/>
</Cell>
))}
</Grid>
<div style={{ marginLeft: '299px', marginTop: '15px' }}> <Timer timeout={25} pause={this.state.pauseTimer} /></div>
<Dialog style={{ textAlign: 'center', background: `url(${time}) center / cover`, minHeight: '200px' }} open={this.state.openDialogWait}>
</Dialog>
<ResultDialog score="5" correct={this.state.openDialogCorrect} wrong={this.state.openDialogWrong} />
</Layout>
);
}
}
|
src/parser/hunter/survival/modules/spells/WildfireBomb.js | fyruna/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import { formatPercentage } from 'common/format';
import StatisticBox from 'interface/others/StatisticBox';
import SpellIcon from 'common/SpellIcon';
import Enemies from 'parser/shared/modules/Enemies';
import SpellUsable from 'parser/shared/modules/SpellUsable';
import StatTracker from 'parser/shared/modules/StatTracker';
import SpellLink from 'common/SpellLink';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
import GlobalCooldown from 'parser/shared/modules/GlobalCooldown';
/**
* Hurl a bomb at the target, exploding for (45% of Attack power) Fire
* damage in a cone and coating enemies in wildfire, scorching them for (90%
* of Attack power) Fire damage over 6 sec.
*
* Example log: https://www.warcraftlogs.com/reports/pNJbYdLrMW2ynKGa#fight=3&type=damage-done&source=16&translate=true
*/
const GCD_BUFFER = 500; //People aren't robots, give them a bit of leeway in terms of when they cast WFB to avoid capping on charges
const MS_BUFFER = 200;
class WildfireBomb extends Analyzer {
static dependencies = {
enemies: Enemies,
spellUsable: SpellUsable,
statTracker: StatTracker,
globalCooldown: GlobalCooldown,
};
acceptedCastDueToCapping = false;
currentGCD = 0;
badRefreshes = 0;
lastRefresh = 0;
casts = 0;
targetsHit = 0;
constructor(...args) {
super(...args);
this.active = !this.selectedCombatant.hasTalent(SPELLS.WILDFIRE_INFUSION_TALENT.id);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.WILDFIRE_BOMB.id) {
return;
}
this.casts += 1;
this.currentGCD = this.globalCooldown.getGlobalCooldownDuration(spellId);
if (!this.spellUsable.isOnCooldown(SPELLS.WILDFIRE_BOMB.id) || this.spellUsable.cooldownRemaining(SPELLS.WILDFIRE_BOMB.id) < GCD_BUFFER + this.currentGCD) {
this.acceptedCastDueToCapping = true;
}
}
on_byPlayer_damage(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.WILDFIRE_BOMB_IMPACT.id) {
return;
}
if (this.casts === 0) {
this.casts += 1;
this.spellUsable.beginCooldown(SPELLS.WILDFIRE_BOMB.id, {
timestamp: this.owner.fight.start_time,
});
}
this.targetsHit++;
const enemy = this.enemies.getEntity(event);
if (this.acceptedCastDueToCapping || !enemy) {
return;
}
if (enemy.hasBuff(SPELLS.WILDFIRE_BOMB_DOT.id) && event.timestamp > this.lastRefresh + MS_BUFFER) {
this.badRefreshes++;
this.lastRefresh = event.timestamp;
}
}
get uptimePercentage() {
return this.enemies.getBuffUptime(SPELLS.WILDFIRE_BOMB_DOT.id) / this.owner.fightDuration;
}
get badWFBThresholds() {
return {
actual: this.badRefreshes,
isGreaterThan: {
minor: 2,
average: 4,
major: 6,
},
style: 'number',
};
}
get uptimeThresholds() {
return {
actual: this.uptimePercentage,
isLessThan: {
minor: 0.4,
average: 0.35,
major: 0.3,
},
style: 'percent',
};
}
suggestions(when) {
when(this.badWFBThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(<>You shouldn't refresh <SpellLink id={SPELLS.WILDFIRE_BOMB.id} /> since it doesn't pandemic. It's generally better to cast something else and wait for the DOT to drop off before reapplying.</>)
.icon(SPELLS.WILDFIRE_BOMB.icon)
.actual(`${actual} casts unnecessarily refreshed WFB`)
.recommended(`<${recommended} is recommended`);
});
when(this.uptimeThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(<>Try and maximize your uptime on <SpellLink id={SPELLS.WILDFIRE_BOMB.id} />. This is achieved through not unnecessarily refreshing the debuff as it doesn't pandemic. </>)
.icon(SPELLS.WILDFIRE_BOMB.icon)
.actual(`${formatPercentage(actual)}% uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`);
});
}
get averageTargetsHit() {
return (this.targetsHit / this.casts).toFixed(2);
}
statistic() {
return (
<StatisticBox
position={STATISTIC_ORDER.CORE(20)}
icon={<SpellIcon id={SPELLS.WILDFIRE_BOMB.id} />}
value={this.averageTargetsHit}
label="Average targets hit"
tooltip={`You had an uptime of ${formatPercentage(this.uptimePercentage)}% on the DoT from Wildfire Bomb.`}
/>
);
}
}
export default WildfireBomb;
|
client/modules/App/components/DevTools.js | CODEINAE/todoy | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-w"
>
<LogMonitor />
</DockMonitor>
);
|
test/componets-test.js | Trivardy/Trivardy | import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import sinon from 'sinon';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import TestUtils from 'react-addons-test-utils';
import FetchBar from '../public/client/components/random_categories';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('<FetchBar/>', function() {
const initialState = {
messages: [],
username: null,
canEdit: true
};
const store = mockStore(initialState);
const wrapper = mount(<Provider store={store}><FetchBar onClick={this.submit}/></Provider>);
it('category test' , function() {
expect(wrapper.find('div').hasClass('test')).to.equal(true);
});
});
// describe('<Header />', () => {
// const initialState = {}
// const store = mockStore(initialState)
// const props = {
// loginStatus:null,
// dispatch: () => {},
// authenticated: null,
// username: null,
// }
// const wrapper = mount(<Provider store={store}><Header /></Provider>);
//
// it('allows us to set props', () => {
// expect(
// wrapper.find('div')
// )
// });
//
// after(function() {
// global.window.close();
// });
// });
|
src/CollapsibleMixin.js | PeterDaveHello/react-bootstrap | import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
import deprecationWarning from './utils/deprecationWarning';
let warned = false;
const CollapsibleMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState(){
let defaultExpanded = this.props.defaultExpanded != null ?
this.props.defaultExpanded :
this.props.expanded != null ?
this.props.expanded :
false;
return {
expanded: defaultExpanded,
collapsing: false
};
},
componentWillMount(){
if ( !warned ){
deprecationWarning('CollapsibleMixin', 'Collapse Component');
warned = true;
}
},
componentWillUpdate(nextProps, nextState){
let willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded;
if (willExpanded === this.isExpanded()) {
return;
}
// if the expanded state is being toggled, ensure node has a dimension value
// this is needed for the animation to work and needs to be set before
// the collapsing class is applied (after collapsing is applied the in class
// is removed and the node's dimension will be wrong)
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = '0';
if(!willExpanded){
value = this.getCollapsibleDimensionValue();
}
node.style[dimension] = value + 'px';
this._afterWillUpdate();
},
componentDidUpdate(prevProps, prevState){
// check if expanded is being toggled; if so, set collapsing
this._checkToggleCollapsing(prevProps, prevState);
// check if collapsing was turned on; if so, start animation
this._checkStartAnimation();
},
// helps enable test stubs
_afterWillUpdate(){
},
_checkStartAnimation(){
if(!this.state.collapsing) {
return;
}
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = this.getCollapsibleDimensionValue();
// setting the dimension here starts the transition animation
let result;
if(this.isExpanded()) {
result = value + 'px';
} else {
result = '0px';
}
node.style[dimension] = result;
},
_checkToggleCollapsing(prevProps, prevState){
let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded;
let isExpanded = this.isExpanded();
if(wasExpanded !== isExpanded){
if(wasExpanded) {
this._handleCollapse();
} else {
this._handleExpand();
}
}
},
_handleExpand(){
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let complete = () => {
this._removeEndEventListener(node, complete);
// remove dimension value - this ensures the collapsible item can grow
// in dimension after initial display (such as an image loading)
node.style[dimension] = '';
this.setState({
collapsing:false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
_handleCollapse(){
let node = this.getCollapsibleDOMNode();
let complete = () => {
this._removeEndEventListener(node, complete);
this.setState({
collapsing: false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
// helps enable test stubs
_addEndEventListener(node, complete){
TransitionEvents.addEndEventListener(node, complete);
},
// helps enable test stubs
_removeEndEventListener(node, complete){
TransitionEvents.removeEndEventListener(node, complete);
},
dimension(){
return (typeof this.getCollapsibleDimension === 'function') ?
this.getCollapsibleDimension() :
'height';
},
isExpanded(){
return this.props.expanded != null ? this.props.expanded : this.state.expanded;
},
getCollapsibleClassSet(className) {
let classes = {};
if (typeof className === 'string') {
className.split(' ').forEach(subClasses => {
if (subClasses) {
classes[subClasses] = true;
}
});
}
classes.collapsing = this.state.collapsing;
classes.collapse = !this.state.collapsing;
classes.in = this.isExpanded() && !this.state.collapsing;
return classes;
}
};
export default CollapsibleMixin;
|
ajax/libs/preact/5.0.1-beta.14/preact.min.js | jdh8/cdnjs | !function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(e.preact=e.preact||{})}(this,function(e){function n(e,n,t){this.nodeName=e,this.attributes=n,this.children=t,this.key=n&&n.key}function t(e,n){if(n)for(var t in n)e[t]=n[t];return e}function r(e){return t({},e)}function o(e){var n={};return function(t){return n[t]||(n[t]=e(t))}}function i(e,n){for(var t=n.split("."),r=0;t.length>r&&e;r++)e=e[t[r]];return e}function a(e,n){return[].slice.call(e,n)}function c(e){return"function"==typeof e}function s(e){return"string"==typeof e}function u(e){return void 0===e||null===e}function l(e){return e===!1||u(e)}function f(e){var n="";for(var t in e){var r=e[t];u(r)||(n&&(n+=" "),n+=ce(t),n+=": ",n+=r,"number"!=typeof r||ae[t]||(n+="px"),n+=";")}return n}function p(e){var n="";for(var t in e)e[t]&&(n&&(n+=" "),n+=t);return n}function d(e,n){return v(fe,e,n)}function v(e,n,t,r,o){return e[n]?e[n](t,r,o):void 0}function h(e,n){do v(e,n);while(e=e._component)}function m(e,t,r){var o,i,a,u=arguments.length;if(u>2){var v=typeof r;if(3===u&&"object"!==v&&"function"!==v)l(r)||(o=[r+""]);else{o=[];for(var h=2;u>h;h++){var _=arguments[h];if(!l(_)){_.join?i=_:(i=pe)[0]=_;for(var y=0;i.length>y;y++){var b=i[y],C=!(l(b)||c(b)||b instanceof n);C&&!s(b)&&(b+=""),C&&a?o[o.length-1]+=b:l(b)||o.push(b),a=C}}}}}else if(t){if(t.children)return m(e,t,t.children);c(e)||("className"in t&&(t.class=t.className,delete t.className),a=t.class,a&&!s(a)&&(t.class=p(a)),a=t.style,a&&!s(a)&&(t.style=f(a)))}var g=new n(e,t||void 0,o);return d("vnode",g),g}function _(e,n){return m(e.nodeName,t(r(e.attributes),n),arguments.length>2?a(arguments,2):e.children)}function y(e,n,t){var r=n.split("."),o=r[0],a=r.length;return function(n){var l,f,p,d=n&&n.currentTarget||this,v=e.state,h=v;if(s(t)?(f=i(n,t),u(f)&&(d=d._component)&&(f=i(d,t))):f=(d.nodeName+d.type).match(/^input(check|rad)/i)?d.checked:d.value,c(f)&&(f=f.call(d)),a>1){for(p=0;a-1>p;p++)h=h[r[p]]||(h[r[p]]={});h[r[p]]=f,f=v[o]}e.setState((l={},l[o]=f,l))}}function b(e){1===de.push(e)&&(fe.debounceRendering||le)(C)}function C(){if(de.length){var e,n=de;de=ve,ve=n;while(e=n.pop())e._dirty&&$(e)}}function g(e){var n=e&&e.nodeName;return n&&c(n)&&!(n.prototype&&n.prototype.render)}function x(e,n){return e.nodeName(W(e),n||re)||oe}function N(e,n){return e[ie]||(e[ie]=n||{})}function k(e){return e instanceof Text?3:e instanceof Element?1:0}function S(e){var n=e.parentNode;n&&n.removeChild(e)}function w(e,n,t){if(N(e)[n]=t,"key"!==n&&"children"!==n)if("class"===n)e.className=t||"";else if("style"===n)e.style.cssText=t||"";else if("dangerouslySetInnerHTML"===n)t&&t.__html&&(e.innerHTML=t.__html);else if("type"!==n&&n in e)M(e,n,u(t)?"":t),l(t)&&e.removeAttribute(n);else if("o"===n[0]&&"n"===n[1]){var r=e._listeners||(e._listeners={});n=se(n.substring(2)),r[n]?t||e.removeEventListener(n,P):e.addEventListener(n,P),r[n]=t}else l(t)?e.removeAttribute(n):"object"==typeof t||c(t)||e.setAttribute(n,t)}function M(e,n,t){try{e[n]=t}catch(r){}}function P(e){return this._listeners[se(e.type)](d("event",e)||e)}function T(e){for(var n={},t=e.attributes.length;t--;)n[e.attributes[t].name]=e.attributes[t].value;return n}function R(e,n){if(s(n))return 3===k(e);var t=n.nodeName,r=typeof t;return"string"===r?U(e,t):"function"===r?e._componentConstructor===t||g(n):void 0}function U(e,n){return(e.normalizedNodeName||se(e.nodeName))===se(n)}function W(e){var n=e.nodeName.defaultProps,o=r(n||e.attributes);return n&&t(o,e.attributes),e.children&&(o.children=e.children),o}function B(e){E(e);var n=se(e.nodeName),t=he[n];t?t.push(e):he[n]=[e]}function D(e){var n=se(e),t=he[n],r=t&&t.pop()||document.createElement(e);return N(r),r.normalizedNodeName=n,r}function E(e){S(e),3!==k(e)&&(N(e,T(e)),e._component=e._componentConstructor=null)}function L(e,n,t,r,o){var i=n.attributes;while(g(n))n=x(n,t);if(s(n)){if(e){if(3===k(e))return e.nodeValue!==n&&(e.nodeValue=n),e;o||B(e)}return document.createTextNode(n)}if(c(n.nodeName))return q(e,n,t,r);var a=e,u=n.nodeName;if(s(u)||(u+=""),e){if(!U(e,u)){a=D(u);while(e.firstChild)a.appendChild(e.firstChild);o||I(e)}}else a=D(u);return j(a,n.children,t,r),V(a,n.attributes),i&&i.ref&&(a[ie].ref=i.ref)(a),a}function j(e,n,t,r){var o=e.firstChild;n&&1===n.length&&"string"==typeof n[0]&&o instanceof Text&&1===e.childNodes.length?o.nodeValue=n[0]:(n||o)&&A(e,n,t,r)}function z(e){var n=e._component;if(n)return n.__key;var t=e[ie];return t?t.key:void 0}function A(e,n,t,r){var o,i,a=e.childNodes,c=0,s=0,l=a.length,f=0;if(l){o=[];for(var p=0;l>p;p++){var d=a[p],v=z(d);v||0===v?(c++||(i={}),i[v]=d):o[f++]=d}}if(n)for(var p=0;n.length>p;p++){var d,m=n[p];if(c&&m.attributes){var v=m.key;!u(v)&&v in i&&(d=i[v],i[v]=void 0,c--)}if(!d&&f>s)for(var _=s;f>_;_++){var y=o[_];if(y&&R(y,m)){d=y,o[_]=void 0,_===f-1&&f--,_===s&&s++;break}}d=L(d,m,t,r);var b=(r||d.parentNode!==e)&&d._component;b&&h(b,"componentWillMount");var C=a[p];C!==d&&(C?e.insertBefore(d,C):e.appendChild(d)),b&&h(b,"componentDidMount")}if(c)for(var p in i)i[p]&&(o[s=f++]=i[p]);f>s&&H(o)}function H(e,n){for(var t=e.length;t--;){var r=e[t];r&&I(r,n)}}function I(e,n){var t=e[ie];t&&v(t,"ref",null);var r=e._component;if(r)K(r,!n);else{if(!n){if(1!==k(e))return void S(e);B(e)}var o=e.childNodes;o&&o.length&&H(o,n)}}function V(e,n){var t=e[ie]||T(e);for(var r in t)n&&r in n||w(e,r,null);if(n)for(var o in n){var i=n[o];void 0===i&&(i=null),o in t&&i==t[o]||w(e,o,i)}}function F(e){var n=e.constructor.name,t=me[n];t?t.push(e):me[n]=[e]}function G(e,n,t,r){var o=new e(n,t),i=!r&&me[e.name];if(i)for(var a=0;i.length>a;a++)if(i[a].constructor===e){o.nextBase=i[a].base,i.splice(a,1);break}return o}function O(e){e._dirty||(e._dirty=!0,b(e))}function Z(e,n,t,r,o){var i=e._disableRendering===!0;e._disableRendering=!0,(e.__ref=n.ref)&&delete n.ref,(e.__key=n.key)&&delete n.key,u(e.base)||v(e,"componentWillReceiveProps",n,r),r&&r!==e.context&&(e.prevContext||(e.prevContext=e.context),e.context=r),e.prevProps||(e.prevProps=e.props),e.props=n,e._disableRendering=i,t!==ee&&(t===ne||fe.syncComponentUpdates!==!1?$(e,ne,o):O(e)),v(e,"__ref",e)}function $(e,n,o){if(!e._disableRendering){var i,a,s=e.props,u=e.state,l=e.context,f=e.prevProps||s,p=e.prevState||u,d=e.prevContext||l,m=e.base,_=m||e.nextBase,y=_&&_._component;if(m&&(e.props=f,e.state=p,e.context=d,n!==te&&v(e,"shouldComponentUpdate",s,u,l)===!1?i=!0:v(e,"componentWillUpdate",s,u,l),e.props=s,e.state=u,e.context=l),e.prevProps=e.prevState=e.prevContext=e.nextBase=null,e._dirty=!1,!i){a=v(e,"render",s,u,l),e.getChildContext&&(l=t(r(l),e.getChildContext()));while(g(a))a=x(a,l);var b,C,N=a&&a.nodeName;if(c(N)&&N.prototype.render){var k=e._component;k&&k.constructor!==N&&(b=k,k=null);var S=W(a);k?Z(k,S,ne,l):(k=G(N,S,l,!1),k._parentComponent=e,e._component=k,m&&h(k,"componentWillMount"),Z(k,S,ee,l),$(k,ne),m&&h(k,"componentDidMount")),C=k.base}else{var w=_;b=e._component,b&&(w=e._component=null),(_||n===ne)&&(w&&(w._component=null),C=L(w,a||oe,l,o||!m,!0))}if(_&&C!==_){var M=_.parentNode;M&&C!==M&&M.replaceChild(C,_),b||y!==e||I(_)}if(b&&K(b,!0),e.base=C,C){var P=e,T=e;while(T=T._parentComponent)P=T;C._component=P,C._componentConstructor=P.constructor}m&&v(e,"componentDidUpdate",f,p,d)}var R,U=e._renderCallbacks;if(U)while(R=U.pop())R.call(e);return a}}function q(e,n,t,r){var o=e&&e._component,i=e,a=o&&e._componentConstructor===n.nodeName,c=a;while(o&&!c&&(o=o._parentComponent))c=o.constructor===n.nodeName;return!c||r&&!o._component?(o&&!a&&(K(o,!0),e=i=null),e=J(n,e,t,r),i&&e!==i&&(i._component=null,I(i))):(Z(o,W(n),ne,t,r),e=o.base),e}function J(e,n,t,r){var o=W(e),i=G(e.nodeName,o,t,!!n);return n&&(i.nextBase=n),Z(i,o,ne,t,r),i.base}function K(e,n){v(e,"__ref",null),v(e,"componentWillUnmount");var t=e._component;t&&(K(t,n),n=!1);var r=e.base;r&&(n!==!1&&S(r),H(r.childNodes,!0)),n&&(e._parentComponent=null,F(e)),v(e,"componentDidUnmount")}function Q(e,n){this._dirty=!0,this._disableRendering=!1,this.prevState=this.prevProps=this.prevContext=this.base=this.nextBase=this._parentComponent=this._component=this.__ref=this.__key=this._linkedStates=this._renderCallbacks=null,this.context=n||{},this.props=e,this.state=v(this,"getInitialState")||{}}function X(e,n,t){var r=t&&t._component&&t._componentConstructor===e.nodeName,o=L(t,e,{},!1),i=!r&&o._component;return i&&h(i,"componentWillMount"),o.parentNode!==n&&n.appendChild(o),i&&h(i,"componentDidMount"),o}var Y,ee=0,ne=1,te=2,re={},oe="",ie="undefined"!=typeof Symbol?Symbol.for("preactattr"):"__preactattr_",ae={boxFlex:1,boxFlexGroup:1,columnCount:1,fillOpacity:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,fontWeight:1,lineClamp:1,lineHeight:1,opacity:1,order:1,orphans:1,strokeOpacity:1,widows:1,zIndex:1,zoom:1},ce=o(function(e){return se(e.replace(/([A-Z])/g,"-$1"))}),se=o(function(e){return e.toLowerCase()});try{Y=new MessageChannel}catch(ue){}var le=Y?function(e){Y.port1.onmessage=e,Y.port2.postMessage(oe)}:setTimeout,fe={vnode:u},pe=[],de=[],ve=[],he={},me={};t(Q.prototype,{linkState:function(e,n){var t=this._linkedStates||(this._linkedStates={}),r=e+"|"+n;return t[r]||(t[r]=y(this,e,n))},setState:function(e,n){var o=this.state;this.prevState||(this.prevState=r(o)),t(o,c(e)?e(o,this.props):e),n&&(this._renderCallbacks=this._renderCallbacks||[]).push(n),O(this)},forceUpdate:function(){$(this,te)},render:function(){return null}}),e.h=m,e.cloneElement=_,e.Component=Q,e.render=X,e.rerender=C,e.options=fe});
//# sourceMappingURL=preact.min.js.map |
docs/js/apache-maven-fluido-1.6.min.js | daverix/zxing | /*!
* jQuery JavaScript Library v1.11.2
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-17T15:27Z
*/
(function(b,a){if(typeof module==="object"&&typeof module.exports==="object"){module.exports=b.document?a(b,true):function(c){if(!c.document){throw new Error("jQuery requires a window with a document")}return a(c)}}else{a(b)}}(typeof window!=="undefined"?window:this,function(a5,av){var aP=[];var P=aP.slice;var az=aP.concat;var x=aP.push;var bU=aP.indexOf;var ac={};var y=ac.toString;var K=ac.hasOwnProperty;var D={};var ai="1.11.2",bI=function(e,i){return new bI.fn.init(e,i)},E=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,bS=/^-ms-/,aW=/-([\da-z])/gi,O=function(e,i){return i.toUpperCase()};bI.fn=bI.prototype={jquery:ai,constructor:bI,selector:"",length:0,toArray:function(){return P.call(this)},get:function(e){return e!=null?(e<0?this[e+this.length]:this[e]):P.call(this)},pushStack:function(e){var i=bI.merge(this.constructor(),e);i.prevObject=this;i.context=this.context;return i},each:function(i,e){return bI.each(this,i,e)},map:function(e){return this.pushStack(bI.map(this,function(b7,b6){return e.call(b7,b6,b7)}))},slice:function(){return this.pushStack(P.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(b7){var e=this.length,b6=+b7+(b7<0?e:0);return this.pushStack(b6>=0&&b6<e?[this[b6]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:x,sort:aP.sort,splice:aP.splice};bI.extend=bI.fn.extend=function(){var e,cb,b6,b7,ce,cc,ca=arguments[0]||{},b9=1,b8=arguments.length,cd=false;if(typeof ca==="boolean"){cd=ca;ca=arguments[b9]||{};b9++}if(typeof ca!=="object"&&!bI.isFunction(ca)){ca={}}if(b9===b8){ca=this;b9--}for(;b9<b8;b9++){if((ce=arguments[b9])!=null){for(b7 in ce){e=ca[b7];b6=ce[b7];if(ca===b6){continue}if(cd&&b6&&(bI.isPlainObject(b6)||(cb=bI.isArray(b6)))){if(cb){cb=false;cc=e&&bI.isArray(e)?e:[]}else{cc=e&&bI.isPlainObject(e)?e:{}}ca[b7]=bI.extend(cd,cc,b6)}else{if(b6!==undefined){ca[b7]=b6}}}}}return ca};bI.extend({expando:"jQuery"+(ai+Math.random()).replace(/\D/g,""),isReady:true,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return bI.type(e)==="function"},isArray:Array.isArray||function(e){return bI.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return !bI.isArray(e)&&(e-parseFloat(e)+1)>=0},isEmptyObject:function(i){var e;for(e in i){return false}return true},isPlainObject:function(b7){var i;if(!b7||bI.type(b7)!=="object"||b7.nodeType||bI.isWindow(b7)){return false}try{if(b7.constructor&&!K.call(b7,"constructor")&&!K.call(b7.constructor.prototype,"isPrototypeOf")){return false}}catch(b6){return false}if(D.ownLast){for(i in b7){return K.call(b7,i)}}for(i in b7){}return i===undefined||K.call(b7,i)},type:function(e){if(e==null){return e+""}return typeof e==="object"||typeof e==="function"?ac[y.call(e)]||"object":typeof e},globalEval:function(e){if(e&&bI.trim(e)){(a5.execScript||function(i){a5["eval"].call(a5,i)})(e)}},camelCase:function(e){return e.replace(bS,"ms-").replace(aW,O)},nodeName:function(i,e){return i.nodeName&&i.nodeName.toLowerCase()===e.toLowerCase()},each:function(ca,cb,b6){var b9,b7=0,b8=ca.length,e=ad(ca);if(b6){if(e){for(;b7<b8;b7++){b9=cb.apply(ca[b7],b6);if(b9===false){break}}}else{for(b7 in ca){b9=cb.apply(ca[b7],b6);if(b9===false){break}}}}else{if(e){for(;b7<b8;b7++){b9=cb.call(ca[b7],b7,ca[b7]);if(b9===false){break}}}else{for(b7 in ca){b9=cb.call(ca[b7],b7,ca[b7]);if(b9===false){break}}}}return ca},trim:function(e){return e==null?"":(e+"").replace(E,"")},makeArray:function(e,b6){var i=b6||[];if(e!=null){if(ad(Object(e))){bI.merge(i,typeof e==="string"?[e]:e)}else{x.call(i,e)}}return i},inArray:function(b8,b6,b7){var e;if(b6){if(bU){return bU.call(b6,b8,b7)}e=b6.length;b7=b7?b7<0?Math.max(0,e+b7):b7:0;for(;b7<e;b7++){if(b7 in b6&&b6[b7]===b8){return b7}}}return -1},merge:function(b9,b7){var e=+b7.length,b6=0,b8=b9.length;while(b6<e){b9[b8++]=b7[b6++]}if(e!==e){while(b7[b6]!==undefined){b9[b8++]=b7[b6++]}}b9.length=b8;return b9},grep:function(e,cc,b9){var cb,b8=[],b6=0,b7=e.length,ca=!b9;for(;b6<b7;b6++){cb=!cc(e[b6],b6);if(cb!==ca){b8.push(e[b6])}}return b8},map:function(b7,cc,e){var cb,b9=0,ca=b7.length,b6=ad(b7),b8=[];if(b6){for(;b9<ca;b9++){cb=cc(b7[b9],b9,e);if(cb!=null){b8.push(cb)}}}else{for(b9 in b7){cb=cc(b7[b9],b9,e);if(cb!=null){b8.push(cb)}}}return az.apply([],b8)},guid:1,proxy:function(b8,b7){var e,b6,i;if(typeof b7==="string"){i=b8[b7];b7=b8;b8=i}if(!bI.isFunction(b8)){return undefined}e=P.call(arguments,2);b6=function(){return b8.apply(b7||this,e.concat(P.call(arguments)))};b6.guid=b8.guid=b8.guid||bI.guid++;return b6},now:function(){return +(new Date())},support:D});bI.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(b6,e){ac["[object "+e+"]"]=e.toLowerCase()});function ad(b6){var i=b6.length,e=bI.type(b6);if(e==="function"||bI.isWindow(b6)){return false}if(b6.nodeType===1&&i){return true}return e==="array"||i===0||typeof i==="number"&&i>0&&(i-1) in b6}var m=
/*!
* Sizzle CSS Selector Engine v2.2.0-pre
* http://sizzlejs.com/
*
* Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-16
*/
(function(de){var cy,dh,cn,cH,cK,ci,cW,dg,dm,cI,cX,cZ,cC,co,c8,c3,df,ce,cF,da="sizzle"+1*new Date(),cJ=de.document,di=0,c4=0,b9=cA(),c9=cA(),cG=cA(),cE=function(i,e){if(i===e){cX=true}return 0},cQ=1<<31,cO=({}).hasOwnProperty,dc=[],dd=dc.pop,cM=dc.push,b7=dc.push,cm=dc.slice,cd=function(dq,dp){var dn=0,e=dq.length;for(;dn<e;dn++){if(dq[dn]===dp){return dn}}return -1},b8="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",cp="[\\x20\\t\\r\\n\\f]",b6="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",cL=b6.replace("w","w#"),c6="\\["+cp+"*("+b6+")(?:"+cp+"*([*^$|!~]?=)"+cp+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+cL+"))|)"+cp+"*\\]",ck=":("+b6+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+c6+")*)|.*)\\)|)",cu=new RegExp(cp+"+","g"),cr=new RegExp("^"+cp+"+|((?:^|[^\\\\])(?:\\\\.)*)"+cp+"+$","g"),cv=new RegExp("^"+cp+"*,"+cp+"*"),cB=new RegExp("^"+cp+"*([>+~]|"+cp+")"+cp+"*"),ct=new RegExp("="+cp+"*([^\\]'\"]*?)"+cp+"*\\]","g"),cS=new RegExp(ck),cU=new RegExp("^"+cL+"$"),c2={ID:new RegExp("^#("+b6+")"),CLASS:new RegExp("^\\.("+b6+")"),TAG:new RegExp("^("+b6.replace("w","w*")+")"),ATTR:new RegExp("^"+c6),PSEUDO:new RegExp("^"+ck),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+cp+"*(even|odd|(([+-]|)(\\d*)n|)"+cp+"*(?:([+-]|)"+cp+"*(\\d+)|))"+cp+"*\\)|)","i"),bool:new RegExp("^(?:"+b8+")$","i"),needsContext:new RegExp("^"+cp+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+cp+"*((?:-\\d)?\\d*)"+cp+"*\\)|)(?=[^-]|$)","i")},cc=/^(?:input|select|textarea|button)$/i,cl=/^h\d$/i,cP=/^[^{]+\{\s*\[native \w/,cR=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,c1=/[+~]/,cN=/'|\\/g,cs=new RegExp("\\\\([\\da-f]{1,6}"+cp+"?|("+cp+")|.)","ig"),c5=function(e,dp,i){var dn="0x"+dp-65536;return dn!==dn||i?dp:dn<0?String.fromCharCode(dn+65536):String.fromCharCode(dn>>10|55296,dn&1023|56320)},dl=function(){cZ()};try{b7.apply((dc=cm.call(cJ.childNodes)),cJ.childNodes);dc[cJ.childNodes.length].nodeType}catch(cD){b7={apply:dc.length?function(i,e){cM.apply(i,cm.call(e))}:function(dq,dp){var e=dq.length,dn=0;while((dq[e++]=dp[dn++])){}dq.length=e-1}}}function cw(dv,dn,dz,dB){var dA,ds,dt,dx,dy,dr,dq,e,dp,dw;if((dn?dn.ownerDocument||dn:cJ)!==cC){cZ(dn)}dn=dn||cC;dz=dz||[];dx=dn.nodeType;if(typeof dv!=="string"||!dv||dx!==1&&dx!==9&&dx!==11){return dz}if(!dB&&c8){if(dx!==11&&(dA=cR.exec(dv))){if((dt=dA[1])){if(dx===9){ds=dn.getElementById(dt);if(ds&&ds.parentNode){if(ds.id===dt){dz.push(ds);return dz}}else{return dz}}else{if(dn.ownerDocument&&(ds=dn.ownerDocument.getElementById(dt))&&cF(dn,ds)&&ds.id===dt){dz.push(ds);return dz}}}else{if(dA[2]){b7.apply(dz,dn.getElementsByTagName(dv));return dz}else{if((dt=dA[3])&&dh.getElementsByClassName){b7.apply(dz,dn.getElementsByClassName(dt));return dz}}}}if(dh.qsa&&(!c3||!c3.test(dv))){e=dq=da;dp=dn;dw=dx!==1&&dv;if(dx===1&&dn.nodeName.toLowerCase()!=="object"){dr=ci(dv);if((dq=dn.getAttribute("id"))){e=dq.replace(cN,"\\$&")}else{dn.setAttribute("id",e)}e="[id='"+e+"'] ";dy=dr.length;while(dy--){dr[dy]=e+ch(dr[dy])}dp=c1.test(dv)&&cT(dn.parentNode)||dn;dw=dr.join(",")}if(dw){try{b7.apply(dz,dp.querySelectorAll(dw));return dz}catch(du){}finally{if(!dq){dn.removeAttribute("id")}}}}}return dg(dv.replace(cr,"$1"),dn,dz,dB)}function cA(){var i=[];function e(dn,dp){if(i.push(dn+" ")>cn.cacheLength){delete e[i.shift()]}return(e[dn+" "]=dp)}return e}function cj(e){e[da]=true;return e}function cf(i){var dp=cC.createElement("div");try{return !!i(dp)}catch(dn){return false}finally{if(dp.parentNode){dp.parentNode.removeChild(dp)}dp=null}}function dj(dn,dq){var e=dn.split("|"),dp=dn.length;while(dp--){cn.attrHandle[e[dp]]=dq}}function ca(i,e){var dp=e&&i,dn=dp&&i.nodeType===1&&e.nodeType===1&&(~e.sourceIndex||cQ)-(~i.sourceIndex||cQ);if(dn){return dn}if(dp){while((dp=dp.nextSibling)){if(dp===e){return -1}}}return i?1:-1}function cx(e){return function(dn){var i=dn.nodeName.toLowerCase();return i==="input"&&dn.type===e}}function cb(e){return function(dn){var i=dn.nodeName.toLowerCase();return(i==="input"||i==="button")&&dn.type===e}}function c7(e){return cj(function(i){i=+i;return cj(function(dn,ds){var dq,dp=e([],dn.length,i),dr=dp.length;while(dr--){if(dn[(dq=dp[dr])]){dn[dq]=!(ds[dq]=dn[dq])}}})})}function cT(e){return e&&typeof e.getElementsByTagName!=="undefined"&&e}dh=cw.support={};cK=cw.isXML=function(e){var i=e&&(e.ownerDocument||e).documentElement;return i?i.nodeName!=="HTML":false};cZ=cw.setDocument=function(dn){var e,i,dp=dn?dn.ownerDocument||dn:cJ;if(dp===cC||dp.nodeType!==9||!dp.documentElement){return cC}cC=dp;co=dp.documentElement;i=dp.defaultView;if(i&&i!==i.top){if(i.addEventListener){i.addEventListener("unload",dl,false)}else{if(i.attachEvent){i.attachEvent("onunload",dl)}}}c8=!cK(dp);dh.attributes=cf(function(dq){dq.className="i";return !dq.getAttribute("className")});dh.getElementsByTagName=cf(function(dq){dq.appendChild(dp.createComment(""));return !dq.getElementsByTagName("*").length});dh.getElementsByClassName=cP.test(dp.getElementsByClassName);dh.getById=cf(function(dq){co.appendChild(dq).id=da;return !dp.getElementsByName||!dp.getElementsByName(da).length});if(dh.getById){cn.find.ID=function(ds,dr){if(typeof dr.getElementById!=="undefined"&&c8){var dq=dr.getElementById(ds);return dq&&dq.parentNode?[dq]:[]}};cn.filter.ID=function(dr){var dq=dr.replace(cs,c5);return function(ds){return ds.getAttribute("id")===dq}}}else{delete cn.find.ID;cn.filter.ID=function(dr){var dq=dr.replace(cs,c5);return function(dt){var ds=typeof dt.getAttributeNode!=="undefined"&&dt.getAttributeNode("id");return ds&&ds.value===dq}}}cn.find.TAG=dh.getElementsByTagName?function(dq,dr){if(typeof dr.getElementsByTagName!=="undefined"){return dr.getElementsByTagName(dq)}else{if(dh.qsa){return dr.querySelectorAll(dq)}}}:function(dq,du){var dv,dt=[],ds=0,dr=du.getElementsByTagName(dq);if(dq==="*"){while((dv=dr[ds++])){if(dv.nodeType===1){dt.push(dv)}}return dt}return dr};cn.find.CLASS=dh.getElementsByClassName&&function(dr,dq){if(c8){return dq.getElementsByClassName(dr)}};df=[];c3=[];if((dh.qsa=cP.test(dp.querySelectorAll))){cf(function(dq){co.appendChild(dq).innerHTML="<a id='"+da+"'></a><select id='"+da+"-\f]' msallowcapture=''><option selected=''></option></select>";if(dq.querySelectorAll("[msallowcapture^='']").length){c3.push("[*^$]="+cp+"*(?:''|\"\")")}if(!dq.querySelectorAll("[selected]").length){c3.push("\\["+cp+"*(?:value|"+b8+")")}if(!dq.querySelectorAll("[id~="+da+"-]").length){c3.push("~=")}if(!dq.querySelectorAll(":checked").length){c3.push(":checked")}if(!dq.querySelectorAll("a#"+da+"+*").length){c3.push(".#.+[+~]")}});cf(function(dr){var dq=dp.createElement("input");dq.setAttribute("type","hidden");dr.appendChild(dq).setAttribute("name","D");if(dr.querySelectorAll("[name=d]").length){c3.push("name"+cp+"*[*^$|!~]?=")}if(!dr.querySelectorAll(":enabled").length){c3.push(":enabled",":disabled")}dr.querySelectorAll("*,:x");c3.push(",.*:")})}if((dh.matchesSelector=cP.test((ce=co.matches||co.webkitMatchesSelector||co.mozMatchesSelector||co.oMatchesSelector||co.msMatchesSelector)))){cf(function(dq){dh.disconnectedMatch=ce.call(dq,"div");ce.call(dq,"[s!='']:x");df.push("!=",ck)})}c3=c3.length&&new RegExp(c3.join("|"));df=df.length&&new RegExp(df.join("|"));e=cP.test(co.compareDocumentPosition);cF=e||cP.test(co.contains)?function(dr,dq){var dt=dr.nodeType===9?dr.documentElement:dr,ds=dq&&dq.parentNode;return dr===ds||!!(ds&&ds.nodeType===1&&(dt.contains?dt.contains(ds):dr.compareDocumentPosition&&dr.compareDocumentPosition(ds)&16))}:function(dr,dq){if(dq){while((dq=dq.parentNode)){if(dq===dr){return true}}}return false};cE=e?function(dr,dq){if(dr===dq){cX=true;return 0}var ds=!dr.compareDocumentPosition-!dq.compareDocumentPosition;if(ds){return ds}ds=(dr.ownerDocument||dr)===(dq.ownerDocument||dq)?dr.compareDocumentPosition(dq):1;if(ds&1||(!dh.sortDetached&&dq.compareDocumentPosition(dr)===ds)){if(dr===dp||dr.ownerDocument===cJ&&cF(cJ,dr)){return -1}if(dq===dp||dq.ownerDocument===cJ&&cF(cJ,dq)){return 1}return cI?(cd(cI,dr)-cd(cI,dq)):0}return ds&4?-1:1}:function(dr,dq){if(dr===dq){cX=true;return 0}var dx,du=0,dw=dr.parentNode,dt=dq.parentNode,ds=[dr],dv=[dq];if(!dw||!dt){return dr===dp?-1:dq===dp?1:dw?-1:dt?1:cI?(cd(cI,dr)-cd(cI,dq)):0}else{if(dw===dt){return ca(dr,dq)}}dx=dr;while((dx=dx.parentNode)){ds.unshift(dx)}dx=dq;while((dx=dx.parentNode)){dv.unshift(dx)}while(ds[du]===dv[du]){du++}return du?ca(ds[du],dv[du]):ds[du]===cJ?-1:dv[du]===cJ?1:0};return dp};cw.matches=function(i,e){return cw(i,null,null,e)};cw.matchesSelector=function(dn,dq){if((dn.ownerDocument||dn)!==cC){cZ(dn)}dq=dq.replace(ct,"='$1']");if(dh.matchesSelector&&c8&&(!df||!df.test(dq))&&(!c3||!c3.test(dq))){try{var i=ce.call(dn,dq);if(i||dh.disconnectedMatch||dn.document&&dn.document.nodeType!==11){return i}}catch(dp){}}return cw(dq,cC,null,[dn]).length>0};cw.contains=function(e,i){if((e.ownerDocument||e)!==cC){cZ(e)}return cF(e,i)};cw.attr=function(dn,e){if((dn.ownerDocument||dn)!==cC){cZ(dn)}var i=cn.attrHandle[e.toLowerCase()],dp=i&&cO.call(cn.attrHandle,e.toLowerCase())?i(dn,e,!c8):undefined;return dp!==undefined?dp:dh.attributes||!c8?dn.getAttribute(e):(dp=dn.getAttributeNode(e))&&dp.specified?dp.value:null};cw.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};cw.uniqueSort=function(dp){var dq,dr=[],e=0,dn=0;cX=!dh.detectDuplicates;cI=!dh.sortStable&&dp.slice(0);dp.sort(cE);if(cX){while((dq=dp[dn++])){if(dq===dp[dn]){e=dr.push(dn)}}while(e--){dp.splice(dr[e],1)}}cI=null;return dp};cH=cw.getText=function(dr){var dq,dn="",dp=0,e=dr.nodeType;if(!e){while((dq=dr[dp++])){dn+=cH(dq)}}else{if(e===1||e===9||e===11){if(typeof dr.textContent==="string"){return dr.textContent}else{for(dr=dr.firstChild;dr;dr=dr.nextSibling){dn+=cH(dr)}}}else{if(e===3||e===4){return dr.nodeValue}}}return dn};cn=cw.selectors={cacheLength:50,createPseudo:cj,match:c2,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(cs,c5);e[3]=(e[3]||e[4]||e[5]||"").replace(cs,c5);if(e[2]==="~="){e[3]=" "+e[3]+" "}return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if(e[1].slice(0,3)==="nth"){if(!e[3]){cw.error(e[0])}e[4]=+(e[4]?e[5]+(e[6]||1):2*(e[3]==="even"||e[3]==="odd"));e[5]=+((e[7]+e[8])||e[3]==="odd")}else{if(e[3]){cw.error(e[0])}}return e},PSEUDO:function(i){var e,dn=!i[6]&&i[2];if(c2.CHILD.test(i[0])){return null}if(i[3]){i[2]=i[4]||i[5]||""}else{if(dn&&cS.test(dn)&&(e=ci(dn,true))&&(e=dn.indexOf(")",dn.length-e)-dn.length)){i[0]=i[0].slice(0,e);i[2]=dn.slice(0,e)}}return i.slice(0,3)}},filter:{TAG:function(i){var e=i.replace(cs,c5).toLowerCase();return i==="*"?function(){return true}:function(dn){return dn.nodeName&&dn.nodeName.toLowerCase()===e}},CLASS:function(e){var i=b9[e+" "];return i||(i=new RegExp("(^|"+cp+")"+e+"("+cp+"|$)"))&&b9(e,function(dn){return i.test(typeof dn.className==="string"&&dn.className||typeof dn.getAttribute!=="undefined"&&dn.getAttribute("class")||"")})},ATTR:function(dn,i,e){return function(dq){var dp=cw.attr(dq,dn);if(dp==null){return i==="!="}if(!i){return true}dp+="";return i==="="?dp===e:i==="!="?dp!==e:i==="^="?e&&dp.indexOf(e)===0:i==="*="?e&&dp.indexOf(e)>-1:i==="$="?e&&dp.slice(-e.length)===e:i==="~="?(" "+dp.replace(cu," ")+" ").indexOf(e)>-1:i==="|="?dp===e||dp.slice(0,e.length+1)===e+"-":false}},CHILD:function(i,dq,dp,dr,dn){var dt=i.slice(0,3)!=="nth",e=i.slice(-4)!=="last",ds=dq==="of-type";return dr===1&&dn===0?function(du){return !!du.parentNode}:function(dA,dy,dD){var du,dG,dB,dF,dC,dx,dz=dt!==e?"nextSibling":"previousSibling",dE=dA.parentNode,dw=ds&&dA.nodeName.toLowerCase(),dv=!dD&&!ds;if(dE){if(dt){while(dz){dB=dA;while((dB=dB[dz])){if(ds?dB.nodeName.toLowerCase()===dw:dB.nodeType===1){return false}}dx=dz=i==="only"&&!dx&&"nextSibling"}return true}dx=[e?dE.firstChild:dE.lastChild];if(e&&dv){dG=dE[da]||(dE[da]={});du=dG[i]||[];dC=du[0]===di&&du[1];dF=du[0]===di&&du[2];dB=dC&&dE.childNodes[dC];while((dB=++dC&&dB&&dB[dz]||(dF=dC=0)||dx.pop())){if(dB.nodeType===1&&++dF&&dB===dA){dG[i]=[di,dC,dF];break}}}else{if(dv&&(du=(dA[da]||(dA[da]={}))[i])&&du[0]===di){dF=du[1]}else{while((dB=++dC&&dB&&dB[dz]||(dF=dC=0)||dx.pop())){if((ds?dB.nodeName.toLowerCase()===dw:dB.nodeType===1)&&++dF){if(dv){(dB[da]||(dB[da]={}))[i]=[di,dF]}if(dB===dA){break}}}}}dF-=dn;return dF===dr||(dF%dr===0&&dF/dr>=0)}}},PSEUDO:function(dp,dn){var e,i=cn.pseudos[dp]||cn.setFilters[dp.toLowerCase()]||cw.error("unsupported pseudo: "+dp);if(i[da]){return i(dn)}if(i.length>1){e=[dp,dp,"",dn];return cn.setFilters.hasOwnProperty(dp.toLowerCase())?cj(function(ds,du){var dr,dq=i(ds,dn),dt=dq.length;while(dt--){dr=cd(ds,dq[dt]);ds[dr]=!(du[dr]=dq[dt])}}):function(dq){return i(dq,0,e)}}return i}},pseudos:{not:cj(function(e){var i=[],dn=[],dp=cW(e.replace(cr,"$1"));return dp[da]?cj(function(dr,dw,du,ds){var dv,dq=dp(dr,null,ds,[]),dt=dr.length;while(dt--){if((dv=dq[dt])){dr[dt]=!(dw[dt]=dv)}}}):function(ds,dr,dq){i[0]=ds;dp(i,null,dq,dn);i[0]=null;return !dn.pop()}}),has:cj(function(e){return function(i){return cw(e,i).length>0}}),contains:cj(function(e){e=e.replace(cs,c5);return function(i){return(i.textContent||i.innerText||cH(i)).indexOf(e)>-1}}),lang:cj(function(e){if(!cU.test(e||"")){cw.error("unsupported lang: "+e)}e=e.replace(cs,c5).toLowerCase();return function(dn){var i;do{if((i=c8?dn.lang:dn.getAttribute("xml:lang")||dn.getAttribute("lang"))){i=i.toLowerCase();return i===e||i.indexOf(e+"-")===0}}while((dn=dn.parentNode)&&dn.nodeType===1);return false}}),target:function(e){var i=de.location&&de.location.hash;return i&&i.slice(1)===e.id},root:function(e){return e===co},focus:function(e){return e===cC.activeElement&&(!cC.hasFocus||cC.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===false},disabled:function(e){return e.disabled===true},checked:function(e){var i=e.nodeName.toLowerCase();return(i==="input"&&!!e.checked)||(i==="option"&&!!e.selected)},selected:function(e){if(e.parentNode){e.parentNode.selectedIndex}return e.selected===true},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling){if(e.nodeType<6){return false}}return true},parent:function(e){return !cn.pseudos.empty(e)},header:function(e){return cl.test(e.nodeName)},input:function(e){return cc.test(e.nodeName)},button:function(i){var e=i.nodeName.toLowerCase();return e==="input"&&i.type==="button"||e==="button"},text:function(i){var e;return i.nodeName.toLowerCase()==="input"&&i.type==="text"&&((e=i.getAttribute("type"))==null||e.toLowerCase()==="text")},first:c7(function(){return[0]}),last:c7(function(e,i){return[i-1]}),eq:c7(function(e,dn,i){return[i<0?i+dn:i]}),even:c7(function(e,dp){var dn=0;for(;dn<dp;dn+=2){e.push(dn)}return e}),odd:c7(function(e,dp){var dn=1;for(;dn<dp;dn+=2){e.push(dn)}return e}),lt:c7(function(e,dq,dp){var dn=dp<0?dp+dq:dp;for(;--dn>=0;){e.push(dn)}return e}),gt:c7(function(e,dq,dp){var dn=dp<0?dp+dq:dp;for(;++dn<dq;){e.push(dn)}return e})}};cn.pseudos.nth=cn.pseudos.eq;for(cy in {radio:true,checkbox:true,file:true,password:true,image:true}){cn.pseudos[cy]=cx(cy)}for(cy in {submit:true,reset:true}){cn.pseudos[cy]=cb(cy)}function cV(){}cV.prototype=cn.filters=cn.pseudos;cn.setFilters=new cV();ci=cw.tokenize=function(dq,dv){var i,dr,dt,du,ds,dn,e,dp=c9[dq+" "];if(dp){return dv?0:dp.slice(0)}ds=dq;dn=[];e=cn.preFilter;while(ds){if(!i||(dr=cv.exec(ds))){if(dr){ds=ds.slice(dr[0].length)||ds}dn.push((dt=[]))}i=false;if((dr=cB.exec(ds))){i=dr.shift();dt.push({value:i,type:dr[0].replace(cr," ")});ds=ds.slice(i.length)}for(du in cn.filter){if((dr=c2[du].exec(ds))&&(!e[du]||(dr=e[du](dr)))){i=dr.shift();dt.push({value:i,type:du,matches:dr});ds=ds.slice(i.length)}}if(!i){break}}return dv?ds.length:ds?cw.error(dq):c9(dq,dn).slice(0)};function ch(dq){var dp=0,dn=dq.length,e="";for(;dp<dn;dp++){e+=dq[dp].value}return e}function cq(dq,dn,dp){var e=dn.dir,dr=dp&&e==="parentNode",i=c4++;return dn.first?function(du,dt,ds){while((du=du[e])){if(du.nodeType===1||dr){return dq(du,dt,ds)}}}:function(dw,du,dt){var dx,dv,ds=[di,i];if(dt){while((dw=dw[e])){if(dw.nodeType===1||dr){if(dq(dw,du,dt)){return true}}}}else{while((dw=dw[e])){if(dw.nodeType===1||dr){dv=dw[da]||(dw[da]={});if((dx=dv[e])&&dx[0]===di&&dx[1]===i){return(ds[2]=dx[2])}else{dv[e]=ds;if((ds[2]=dq(dw,du,dt))){return true}}}}}}}function dk(e){return e.length>1?function(dr,dq,dn){var dp=e.length;while(dp--){if(!e[dp](dr,dq,dn)){return false}}return true}:e[0]}function cz(dn,dr,dq){var dp=0,e=dr.length;for(;dp<e;dp++){cw(dn,dr[dp],dq)}return dq}function c0(e,dn,dp,dq,dt){var dr,dw=[],ds=0,du=e.length,dv=dn!=null;for(;ds<du;ds++){if((dr=e[ds])){if(!dp||dp(dr,dq,dt)){dw.push(dr);if(dv){dn.push(ds)}}}}return dw}function cg(dn,i,dq,dp,dr,e){if(dp&&!dp[da]){dp=cg(dp)}if(dr&&!dr[da]){dr=cg(dr,e)}return cj(function(dC,dz,du,dB){var dE,dA,dw,dv=[],dD=[],dt=dz.length,ds=dC||cz(i||"*",du.nodeType?[du]:du,[]),dx=dn&&(dC||!i)?c0(ds,dv,dn,du,dB):ds,dy=dq?dr||(dC?dn:dt||dp)?[]:dz:dx;if(dq){dq(dx,dy,du,dB)}if(dp){dE=c0(dy,dD);dp(dE,[],du,dB);dA=dE.length;while(dA--){if((dw=dE[dA])){dy[dD[dA]]=!(dx[dD[dA]]=dw)}}}if(dC){if(dr||dn){if(dr){dE=[];dA=dy.length;while(dA--){if((dw=dy[dA])){dE.push((dx[dA]=dw))}}dr(null,(dy=[]),dE,dB)}dA=dy.length;while(dA--){if((dw=dy[dA])&&(dE=dr?cd(dC,dw):dv[dA])>-1){dC[dE]=!(dz[dE]=dw)}}}}else{dy=c0(dy===dz?dy.splice(dt,dy.length):dy);if(dr){dr(null,dz,dy,dB)}else{b7.apply(dz,dy)}}})}function db(dt){var dn,dr,dp,ds=dt.length,dw=cn.relative[dt[0].type],dx=dw||cn.relative[" "],dq=dw?1:0,du=cq(function(i){return i===dn},dx,true),dv=cq(function(i){return cd(dn,i)>-1},dx,true),e=[function(dA,dz,dy){var i=(!dw&&(dy||dz!==dm))||((dn=dz).nodeType?du(dA,dz,dy):dv(dA,dz,dy));dn=null;return i}];for(;dq<ds;dq++){if((dr=cn.relative[dt[dq].type])){e=[cq(dk(e),dr)]}else{dr=cn.filter[dt[dq].type].apply(null,dt[dq].matches);if(dr[da]){dp=++dq;for(;dp<ds;dp++){if(cn.relative[dt[dp].type]){break}}return cg(dq>1&&dk(e),dq>1&&ch(dt.slice(0,dq-1).concat({value:dt[dq-2].type===" "?"*":""})).replace(cr,"$1"),dr,dq<dp&&db(dt.slice(dq,dp)),dp<ds&&db((dt=dt.slice(dp))),dp<ds&&ch(dt))}e.push(dr)}}return dk(e)}function cY(dp,dn){var e=dn.length>0,dq=dp.length>0,i=function(dA,du,dz,dy,dD){var dv,dw,dB,dF=0,dx="0",dr=dA&&[],dG=[],dE=dm,dt=dA||dq&&cn.find.TAG("*",dD),ds=(di+=dE==null?1:Math.random()||0.1),dC=dt.length;if(dD){dm=du!==cC&&du}for(;dx!==dC&&(dv=dt[dx])!=null;dx++){if(dq&&dv){dw=0;while((dB=dp[dw++])){if(dB(dv,du,dz)){dy.push(dv);break}}if(dD){di=ds}}if(e){if((dv=!dB&&dv)){dF--}if(dA){dr.push(dv)}}}dF+=dx;if(e&&dx!==dF){dw=0;while((dB=dn[dw++])){dB(dr,dG,du,dz)}if(dA){if(dF>0){while(dx--){if(!(dr[dx]||dG[dx])){dG[dx]=dd.call(dy)}}}dG=c0(dG)}b7.apply(dy,dG);if(dD&&!dA&&dG.length>0&&(dF+dn.length)>1){cw.uniqueSort(dy)}}if(dD){di=ds;dm=dE}return dr};return e?cj(i):i}cW=cw.compile=function(e,dp){var dq,dn=[],ds=[],dr=cG[e+" "];if(!dr){if(!dp){dp=ci(e)}dq=dp.length;while(dq--){dr=db(dp[dq]);if(dr[da]){dn.push(dr)}else{ds.push(dr)}}dr=cG(e,cY(ds,dn));dr.selector=e}return dr};dg=cw.select=function(dp,e,dq,dt){var dr,dw,dn,dx,du,dv=typeof dp==="function"&&dp,ds=!dt&&ci((dp=dv.selector||dp));dq=dq||[];if(ds.length===1){dw=ds[0]=ds[0].slice(0);if(dw.length>2&&(dn=dw[0]).type==="ID"&&dh.getById&&e.nodeType===9&&c8&&cn.relative[dw[1].type]){e=(cn.find.ID(dn.matches[0].replace(cs,c5),e)||[])[0];if(!e){return dq}else{if(dv){e=e.parentNode}}dp=dp.slice(dw.shift().value.length)}dr=c2.needsContext.test(dp)?0:dw.length;while(dr--){dn=dw[dr];if(cn.relative[(dx=dn.type)]){break}if((du=cn.find[dx])){if((dt=du(dn.matches[0].replace(cs,c5),c1.test(dw[0].type)&&cT(e.parentNode)||e))){dw.splice(dr,1);dp=dt.length&&ch(dw);if(!dp){b7.apply(dq,dt);return dq}break}}}}(dv||cW(dp,ds))(dt,e,!c8,dq,c1.test(dp)&&cT(e.parentNode)||e);return dq};dh.sortStable=da.split("").sort(cE).join("")===da;dh.detectDuplicates=!!cX;cZ();dh.sortDetached=cf(function(e){return e.compareDocumentPosition(cC.createElement("div"))&1});if(!cf(function(e){e.innerHTML="<a href='#'></a>";return e.firstChild.getAttribute("href")==="#"})){dj("type|href|height|width",function(i,e,dn){if(!dn){return i.getAttribute(e,e.toLowerCase()==="type"?1:2)}})}if(!dh.attributes||!cf(function(e){e.innerHTML="<input/>";e.firstChild.setAttribute("value","");return e.firstChild.getAttribute("value")===""})){dj("value",function(i,e,dn){if(!dn&&i.nodeName.toLowerCase()==="input"){return i.defaultValue}})}if(!cf(function(e){return e.getAttribute("disabled")==null})){dj(b8,function(i,e,dp){var dn;if(!dp){return i[e]===true?e.toLowerCase():(dn=i.getAttributeNode(e))&&dn.specified?dn.value:null}})}return cw})(a5);bI.find=m;bI.expr=m.selectors;bI.expr[":"]=bI.expr.pseudos;bI.unique=m.uniqueSort;bI.text=m.getText;bI.isXMLDoc=m.isXML;bI.contains=m.contains;var A=bI.expr.match.needsContext;var a=(/^<(\w+)\s*\/?>(?:<\/\1>|)$/);var aL=/^.[^:#\[\.,]*$/;function aR(b6,e,i){if(bI.isFunction(e)){return bI.grep(b6,function(b8,b7){return !!e.call(b8,b7,b8)!==i})}if(e.nodeType){return bI.grep(b6,function(b7){return(b7===e)!==i})}if(typeof e==="string"){if(aL.test(e)){return bI.filter(e,b6,i)}e=bI.filter(e,b6)}return bI.grep(b6,function(b7){return(bI.inArray(b7,e)>=0)!==i})}bI.filter=function(b7,e,b6){var i=e[0];if(b6){b7=":not("+b7+")"}return e.length===1&&i.nodeType===1?bI.find.matchesSelector(i,b7)?[i]:[]:bI.find.matches(b7,bI.grep(e,function(b8){return b8.nodeType===1}))};bI.fn.extend({find:function(b6){var b9,b8=[],b7=this,e=b7.length;if(typeof b6!=="string"){return this.pushStack(bI(b6).filter(function(){for(b9=0;b9<e;b9++){if(bI.contains(b7[b9],this)){return true}}}))}for(b9=0;b9<e;b9++){bI.find(b6,b7[b9],b8)}b8=this.pushStack(e>1?bI.unique(b8):b8);b8.selector=this.selector?this.selector+" "+b6:b6;return b8},filter:function(e){return this.pushStack(aR(this,e||[],false))},not:function(e){return this.pushStack(aR(this,e||[],true))},is:function(e){return !!aR(this,typeof e==="string"&&A.test(e)?bI(e):e||[],false).length}});var z,n=a5.document,bt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,bV=bI.fn.init=function(e,b6){var i,b7;if(!e){return this}if(typeof e==="string"){if(e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3){i=[null,e,null]}else{i=bt.exec(e)}if(i&&(i[1]||!b6)){if(i[1]){b6=b6 instanceof bI?b6[0]:b6;bI.merge(this,bI.parseHTML(i[1],b6&&b6.nodeType?b6.ownerDocument||b6:n,true));if(a.test(i[1])&&bI.isPlainObject(b6)){for(i in b6){if(bI.isFunction(this[i])){this[i](b6[i])}else{this.attr(i,b6[i])}}}return this}else{b7=n.getElementById(i[2]);if(b7&&b7.parentNode){if(b7.id!==i[2]){return z.find(e)}this.length=1;this[0]=b7}this.context=n;this.selector=e;return this}}else{if(!b6||b6.jquery){return(b6||z).find(e)}else{return this.constructor(b6).find(e)}}}else{if(e.nodeType){this.context=this[0]=e;this.length=1;return this}else{if(bI.isFunction(e)){return typeof z.ready!=="undefined"?z.ready(e):e(bI)}}}if(e.selector!==undefined){this.selector=e.selector;this.context=e.context}return bI.makeArray(e,this)};bV.prototype=bI.fn;z=bI(n);var bv=/^(?:parents|prev(?:Until|All))/,bz={children:true,contents:true,next:true,prev:true};bI.extend({dir:function(b6,i,b8){var e=[],b7=b6[i];while(b7&&b7.nodeType!==9&&(b8===undefined||b7.nodeType!==1||!bI(b7).is(b8))){if(b7.nodeType===1){e.push(b7)}b7=b7[i]}return e},sibling:function(b6,i){var e=[];for(;b6;b6=b6.nextSibling){if(b6.nodeType===1&&b6!==i){e.push(b6)}}return e}});bI.fn.extend({has:function(b8){var b7,b6=bI(b8,this),e=b6.length;return this.filter(function(){for(b7=0;b7<e;b7++){if(bI.contains(this,b6[b7])){return true}}})},closest:function(b9,b8){var ca,b7=0,b6=this.length,e=[],cb=A.test(b9)||typeof b9!=="string"?bI(b9,b8||this.context):0;for(;b7<b6;b7++){for(ca=this[b7];ca&&ca!==b8;ca=ca.parentNode){if(ca.nodeType<11&&(cb?cb.index(ca)>-1:ca.nodeType===1&&bI.find.matchesSelector(ca,b9))){e.push(ca);break}}}return this.pushStack(e.length>1?bI.unique(e):e)},index:function(e){if(!e){return(this[0]&&this[0].parentNode)?this.first().prevAll().length:-1}if(typeof e==="string"){return bI.inArray(this[0],bI(e))}return bI.inArray(e.jquery?e[0]:e,this)},add:function(e,i){return this.pushStack(bI.unique(bI.merge(this.get(),bI(e,i))))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}});function aY(i,e){do{i=i[e]}while(i&&i.nodeType!==1);return i}bI.each({parent:function(i){var e=i.parentNode;return e&&e.nodeType!==11?e:null},parents:function(e){return bI.dir(e,"parentNode")},parentsUntil:function(b6,e,b7){return bI.dir(b6,"parentNode",b7)},next:function(e){return aY(e,"nextSibling")},prev:function(e){return aY(e,"previousSibling")},nextAll:function(e){return bI.dir(e,"nextSibling")},prevAll:function(e){return bI.dir(e,"previousSibling")},nextUntil:function(b6,e,b7){return bI.dir(b6,"nextSibling",b7)},prevUntil:function(b6,e,b7){return bI.dir(b6,"previousSibling",b7)},siblings:function(e){return bI.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return bI.sibling(e.firstChild)},contents:function(e){return bI.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:bI.merge([],e.childNodes)}},function(e,i){bI.fn[e]=function(b8,b6){var b7=bI.map(this,i,b8);if(e.slice(-5)!=="Until"){b6=b8}if(b6&&typeof b6==="string"){b7=bI.filter(b6,b7)}if(this.length>1){if(!bz[e]){b7=bI.unique(b7)}if(bv.test(e)){b7=b7.reverse()}}return this.pushStack(b7)}});var aF=(/\S+/g);var b2={};function af(i){var e=b2[i]={};bI.each(i.match(aF)||[],function(b7,b6){e[b6]=true});return e}bI.Callbacks=function(ce){ce=typeof ce==="string"?(b2[ce]||af(ce)):bI.extend({},ce);var b8,b7,e,b9,ca,b6,cb=[],cc=!ce.once&&[],i=function(cf){b7=ce.memory&&cf;e=true;ca=b6||0;b6=0;b9=cb.length;b8=true;for(;cb&&ca<b9;ca++){if(cb[ca].apply(cf[0],cf[1])===false&&ce.stopOnFalse){b7=false;break}}b8=false;if(cb){if(cc){if(cc.length){i(cc.shift())}}else{if(b7){cb=[]}else{cd.disable()}}}},cd={add:function(){if(cb){var cg=cb.length;(function cf(ch){bI.each(ch,function(cj,ci){var ck=bI.type(ci);if(ck==="function"){if(!ce.unique||!cd.has(ci)){cb.push(ci)}}else{if(ci&&ci.length&&ck!=="string"){cf(ci)}}})})(arguments);if(b8){b9=cb.length}else{if(b7){b6=cg;i(b7)}}}return this},remove:function(){if(cb){bI.each(arguments,function(ch,cf){var cg;while((cg=bI.inArray(cf,cb,cg))>-1){cb.splice(cg,1);if(b8){if(cg<=b9){b9--}if(cg<=ca){ca--}}}})}return this},has:function(cf){return cf?bI.inArray(cf,cb)>-1:!!(cb&&cb.length)},empty:function(){cb=[];b9=0;return this},disable:function(){cb=cc=b7=undefined;return this},disabled:function(){return !cb},lock:function(){cc=undefined;if(!b7){cd.disable()}return this},locked:function(){return !cc},fireWith:function(cg,cf){if(cb&&(!e||cc)){cf=cf||[];cf=[cg,cf.slice?cf.slice():cf];if(b8){cc.push(cf)}else{i(cf)}}return this},fire:function(){cd.fireWith(this,arguments);return this},fired:function(){return !!e}};return cd};bI.extend({Deferred:function(b6){var i=[["resolve","done",bI.Callbacks("once memory"),"resolved"],["reject","fail",bI.Callbacks("once memory"),"rejected"],["notify","progress",bI.Callbacks("memory")]],b7="pending",b8={state:function(){return b7},always:function(){e.done(arguments).fail(arguments);return this},then:function(){var b9=arguments;return bI.Deferred(function(ca){bI.each(i,function(cc,cb){var cd=bI.isFunction(b9[cc])&&b9[cc];e[cb[1]](function(){var ce=cd&&cd.apply(this,arguments);if(ce&&bI.isFunction(ce.promise)){ce.promise().done(ca.resolve).fail(ca.reject).progress(ca.notify)}else{ca[cb[0]+"With"](this===b8?ca.promise():this,cd?[ce]:arguments)}})});b9=null}).promise()},promise:function(b9){return b9!=null?bI.extend(b9,b8):b8}},e={};b8.pipe=b8.then;bI.each(i,function(ca,b9){var cc=b9[2],cb=b9[3];b8[b9[1]]=cc.add;if(cb){cc.add(function(){b7=cb},i[ca^1][2].disable,i[2][2].lock)}e[b9[0]]=function(){e[b9[0]+"With"](this===e?b8:this,arguments);return this};e[b9[0]+"With"]=cc.fireWith});b8.promise(e);if(b6){b6.call(e,e)}return e},when:function(b9){var b7=0,cb=P.call(arguments),e=cb.length,b6=e!==1||(b9&&bI.isFunction(b9.promise))?e:0,ce=b6===1?b9:bI.Deferred(),b8=function(cg,ch,cf){return function(i){ch[cg]=this;cf[cg]=arguments.length>1?P.call(arguments):i;if(cf===cd){ce.notifyWith(ch,cf)}else{if(!(--b6)){ce.resolveWith(ch,cf)}}}},cd,ca,cc;if(e>1){cd=new Array(e);ca=new Array(e);cc=new Array(e);for(;b7<e;b7++){if(cb[b7]&&bI.isFunction(cb[b7].promise)){cb[b7].promise().done(b8(b7,cc,cb)).fail(ce.reject).progress(b8(b7,ca,cd))}else{--b6}}}if(!b6){ce.resolveWith(cc,cb)}return ce.promise()}});var ak;bI.fn.ready=function(e){bI.ready.promise().done(e);return this};bI.extend({isReady:false,readyWait:1,holdReady:function(e){if(e){bI.readyWait++}else{bI.ready(true)}},ready:function(e){if(e===true?--bI.readyWait:bI.isReady){return}if(!n.body){return setTimeout(bI.ready)}bI.isReady=true;if(e!==true&&--bI.readyWait>0){return}ak.resolveWith(n,[bI]);if(bI.fn.triggerHandler){bI(n).triggerHandler("ready");bI(n).off("ready")}}});function bm(){if(n.addEventListener){n.removeEventListener("DOMContentLoaded",bZ,false);a5.removeEventListener("load",bZ,false)}else{n.detachEvent("onreadystatechange",bZ);a5.detachEvent("onload",bZ)}}function bZ(){if(n.addEventListener||event.type==="load"||n.readyState==="complete"){bm();bI.ready()}}bI.ready.promise=function(b8){if(!ak){ak=bI.Deferred();if(n.readyState==="complete"){setTimeout(bI.ready)}else{if(n.addEventListener){n.addEventListener("DOMContentLoaded",bZ,false);a5.addEventListener("load",bZ,false)}else{n.attachEvent("onreadystatechange",bZ);a5.attachEvent("onload",bZ);var b7=false;try{b7=a5.frameElement==null&&n.documentElement}catch(b6){}if(b7&&b7.doScroll){(function i(){if(!bI.isReady){try{b7.doScroll("left")}catch(b9){return setTimeout(i,50)}bm();bI.ready()}})()}}}}return ak.promise(b8)};var aC=typeof undefined;var bh;for(bh in bI(D)){break}D.ownLast=bh!=="0";D.inlineBlockNeedsLayout=false;bI(function(){var b6,b7,e,i;e=n.getElementsByTagName("body")[0];if(!e||!e.style){return}b7=n.createElement("div");i=n.createElement("div");i.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";e.appendChild(i).appendChild(b7);if(typeof b7.style.zoom!==aC){b7.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";D.inlineBlockNeedsLayout=b6=b7.offsetWidth===3;if(b6){e.style.zoom=1}}e.removeChild(i)});(function(){var b6=n.createElement("div");if(D.deleteExpando==null){D.deleteExpando=true;try{delete b6.test}catch(i){D.deleteExpando=false}}b6=null})();bI.acceptData=function(b6){var i=bI.noData[(b6.nodeName+" ").toLowerCase()],e=+b6.nodeType||1;return e!==1&&e!==9?false:!i||i!==true&&b6.getAttribute("classid")===i};var by=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,aQ=/([A-Z])/g;function bA(b7,b6,b8){if(b8===undefined&&b7.nodeType===1){var i="data-"+b6.replace(aQ,"-$1").toLowerCase();b8=b7.getAttribute(i);if(typeof b8==="string"){try{b8=b8==="true"?true:b8==="false"?false:b8==="null"?null:+b8+""===b8?+b8:by.test(b8)?bI.parseJSON(b8):b8}catch(b9){}bI.data(b7,b6,b8)}else{b8=undefined}}return b8}function Q(i){var e;for(e in i){if(e==="data"&&bI.isEmptyObject(i[e])){continue}if(e!=="toJSON"){return false}}return true}function bc(b7,i,b9,b8){if(!bI.acceptData(b7)){return}var cb,ca,cc=bI.expando,cd=b7.nodeType,e=cd?bI.cache:b7,b6=cd?b7[cc]:b7[cc]&&cc;if((!b6||!e[b6]||(!b8&&!e[b6].data))&&b9===undefined&&typeof i==="string"){return}if(!b6){if(cd){b6=b7[cc]=aP.pop()||bI.guid++}else{b6=cc}}if(!e[b6]){e[b6]=cd?{}:{toJSON:bI.noop}}if(typeof i==="object"||typeof i==="function"){if(b8){e[b6]=bI.extend(e[b6],i)}else{e[b6].data=bI.extend(e[b6].data,i)}}ca=e[b6];if(!b8){if(!ca.data){ca.data={}}ca=ca.data}if(b9!==undefined){ca[bI.camelCase(i)]=b9}if(typeof i==="string"){cb=ca[i];if(cb==null){cb=ca[bI.camelCase(i)]}}else{cb=ca}return cb}function ab(b9,b7,e){if(!bI.acceptData(b9)){return}var cb,b8,ca=b9.nodeType,b6=ca?bI.cache:b9,cc=ca?b9[bI.expando]:bI.expando;if(!b6[cc]){return}if(b7){cb=e?b6[cc]:b6[cc].data;if(cb){if(!bI.isArray(b7)){if(b7 in cb){b7=[b7]}else{b7=bI.camelCase(b7);if(b7 in cb){b7=[b7]}else{b7=b7.split(" ")}}}else{b7=b7.concat(bI.map(b7,bI.camelCase))}b8=b7.length;while(b8--){delete cb[b7[b8]]}if(e?!Q(cb):!bI.isEmptyObject(cb)){return}}}if(!e){delete b6[cc].data;if(!Q(b6[cc])){return}}if(ca){bI.cleanData([b9],true)}else{if(D.deleteExpando||b6!=b6.window){delete b6[cc]}else{b6[cc]=null}}}bI.extend({cache:{},noData:{"applet ":true,"embed ":true,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){e=e.nodeType?bI.cache[e[bI.expando]]:e[bI.expando];return !!e&&!Q(e)},data:function(i,e,b6){return bc(i,e,b6)},removeData:function(i,e){return ab(i,e)},_data:function(i,e,b6){return bc(i,e,b6,true)},_removeData:function(i,e){return ab(i,e,true)}});bI.fn.extend({data:function(b8,cb){var b7,b6,ca,b9=this[0],e=b9&&b9.attributes;if(b8===undefined){if(this.length){ca=bI.data(b9);if(b9.nodeType===1&&!bI._data(b9,"parsedAttrs")){b7=e.length;while(b7--){if(e[b7]){b6=e[b7].name;if(b6.indexOf("data-")===0){b6=bI.camelCase(b6.slice(5));bA(b9,b6,ca[b6])}}}bI._data(b9,"parsedAttrs",true)}}return ca}if(typeof b8==="object"){return this.each(function(){bI.data(this,b8)})}return arguments.length>1?this.each(function(){bI.data(this,b8,cb)}):b9?bA(b9,b8,bI.data(b9,b8)):undefined},removeData:function(e){return this.each(function(){bI.removeData(this,e)})}});bI.extend({queue:function(b6,i,b7){var e;if(b6){i=(i||"fx")+"queue";e=bI._data(b6,i);if(b7){if(!e||bI.isArray(b7)){e=bI._data(b6,i,bI.makeArray(b7))}else{e.push(b7)}}return e||[]}},dequeue:function(b9,b8){b8=b8||"fx";var i=bI.queue(b9,b8),ca=i.length,b7=i.shift(),e=bI._queueHooks(b9,b8),b6=function(){bI.dequeue(b9,b8)};if(b7==="inprogress"){b7=i.shift();ca--}if(b7){if(b8==="fx"){i.unshift("inprogress")}delete e.stop;b7.call(b9,b6,e)}if(!ca&&e){e.empty.fire()}},_queueHooks:function(b6,i){var e=i+"queueHooks";return bI._data(b6,e)||bI._data(b6,e,{empty:bI.Callbacks("once memory").add(function(){bI._removeData(b6,i+"queue");bI._removeData(b6,e)})})}});bI.fn.extend({queue:function(e,i){var b6=2;if(typeof e!=="string"){i=e;e="fx";b6--}if(arguments.length<b6){return bI.queue(this[0],e)}return i===undefined?this:this.each(function(){var b7=bI.queue(this,e,i);bI._queueHooks(this,e);if(e==="fx"&&b7[0]!=="inprogress"){bI.dequeue(this,e)}})},dequeue:function(e){return this.each(function(){bI.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(b7,cb){var b6,b8=1,cc=bI.Deferred(),ca=this,e=this.length,b9=function(){if(!(--b8)){cc.resolveWith(ca,[ca])}};if(typeof b7!=="string"){cb=b7;b7=undefined}b7=b7||"fx";while(e--){b6=bI._data(ca[e],b7+"queueHooks");if(b6&&b6.empty){b8++;b6.empty.add(b9)}}b9();return cc.promise(cb)}});var aE=(/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;var bT=["Top","Right","Bottom","Left"];var S=function(i,e){i=e||i;return bI.css(i,"display")==="none"||!bI.contains(i.ownerDocument,i)};var aB=bI.access=function(e,ca,cc,cb,b8,ce,cd){var b7=0,b6=e.length,b9=cc==null;if(bI.type(cc)==="object"){b8=true;for(b7 in cc){bI.access(e,ca,b7,cc[b7],true,ce,cd)}}else{if(cb!==undefined){b8=true;if(!bI.isFunction(cb)){cd=true}if(b9){if(cd){ca.call(e,cb);ca=null}else{b9=ca;ca=function(cf,i,cg){return b9.call(bI(cf),cg)}}}if(ca){for(;b7<b6;b7++){ca(e[b7],cc,cd?cb:cb.call(e[b7],b7,ca(e[b7],cc)))}}}}return b8?e:b9?ca.call(e):b6?ca(e[0],cc):ce};var aM=(/^(?:checkbox|radio)$/i);(function(){var i=n.createElement("input"),b8=n.createElement("div"),b6=n.createDocumentFragment();b8.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";D.leadingWhitespace=b8.firstChild.nodeType===3;D.tbody=!b8.getElementsByTagName("tbody").length;D.htmlSerialize=!!b8.getElementsByTagName("link").length;D.html5Clone=n.createElement("nav").cloneNode(true).outerHTML!=="<:nav></:nav>";i.type="checkbox";i.checked=true;b6.appendChild(i);D.appendChecked=i.checked;b8.innerHTML="<textarea>x</textarea>";D.noCloneChecked=!!b8.cloneNode(true).lastChild.defaultValue;b6.appendChild(b8);b8.innerHTML="<input type='radio' checked='checked' name='t'/>";D.checkClone=b8.cloneNode(true).cloneNode(true).lastChild.checked;D.noCloneEvent=true;if(b8.attachEvent){b8.attachEvent("onclick",function(){D.noCloneEvent=false});b8.cloneNode(true).click()}if(D.deleteExpando==null){D.deleteExpando=true;try{delete b8.test}catch(b7){D.deleteExpando=false}}})();(function(){var b6,e,b7=n.createElement("div");for(b6 in {submit:true,change:true,focusin:true}){e="on"+b6;if(!(D[b6+"Bubbles"]=e in a5)){b7.setAttribute(e,"t");D[b6+"Bubbles"]=b7.attributes[e].expando===false}}b7=null})();var bG=/^(?:input|select|textarea)$/i,a6=/^key/,bM=/^(?:mouse|pointer|contextmenu)|click/,bC=/^(?:focusinfocus|focusoutblur)$/,bx=/^([^.]*)(?:\.(.+)|)$/;function U(){return true}function Z(){return false}function am(){try{return n.activeElement}catch(e){}}bI.event={global:{},add:function(b8,cd,ci,ca,b9){var cb,cj,ck,b6,cf,cc,ch,b7,cg,e,i,ce=bI._data(b8);if(!ce){return}if(ci.handler){b6=ci;ci=b6.handler;b9=b6.selector}if(!ci.guid){ci.guid=bI.guid++}if(!(cj=ce.events)){cj=ce.events={}}if(!(cc=ce.handle)){cc=ce.handle=function(cl){return typeof bI!==aC&&(!cl||bI.event.triggered!==cl.type)?bI.event.dispatch.apply(cc.elem,arguments):undefined};cc.elem=b8}cd=(cd||"").match(aF)||[""];ck=cd.length;while(ck--){cb=bx.exec(cd[ck])||[];cg=i=cb[1];e=(cb[2]||"").split(".").sort();if(!cg){continue}cf=bI.event.special[cg]||{};cg=(b9?cf.delegateType:cf.bindType)||cg;cf=bI.event.special[cg]||{};ch=bI.extend({type:cg,origType:i,data:ca,handler:ci,guid:ci.guid,selector:b9,needsContext:b9&&bI.expr.match.needsContext.test(b9),namespace:e.join(".")},b6);if(!(b7=cj[cg])){b7=cj[cg]=[];b7.delegateCount=0;if(!cf.setup||cf.setup.call(b8,ca,e,cc)===false){if(b8.addEventListener){b8.addEventListener(cg,cc,false)}else{if(b8.attachEvent){b8.attachEvent("on"+cg,cc)}}}}if(cf.add){cf.add.call(b8,ch);if(!ch.handler.guid){ch.handler.guid=ci.guid}}if(b9){b7.splice(b7.delegateCount++,0,ch)}else{b7.push(ch)}bI.event.global[cg]=true}b8=null},remove:function(b7,cd,ck,b8,cc){var ca,ch,cb,b9,cj,ci,cf,b6,cg,e,i,ce=bI.hasData(b7)&&bI._data(b7);if(!ce||!(ci=ce.events)){return}cd=(cd||"").match(aF)||[""];cj=cd.length;while(cj--){cb=bx.exec(cd[cj])||[];cg=i=cb[1];e=(cb[2]||"").split(".").sort();if(!cg){for(cg in ci){bI.event.remove(b7,cg+cd[cj],ck,b8,true)}continue}cf=bI.event.special[cg]||{};cg=(b8?cf.delegateType:cf.bindType)||cg;b6=ci[cg]||[];cb=cb[2]&&new RegExp("(^|\\.)"+e.join("\\.(?:.*\\.|)")+"(\\.|$)");b9=ca=b6.length;while(ca--){ch=b6[ca];if((cc||i===ch.origType)&&(!ck||ck.guid===ch.guid)&&(!cb||cb.test(ch.namespace))&&(!b8||b8===ch.selector||b8==="**"&&ch.selector)){b6.splice(ca,1);if(ch.selector){b6.delegateCount--}if(cf.remove){cf.remove.call(b7,ch)}}}if(b9&&!b6.length){if(!cf.teardown||cf.teardown.call(b7,e,ce.handle)===false){bI.removeEvent(b7,cg,ce.handle)}delete ci[cg]}}if(bI.isEmptyObject(ci)){delete ce.handle;bI._removeData(b7,"events")}},trigger:function(b6,cd,b9,ck){var ce,b8,ci,cj,cg,cc,cb,ca=[b9||n],ch=K.call(b6,"type")?b6.type:b6,b7=K.call(b6,"namespace")?b6.namespace.split("."):[];ci=cc=b9=b9||n;if(b9.nodeType===3||b9.nodeType===8){return}if(bC.test(ch+bI.event.triggered)){return}if(ch.indexOf(".")>=0){b7=ch.split(".");ch=b7.shift();b7.sort()}b8=ch.indexOf(":")<0&&"on"+ch;b6=b6[bI.expando]?b6:new bI.Event(ch,typeof b6==="object"&&b6);b6.isTrigger=ck?2:3;b6.namespace=b7.join(".");b6.namespace_re=b6.namespace?new RegExp("(^|\\.)"+b7.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;b6.result=undefined;if(!b6.target){b6.target=b9}cd=cd==null?[b6]:bI.makeArray(cd,[b6]);cg=bI.event.special[ch]||{};if(!ck&&cg.trigger&&cg.trigger.apply(b9,cd)===false){return}if(!ck&&!cg.noBubble&&!bI.isWindow(b9)){cj=cg.delegateType||ch;if(!bC.test(cj+ch)){ci=ci.parentNode}for(;ci;ci=ci.parentNode){ca.push(ci);cc=ci}if(cc===(b9.ownerDocument||n)){ca.push(cc.defaultView||cc.parentWindow||a5)}}cb=0;while((ci=ca[cb++])&&!b6.isPropagationStopped()){b6.type=cb>1?cj:cg.bindType||ch;ce=(bI._data(ci,"events")||{})[b6.type]&&bI._data(ci,"handle");if(ce){ce.apply(ci,cd)}ce=b8&&ci[b8];if(ce&&ce.apply&&bI.acceptData(ci)){b6.result=ce.apply(ci,cd);if(b6.result===false){b6.preventDefault()}}}b6.type=ch;if(!ck&&!b6.isDefaultPrevented()){if((!cg._default||cg._default.apply(ca.pop(),cd)===false)&&bI.acceptData(b9)){if(b8&&b9[ch]&&!bI.isWindow(b9)){cc=b9[b8];if(cc){b9[b8]=null}bI.event.triggered=ch;try{b9[ch]()}catch(cf){}bI.event.triggered=undefined;if(cc){b9[b8]=cc}}}}return b6.result},dispatch:function(e){e=bI.event.fix(e);var b9,ca,ce,b6,b8,cd=[],cc=P.call(arguments),b7=(bI._data(this,"events")||{})[e.type]||[],cb=bI.event.special[e.type]||{};cc[0]=e;e.delegateTarget=this;if(cb.preDispatch&&cb.preDispatch.call(this,e)===false){return}cd=bI.event.handlers.call(this,e,b7);b9=0;while((b6=cd[b9++])&&!e.isPropagationStopped()){e.currentTarget=b6.elem;b8=0;while((ce=b6.handlers[b8++])&&!e.isImmediatePropagationStopped()){if(!e.namespace_re||e.namespace_re.test(ce.namespace)){e.handleObj=ce;e.data=ce.data;ca=((bI.event.special[ce.origType]||{}).handle||ce.handler).apply(b6.elem,cc);if(ca!==undefined){if((e.result=ca)===false){e.preventDefault();e.stopPropagation()}}}}}if(cb.postDispatch){cb.postDispatch.call(this,e)}return e.result},handlers:function(e,b7){var b6,cc,ca,b9,cb=[],b8=b7.delegateCount,cd=e.target;if(b8&&cd.nodeType&&(!e.button||e.type!=="click")){for(;cd!=this;cd=cd.parentNode||this){if(cd.nodeType===1&&(cd.disabled!==true||e.type!=="click")){ca=[];for(b9=0;b9<b8;b9++){cc=b7[b9];b6=cc.selector+" ";if(ca[b6]===undefined){ca[b6]=cc.needsContext?bI(b6,this).index(cd)>=0:bI.find(b6,this,null,[cd]).length}if(ca[b6]){ca.push(cc)}}if(ca.length){cb.push({elem:cd,handlers:ca})}}}}if(b8<b7.length){cb.push({elem:this,handlers:b7.slice(b8)})}return cb},fix:function(b8){if(b8[bI.expando]){return b8}var b6,cb,ca,b7=b8.type,e=b8,b9=this.fixHooks[b7];if(!b9){this.fixHooks[b7]=b9=bM.test(b7)?this.mouseHooks:a6.test(b7)?this.keyHooks:{}}ca=b9.props?this.props.concat(b9.props):this.props;b8=new bI.Event(e);b6=ca.length;while(b6--){cb=ca[b6];b8[cb]=e[cb]}if(!b8.target){b8.target=e.srcElement||n}if(b8.target.nodeType===3){b8.target=b8.target.parentNode}b8.metaKey=!!b8.metaKey;return b9.filter?b9.filter(b8,e):b8},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(i,e){if(i.which==null){i.which=e.charCode!=null?e.charCode:e.keyCode}return i}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(b7,b6){var e,b8,b9,i=b6.button,ca=b6.fromElement;if(b7.pageX==null&&b6.clientX!=null){b8=b7.target.ownerDocument||n;b9=b8.documentElement;e=b8.body;b7.pageX=b6.clientX+(b9&&b9.scrollLeft||e&&e.scrollLeft||0)-(b9&&b9.clientLeft||e&&e.clientLeft||0);b7.pageY=b6.clientY+(b9&&b9.scrollTop||e&&e.scrollTop||0)-(b9&&b9.clientTop||e&&e.clientTop||0)}if(!b7.relatedTarget&&ca){b7.relatedTarget=ca===b7.target?b6.toElement:ca}if(!b7.which&&i!==undefined){b7.which=(i&1?1:(i&2?3:(i&4?2:0)))}return b7}},special:{load:{noBubble:true},focus:{trigger:function(){if(this!==am()&&this.focus){try{this.focus();return false}catch(i){}}},delegateType:"focusin"},blur:{trigger:function(){if(this===am()&&this.blur){this.blur();return false}},delegateType:"focusout"},click:{trigger:function(){if(bI.nodeName(this,"input")&&this.type==="checkbox"&&this.click){this.click();return false}},_default:function(e){return bI.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){if(e.result!==undefined&&e.originalEvent){e.originalEvent.returnValue=e.result}}}},simulate:function(b6,b8,b7,i){var b9=bI.extend(new bI.Event(),b7,{type:b6,isSimulated:true,originalEvent:{}});if(i){bI.event.trigger(b9,null,b8)}else{bI.event.dispatch.call(b8,b9)}if(b9.isDefaultPrevented()){b7.preventDefault()}}};bI.removeEvent=n.removeEventListener?function(i,e,b6){if(i.removeEventListener){i.removeEventListener(e,b6,false)}}:function(b6,i,b7){var e="on"+i;if(b6.detachEvent){if(typeof b6[e]===aC){b6[e]=null}b6.detachEvent(e,b7)}};bI.Event=function(i,e){if(!(this instanceof bI.Event)){return new bI.Event(i,e)}if(i&&i.type){this.originalEvent=i;this.type=i.type;this.isDefaultPrevented=i.defaultPrevented||i.defaultPrevented===undefined&&i.returnValue===false?U:Z}else{this.type=i}if(e){bI.extend(this,e)}this.timeStamp=i&&i.timeStamp||bI.now();this[bI.expando]=true};bI.Event.prototype={isDefaultPrevented:Z,isPropagationStopped:Z,isImmediatePropagationStopped:Z,preventDefault:function(){var i=this.originalEvent;this.isDefaultPrevented=U;if(!i){return}if(i.preventDefault){i.preventDefault()}else{i.returnValue=false}},stopPropagation:function(){var i=this.originalEvent;this.isPropagationStopped=U;if(!i){return}if(i.stopPropagation){i.stopPropagation()}i.cancelBubble=true},stopImmediatePropagation:function(){var i=this.originalEvent;this.isImmediatePropagationStopped=U;if(i&&i.stopImmediatePropagation){i.stopImmediatePropagation()}this.stopPropagation()}};bI.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(i,e){bI.event.special[i]={delegateType:e,bindType:e,handle:function(b8){var b6,ca=this,b9=b8.relatedTarget,b7=b8.handleObj;if(!b9||(b9!==ca&&!bI.contains(ca,b9))){b8.type=b7.origType;b6=b7.handler.apply(this,arguments);b8.type=e}return b6}}});if(!D.submitBubbles){bI.event.special.submit={setup:function(){if(bI.nodeName(this,"form")){return false}bI.event.add(this,"click._submit keypress._submit",function(b7){var b6=b7.target,i=bI.nodeName(b6,"input")||bI.nodeName(b6,"button")?b6.form:undefined;if(i&&!bI._data(i,"submitBubbles")){bI.event.add(i,"submit._submit",function(e){e._submit_bubble=true});bI._data(i,"submitBubbles",true)}})},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;if(this.parentNode&&!e.isTrigger){bI.event.simulate("submit",this.parentNode,e,true)}}},teardown:function(){if(bI.nodeName(this,"form")){return false}bI.event.remove(this,"._submit")}}}if(!D.changeBubbles){bI.event.special.change={setup:function(){if(bG.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio"){bI.event.add(this,"propertychange._change",function(e){if(e.originalEvent.propertyName==="checked"){this._just_changed=true}});bI.event.add(this,"click._change",function(e){if(this._just_changed&&!e.isTrigger){this._just_changed=false}bI.event.simulate("change",this,e,true)})}return false}bI.event.add(this,"beforeactivate._change",function(b6){var i=b6.target;if(bG.test(i.nodeName)&&!bI._data(i,"changeBubbles")){bI.event.add(i,"change._change",function(e){if(this.parentNode&&!e.isSimulated&&!e.isTrigger){bI.event.simulate("change",this.parentNode,e,true)}});bI._data(i,"changeBubbles",true)}})},handle:function(i){var e=i.target;if(this!==e||i.isSimulated||i.isTrigger||(e.type!=="radio"&&e.type!=="checkbox")){return i.handleObj.handler.apply(this,arguments)}},teardown:function(){bI.event.remove(this,"._change");return !bG.test(this.nodeName)}}}if(!D.focusinBubbles){bI.each({focus:"focusin",blur:"focusout"},function(b6,e){var i=function(b7){bI.event.simulate(e,b7.target,bI.event.fix(b7),true)};bI.event.special[e]={setup:function(){var b8=this.ownerDocument||this,b7=bI._data(b8,e);if(!b7){b8.addEventListener(b6,i,true)}bI._data(b8,e,(b7||0)+1)},teardown:function(){var b8=this.ownerDocument||this,b7=bI._data(b8,e)-1;if(!b7){b8.removeEventListener(b6,i,true);bI._removeData(b8,e)}else{bI._data(b8,e,b7)}}}})}bI.fn.extend({on:function(b6,e,b9,b8,i){var b7,ca;if(typeof b6==="object"){if(typeof e!=="string"){b9=b9||e;e=undefined}for(b7 in b6){this.on(b7,e,b9,b6[b7],i)}return this}if(b9==null&&b8==null){b8=e;b9=e=undefined}else{if(b8==null){if(typeof e==="string"){b8=b9;b9=undefined}else{b8=b9;b9=e;e=undefined}}}if(b8===false){b8=Z}else{if(!b8){return this}}if(i===1){ca=b8;b8=function(cb){bI().off(cb);return ca.apply(this,arguments)};b8.guid=ca.guid||(ca.guid=bI.guid++)}return this.each(function(){bI.event.add(this,b6,b8,b9,e)})},one:function(i,e,b7,b6){return this.on(i,e,b7,b6,1)},off:function(b6,e,b8){var i,b7;if(b6&&b6.preventDefault&&b6.handleObj){i=b6.handleObj;bI(b6.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler);return this}if(typeof b6==="object"){for(b7 in b6){this.off(b7,e,b6[b7])}return this}if(e===false||typeof e==="function"){b8=e;e=undefined}if(b8===false){b8=Z}return this.each(function(){bI.event.remove(this,b6,b8,e)})},trigger:function(e,i){return this.each(function(){bI.event.trigger(e,i,this)})},triggerHandler:function(e,b6){var i=this[0];if(i){return bI.event.trigger(e,b6,i,true)}}});function B(e){var b6=d.split("|"),i=e.createDocumentFragment();if(i.createElement){while(b6.length){i.createElement(b6.pop())}}return i}var d="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",aD=/ jQuery\d+="(?:null|\d+)"/g,M=new RegExp("<(?:"+d+")[\\s/>]","i"),b5=/^\s+/,aH=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,o=/<([\w:]+)/,b0=/<tbody/i,L=/<|&#?\w+;/,an=/<(?:script|style|link)/i,bW=/checked\s*(?:[^=]|=\s*.checked.)/i,bB=/^$|\/(?:java|ecma)script/i,ar=/^true\/(.*)/,aO=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,W={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:D.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},aT=B(n),k=aT.appendChild(n.createElement("div"));W.optgroup=W.option;W.tbody=W.tfoot=W.colgroup=W.caption=W.thead;W.th=W.td;function l(b8,e){var b6,b9,b7=0,ca=typeof b8.getElementsByTagName!==aC?b8.getElementsByTagName(e||"*"):typeof b8.querySelectorAll!==aC?b8.querySelectorAll(e||"*"):undefined;if(!ca){for(ca=[],b6=b8.childNodes||b8;(b9=b6[b7])!=null;b7++){if(!e||bI.nodeName(b9,e)){ca.push(b9)}else{bI.merge(ca,l(b9,e))}}}return e===undefined||e&&bI.nodeName(b8,e)?bI.merge([b8],ca):ca}function bY(e){if(aM.test(e.type)){e.defaultChecked=e.checked}}function a3(i,e){return bI.nodeName(i,"table")&&bI.nodeName(e.nodeType!==11?e:e.firstChild,"tr")?i.getElementsByTagName("tbody")[0]||i.appendChild(i.ownerDocument.createElement("tbody")):i}function u(e){e.type=(bI.find.attr(e,"type")!==null)+"/"+e.type;return e}function bf(i){var e=ar.exec(i.type);if(e){i.type=e[1]}else{i.removeAttribute("type")}return i}function bu(e,b7){var b8,b6=0;for(;(b8=e[b6])!=null;b6++){bI._data(b8,"globalEval",!b7||bI._data(b7[b6],"globalEval"))}}function at(cc,b6){if(b6.nodeType!==1||!bI.hasData(cc)){return}var b9,b8,e,cb=bI._data(cc),ca=bI._data(b6,cb),b7=cb.events;if(b7){delete ca.handle;ca.events={};for(b9 in b7){for(b8=0,e=b7[b9].length;b8<e;b8++){bI.event.add(b6,b9,b7[b9][b8])}}}if(ca.data){ca.data=bI.extend({},ca.data)}}function T(b8,i){var b9,b7,b6;if(i.nodeType!==1){return}b9=i.nodeName.toLowerCase();if(!D.noCloneEvent&&i[bI.expando]){b6=bI._data(i);for(b7 in b6.events){bI.removeEvent(i,b7,b6.handle)}i.removeAttribute(bI.expando)}if(b9==="script"&&i.text!==b8.text){u(i).text=b8.text;bf(i)}else{if(b9==="object"){if(i.parentNode){i.outerHTML=b8.outerHTML}if(D.html5Clone&&(b8.innerHTML&&!bI.trim(i.innerHTML))){i.innerHTML=b8.innerHTML}}else{if(b9==="input"&&aM.test(b8.type)){i.defaultChecked=i.checked=b8.checked;if(i.value!==b8.value){i.value=b8.value}}else{if(b9==="option"){i.defaultSelected=i.selected=b8.defaultSelected}else{if(b9==="input"||b9==="textarea"){i.defaultValue=b8.defaultValue}}}}}}bI.extend({clone:function(b6,b8,e){var ca,b7,cd,b9,cb,cc=bI.contains(b6.ownerDocument,b6);if(D.html5Clone||bI.isXMLDoc(b6)||!M.test("<"+b6.nodeName+">")){cd=b6.cloneNode(true)}else{k.innerHTML=b6.outerHTML;k.removeChild(cd=k.firstChild)}if((!D.noCloneEvent||!D.noCloneChecked)&&(b6.nodeType===1||b6.nodeType===11)&&!bI.isXMLDoc(b6)){ca=l(cd);cb=l(b6);for(b9=0;(b7=cb[b9])!=null;++b9){if(ca[b9]){T(b7,ca[b9])}}}if(b8){if(e){cb=cb||l(b6);ca=ca||l(cd);for(b9=0;(b7=cb[b9])!=null;b9++){at(b7,ca[b9])}}else{at(b6,cd)}}ca=l(cd,"script");if(ca.length>0){bu(ca,!cc&&l(b6,"script"))}ca=cb=b7=null;return cd},buildFragment:function(b6,b8,cd,ci){var ce,ca,cc,ch,cj,cg,b7,cb=b6.length,b9=B(b8),e=[],cf=0;for(;cf<cb;cf++){ca=b6[cf];if(ca||ca===0){if(bI.type(ca)==="object"){bI.merge(e,ca.nodeType?[ca]:ca)}else{if(!L.test(ca)){e.push(b8.createTextNode(ca))}else{ch=ch||b9.appendChild(b8.createElement("div"));cj=(o.exec(ca)||["",""])[1].toLowerCase();b7=W[cj]||W._default;ch.innerHTML=b7[1]+ca.replace(aH,"<$1></$2>")+b7[2];ce=b7[0];while(ce--){ch=ch.lastChild}if(!D.leadingWhitespace&&b5.test(ca)){e.push(b8.createTextNode(b5.exec(ca)[0]))}if(!D.tbody){ca=cj==="table"&&!b0.test(ca)?ch.firstChild:b7[1]==="<table>"&&!b0.test(ca)?ch:0;ce=ca&&ca.childNodes.length;while(ce--){if(bI.nodeName((cg=ca.childNodes[ce]),"tbody")&&!cg.childNodes.length){ca.removeChild(cg)}}}bI.merge(e,ch.childNodes);ch.textContent="";while(ch.firstChild){ch.removeChild(ch.firstChild)}ch=b9.lastChild}}}}if(ch){b9.removeChild(ch)}if(!D.appendChecked){bI.grep(l(e,"input"),bY)}cf=0;while((ca=e[cf++])){if(ci&&bI.inArray(ca,ci)!==-1){continue}cc=bI.contains(ca.ownerDocument,ca);ch=l(b9.appendChild(ca),"script");if(cc){bu(ch)}if(cd){ce=0;while((ca=ch[ce++])){if(bB.test(ca.type||"")){cd.push(ca)}}}}ch=null;return b9},cleanData:function(b6,ce){var b8,cd,b7,b9,ca=0,cf=bI.expando,e=bI.cache,cb=D.deleteExpando,cc=bI.event.special;for(;(b8=b6[ca])!=null;ca++){if(ce||bI.acceptData(b8)){b7=b8[cf];b9=b7&&e[b7];if(b9){if(b9.events){for(cd in b9.events){if(cc[cd]){bI.event.remove(b8,cd)}else{bI.removeEvent(b8,cd,b9.handle)}}}if(e[b7]){delete e[b7];if(cb){delete b8[cf]}else{if(typeof b8.removeAttribute!==aC){b8.removeAttribute(cf)}else{b8[cf]=null}}aP.push(b7)}}}}}});bI.fn.extend({text:function(e){return aB(this,function(i){return i===undefined?bI.text(this):this.empty().append((this[0]&&this[0].ownerDocument||n).createTextNode(i))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var i=a3(this,e);i.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var i=a3(this,e);i.insertBefore(e,i.firstChild)}})},before:function(){return this.domManip(arguments,function(e){if(this.parentNode){this.parentNode.insertBefore(e,this)}})},after:function(){return this.domManip(arguments,function(e){if(this.parentNode){this.parentNode.insertBefore(e,this.nextSibling)}})},remove:function(e,b9){var b8,b6=e?bI.filter(e,this):this,b7=0;for(;(b8=b6[b7])!=null;b7++){if(!b9&&b8.nodeType===1){bI.cleanData(l(b8))}if(b8.parentNode){if(b9&&bI.contains(b8.ownerDocument,b8)){bu(l(b8,"script"))}b8.parentNode.removeChild(b8)}}return this},empty:function(){var b6,e=0;for(;(b6=this[e])!=null;e++){if(b6.nodeType===1){bI.cleanData(l(b6,false))}while(b6.firstChild){b6.removeChild(b6.firstChild)}if(b6.options&&bI.nodeName(b6,"select")){b6.options.length=0}}return this},clone:function(i,e){i=i==null?false:i;e=e==null?i:e;return this.map(function(){return bI.clone(this,i,e)})},html:function(e){return aB(this,function(b9){var b8=this[0]||{},b7=0,b6=this.length;if(b9===undefined){return b8.nodeType===1?b8.innerHTML.replace(aD,""):undefined}if(typeof b9==="string"&&!an.test(b9)&&(D.htmlSerialize||!M.test(b9))&&(D.leadingWhitespace||!b5.test(b9))&&!W[(o.exec(b9)||["",""])[1].toLowerCase()]){b9=b9.replace(aH,"<$1></$2>");try{for(;b7<b6;b7++){b8=this[b7]||{};if(b8.nodeType===1){bI.cleanData(l(b8,false));b8.innerHTML=b9}}b8=0}catch(ca){}}if(b8){this.empty().append(b9)}},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];this.domManip(arguments,function(i){e=this.parentNode;bI.cleanData(l(this));if(e){e.replaceChild(i,this)}});return e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,true)},domManip:function(cd,ci){cd=az.apply([],cd);var cb,b7,e,b9,cg,cc,ca=0,b8=this.length,cf=this,ch=b8-1,ce=cd[0],b6=bI.isFunction(ce);if(b6||(b8>1&&typeof ce==="string"&&!D.checkClone&&bW.test(ce))){return this.each(function(cj){var i=cf.eq(cj);if(b6){cd[0]=ce.call(this,cj,i.html())}i.domManip(cd,ci)})}if(b8){cc=bI.buildFragment(cd,this[0].ownerDocument,false,this);cb=cc.firstChild;if(cc.childNodes.length===1){cc=cb}if(cb){b9=bI.map(l(cc,"script"),u);e=b9.length;for(;ca<b8;ca++){b7=cc;if(ca!==ch){b7=bI.clone(b7,true,true);if(e){bI.merge(b9,l(b7,"script"))}}ci.call(this[ca],b7,ca)}if(e){cg=b9[b9.length-1].ownerDocument;bI.map(b9,bf);for(ca=0;ca<e;ca++){b7=b9[ca];if(bB.test(b7.type||"")&&!bI._data(b7,"globalEval")&&bI.contains(cg,b7)){if(b7.src){if(bI._evalUrl){bI._evalUrl(b7.src)}}else{bI.globalEval((b7.text||b7.textContent||b7.innerHTML||"").replace(aO,""))}}}}cc=cb=null}}return this}});bI.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,i){bI.fn[e]=function(b6){var b7,b9=0,b8=[],cb=bI(b6),ca=cb.length-1;for(;b9<=ca;b9++){b7=b9===ca?this:this.clone(true);bI(cb[b9])[i](b7);x.apply(b8,b7.get())}return this.pushStack(b8)}});var aI,bl={};function a4(e,b8){var i,b6=bI(b8.createElement(e)).appendTo(b8.body),b7=a5.getDefaultComputedStyle&&(i=a5.getDefaultComputedStyle(b6[0]))?i.display:bI.css(b6[0],"display");b6.detach();return b7}function a0(b6){var i=n,e=bl[b6];if(!e){e=a4(b6,i);if(e==="none"||!e){aI=(aI||bI("<iframe frameborder='0' width='0' height='0'/>")).appendTo(i.documentElement);i=(aI[0].contentWindow||aI[0].contentDocument).document;i.write();i.close();e=a4(b6,i);aI.detach()}bl[b6]=e}return e}(function(){var e;D.shrinkWrapBlocks=function(){if(e!=null){return e}e=false;var b7,i,b6;i=n.getElementsByTagName("body")[0];if(!i||!i.style){return}b7=n.createElement("div");b6=n.createElement("div");b6.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(b6).appendChild(b7);if(typeof b7.style.zoom!==aC){b7.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1";b7.appendChild(n.createElement("div")).style.width="5px";e=b7.offsetWidth!==3}i.removeChild(b6);return e}})();var aZ=(/^margin/);var Y=new RegExp("^("+aE+")(?!px)[a-z%]+$","i");var bq,G,bo=/^(top|right|bottom|left)$/;if(a5.getComputedStyle){bq=function(e){if(e.ownerDocument.defaultView.opener){return e.ownerDocument.defaultView.getComputedStyle(e,null)}return a5.getComputedStyle(e,null)};G=function(cb,i,ca){var b8,b7,b9,e,b6=cb.style;ca=ca||bq(cb);e=ca?ca.getPropertyValue(i)||ca[i]:undefined;if(ca){if(e===""&&!bI.contains(cb.ownerDocument,cb)){e=bI.style(cb,i)}if(Y.test(e)&&aZ.test(i)){b8=b6.width;b7=b6.minWidth;b9=b6.maxWidth;b6.minWidth=b6.maxWidth=b6.width=e;e=ca.width;b6.width=b8;b6.minWidth=b7;b6.maxWidth=b9}}return e===undefined?e:e+""}}else{if(n.documentElement.currentStyle){bq=function(e){return e.currentStyle};G=function(ca,b7,b9){var cb,i,e,b6,b8=ca.style;b9=b9||bq(ca);b6=b9?b9[b7]:undefined;if(b6==null&&b8&&b8[b7]){b6=b8[b7]}if(Y.test(b6)&&!bo.test(b7)){cb=b8.left;i=ca.runtimeStyle;e=i&&i.left;if(e){i.left=ca.currentStyle.left}b8.left=b7==="fontSize"?"1em":b6;b6=b8.pixelLeft+"px";b8.left=cb;if(e){i.left=e}}return b6===undefined?b6:b6+""||"auto"}}}function a7(e,i){return{get:function(){var b6=e();if(b6==null){return}if(b6){delete this.get;return}return(this.get=i).apply(this,arguments)}}}(function(){var cb,b9,b7,ca,b6,b8,i;cb=n.createElement("div");cb.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";b7=cb.getElementsByTagName("a")[0];b9=b7&&b7.style;if(!b9){return}b9.cssText="float:left;opacity:.5";D.opacity=b9.opacity==="0.5";D.cssFloat=!!b9.cssFloat;cb.style.backgroundClip="content-box";cb.cloneNode(true).style.backgroundClip="";D.clearCloneStyle=cb.style.backgroundClip==="content-box";D.boxSizing=b9.boxSizing===""||b9.MozBoxSizing===""||b9.WebkitBoxSizing==="";bI.extend(D,{reliableHiddenOffsets:function(){if(b8==null){e()}return b8},boxSizingReliable:function(){if(b6==null){e()}return b6},pixelPosition:function(){if(ca==null){e()}return ca},reliableMarginRight:function(){if(i==null){e()}return i}});function e(){var cf,cc,cd,ce;cc=n.getElementsByTagName("body")[0];if(!cc||!cc.style){return}cf=n.createElement("div");cd=n.createElement("div");cd.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";cc.appendChild(cd).appendChild(cf);cf.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";ca=b6=false;i=true;if(a5.getComputedStyle){ca=(a5.getComputedStyle(cf,null)||{}).top!=="1%";b6=(a5.getComputedStyle(cf,null)||{width:"4px"}).width==="4px";ce=cf.appendChild(n.createElement("div"));ce.style.cssText=cf.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";ce.style.marginRight=ce.style.width="0";cf.style.width="1px";i=!parseFloat((a5.getComputedStyle(ce,null)||{}).marginRight);cf.removeChild(ce)}cf.innerHTML="<table><tr><td></td><td>t</td></tr></table>";ce=cf.getElementsByTagName("td");ce[0].style.cssText="margin:0;border:0;padding:0;display:none";b8=ce[0].offsetHeight===0;if(b8){ce[0].style.display="";ce[1].style.display="none";b8=ce[0].offsetHeight===0}cc.removeChild(cd)}})();bI.swap=function(b9,b8,ca,b7){var b6,i,e={};for(i in b8){e[i]=b9.style[i];b9.style[i]=b8[i]}b6=ca.apply(b9,b7||[]);for(i in b8){b9.style[i]=e[i]}return b6};var bj=/alpha\([^)]*\)/i,aU=/opacity\s*=\s*([^)]*)/,H=/^(none|table(?!-c[ea]).+)/,bb=new RegExp("^("+aE+")(.*)$","i"),V=new RegExp("^([+-])=("+aE+")","i"),be={position:"absolute",visibility:"hidden",display:"block"},bD={letterSpacing:"0",fontWeight:"400"},aw=["Webkit","O","Moz","ms"];function c(b8,b6){if(b6 in b8){return b6}var b9=b6.charAt(0).toUpperCase()+b6.slice(1),e=b6,b7=aw.length;while(b7--){b6=aw[b7]+b9;if(b6 in b8){return b6}}return e}function s(ca,e){var cb,b8,b9,i=[],b6=0,b7=ca.length;for(;b6<b7;b6++){b8=ca[b6];if(!b8.style){continue}i[b6]=bI._data(b8,"olddisplay");cb=b8.style.display;if(e){if(!i[b6]&&cb==="none"){b8.style.display=""}if(b8.style.display===""&&S(b8)){i[b6]=bI._data(b8,"olddisplay",a0(b8.nodeName))}}else{b9=S(b8);if(cb&&cb!=="none"||!b9){bI._data(b8,"olddisplay",b9?cb:bI.css(b8,"display"))}}}for(b6=0;b6<b7;b6++){b8=ca[b6];if(!b8.style){continue}if(!e||b8.style.display==="none"||b8.style.display===""){b8.style.display=e?i[b6]||"":"none"}}return ca}function aN(e,b6,b7){var i=bb.exec(b6);return i?Math.max(0,i[1]-(b7||0))+(i[2]||"px"):b6}function ax(b9,b6,e,cb,b8){var b7=e===(cb?"border":"content")?4:b6==="width"?1:0,ca=0;for(;b7<4;b7+=2){if(e==="margin"){ca+=bI.css(b9,e+bT[b7],true,b8)}if(cb){if(e==="content"){ca-=bI.css(b9,"padding"+bT[b7],true,b8)}if(e!=="margin"){ca-=bI.css(b9,"border"+bT[b7]+"Width",true,b8)}}else{ca+=bI.css(b9,"padding"+bT[b7],true,b8);if(e!=="padding"){ca+=bI.css(b9,"border"+bT[b7]+"Width",true,b8)}}}return ca}function v(b8,i,e){var b7=true,b9=i==="width"?b8.offsetWidth:b8.offsetHeight,b6=bq(b8),ca=D.boxSizing&&bI.css(b8,"boxSizing",false,b6)==="border-box";if(b9<=0||b9==null){b9=G(b8,i,b6);if(b9<0||b9==null){b9=b8.style[i]}if(Y.test(b9)){return b9}b7=ca&&(D.boxSizingReliable()||b9===b8.style[i]);b9=parseFloat(b9)||0}return(b9+ax(b8,i,e||(ca?"border":"content"),b7,b6))+"px"}bI.extend({cssHooks:{opacity:{get:function(b6,i){if(i){var e=G(b6,"opacity");return e===""?"1":e}}}},cssNumber:{columnCount:true,fillOpacity:true,flexGrow:true,flexShrink:true,fontWeight:true,lineHeight:true,opacity:true,order:true,orphans:true,widows:true,zIndex:true,zoom:true},cssProps:{"float":D.cssFloat?"cssFloat":"styleFloat"},style:function(b7,b6,cd,b8){if(!b7||b7.nodeType===3||b7.nodeType===8||!b7.style){return}var cb,cc,ce,b9=bI.camelCase(b6),i=b7.style;b6=bI.cssProps[b9]||(bI.cssProps[b9]=c(i,b9));ce=bI.cssHooks[b6]||bI.cssHooks[b9];if(cd!==undefined){cc=typeof cd;if(cc==="string"&&(cb=V.exec(cd))){cd=(cb[1]+1)*cb[2]+parseFloat(bI.css(b7,b6));cc="number"}if(cd==null||cd!==cd){return}if(cc==="number"&&!bI.cssNumber[b9]){cd+="px"}if(!D.clearCloneStyle&&cd===""&&b6.indexOf("background")===0){i[b6]="inherit"}if(!ce||!("set" in ce)||(cd=ce.set(b7,cd,b8))!==undefined){try{i[b6]=cd}catch(ca){}}}else{if(ce&&"get" in ce&&(cb=ce.get(b7,false,b8))!==undefined){return cb}return i[b6]}},css:function(ca,b8,i,b9){var b7,cb,e,b6=bI.camelCase(b8);b8=bI.cssProps[b6]||(bI.cssProps[b6]=c(ca.style,b6));e=bI.cssHooks[b8]||bI.cssHooks[b6];if(e&&"get" in e){cb=e.get(ca,true,i)}if(cb===undefined){cb=G(ca,b8,b9)}if(cb==="normal"&&b8 in bD){cb=bD[b8]}if(i===""||i){b7=parseFloat(cb);return i===true||bI.isNumeric(b7)?b7||0:cb}return cb}});bI.each(["height","width"],function(b6,e){bI.cssHooks[e]={get:function(b8,b7,i){if(b7){return H.test(bI.css(b8,"display"))&&b8.offsetWidth===0?bI.swap(b8,be,function(){return v(b8,e,i)}):v(b8,e,i)}},set:function(b8,b9,i){var b7=i&&bq(b8);return aN(b8,b9,i?ax(b8,e,i,D.boxSizing&&bI.css(b8,"boxSizing",false,b7)==="border-box",b7):0)}}});if(!D.opacity){bI.cssHooks.opacity={get:function(i,e){return aU.test((e&&i.currentStyle?i.currentStyle.filter:i.style.filter)||"")?(0.01*parseFloat(RegExp.$1))+"":e?"1":""},set:function(b8,b9){var b7=b8.style,i=b8.currentStyle,e=bI.isNumeric(b9)?"alpha(opacity="+b9*100+")":"",b6=i&&i.filter||b7.filter||"";b7.zoom=1;if((b9>=1||b9==="")&&bI.trim(b6.replace(bj,""))===""&&b7.removeAttribute){b7.removeAttribute("filter");if(b9===""||i&&!i.filter){return}}b7.filter=bj.test(b6)?b6.replace(bj,e):b6+" "+e}}}bI.cssHooks.marginRight=a7(D.reliableMarginRight,function(i,e){if(e){return bI.swap(i,{display:"inline-block"},G,[i,"marginRight"])}});bI.each({margin:"",padding:"",border:"Width"},function(e,i){bI.cssHooks[e+i]={expand:function(b8){var b7=0,b6={},b9=typeof b8==="string"?b8.split(" "):[b8];for(;b7<4;b7++){b6[e+bT[b7]+i]=b9[b7]||b9[b7-2]||b9[0]}return b6}};if(!aZ.test(e)){bI.cssHooks[e+i].set=aN}});bI.fn.extend({css:function(e,i){return aB(this,function(ca,b7,cb){var b9,b6,cc={},b8=0;if(bI.isArray(b7)){b9=bq(ca);b6=b7.length;for(;b8<b6;b8++){cc[b7[b8]]=bI.css(ca,b7[b8],false,b9)}return cc}return cb!==undefined?bI.style(ca,b7,cb):bI.css(ca,b7)},e,i,arguments.length>1)},show:function(){return s(this,true)},hide:function(){return s(this)},toggle:function(e){if(typeof e==="boolean"){return e?this.show():this.hide()}return this.each(function(){if(S(this)){bI(this).show()}else{bI(this).hide()}})}});function J(b6,i,b8,e,b7){return new J.prototype.init(b6,i,b8,e,b7)}bI.Tween=J;J.prototype={constructor:J,init:function(b7,i,b9,e,b8,b6){this.elem=b7;this.prop=b9;this.easing=b8||"swing";this.options=i;this.start=this.now=this.cur();this.end=e;this.unit=b6||(bI.cssNumber[b9]?"":"px")},cur:function(){var e=J.propHooks[this.prop];return e&&e.get?e.get(this):J.propHooks._default.get(this)},run:function(b6){var i,e=J.propHooks[this.prop];if(this.options.duration){this.pos=i=bI.easing[this.easing](b6,this.options.duration*b6,0,1,this.options.duration)}else{this.pos=i=b6}this.now=(this.end-this.start)*i+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this)}if(e&&e.set){e.set(this)}else{J.propHooks._default.set(this)}return this}};J.prototype.init.prototype=J.prototype;J.propHooks={_default:{get:function(i){var e;if(i.elem[i.prop]!=null&&(!i.elem.style||i.elem.style[i.prop]==null)){return i.elem[i.prop]}e=bI.css(i.elem,i.prop,"");return !e||e==="auto"?0:e},set:function(e){if(bI.fx.step[e.prop]){bI.fx.step[e.prop](e)}else{if(e.elem.style&&(e.elem.style[bI.cssProps[e.prop]]!=null||bI.cssHooks[e.prop])){bI.style(e.elem,e.prop,e.now+e.unit)}else{e.elem[e.prop]=e.now}}}}};J.propHooks.scrollTop=J.propHooks.scrollLeft={set:function(e){if(e.elem.nodeType&&e.elem.parentNode){e.elem[e.prop]=e.now}}};bI.easing={linear:function(e){return e},swing:function(e){return 0.5-Math.cos(e*Math.PI)/2}};bI.fx=J.prototype.init;bI.fx.step={};var N,ae,bR=/^(?:toggle|show|hide)$/,bJ=new RegExp("^(?:([+-])=|)("+aE+")([a-z%]*)$","i"),bP=/queueHooks$/,aG=[h],a2={"*":[function(e,ca){var cc=this.createTween(e,ca),b8=cc.cur(),b7=bJ.exec(ca),cb=b7&&b7[3]||(bI.cssNumber[e]?"":"px"),i=(bI.cssNumber[e]||cb!=="px"&&+b8)&&bJ.exec(bI.css(cc.elem,e)),b6=1,b9=20;if(i&&i[3]!==cb){cb=cb||i[3];b7=b7||[];i=+b8||1;do{b6=b6||".5";i=i/b6;bI.style(cc.elem,e,i+cb)}while(b6!==(b6=cc.cur()/b8)&&b6!==1&&--b9)}if(b7){i=cc.start=+i||+b8||0;cc.unit=cb;cc.end=b7[1]?i+(b7[1]+1)*b7[2]:+b7[2]}return cc}]};function bn(){setTimeout(function(){N=undefined});return(N=bI.now())}function bH(b7,b9){var b8,e={height:b7},b6=0;b9=b9?1:0;for(;b6<4;b6+=2-b9){b8=bT[b6];e["margin"+b8]=e["padding"+b8]=b7}if(b9){e.opacity=e.width=b7}return e}function bd(b8,ca,b7){var i,b9=(a2[ca]||[]).concat(a2["*"]),e=0,b6=b9.length;for(;e<b6;e++){if((i=b9[e].call(b7,ca,b8))){return i}}}function h(b7,cc,e){var b6,cf,b9,ci,cj,cg,cb,ce,b8=this,cd={},i=b7.style,ca=b7.nodeType&&S(b7),ch=bI._data(b7,"fxshow");if(!e.queue){cj=bI._queueHooks(b7,"fx");if(cj.unqueued==null){cj.unqueued=0;cg=cj.empty.fire;cj.empty.fire=function(){if(!cj.unqueued){cg()}}}cj.unqueued++;b8.always(function(){b8.always(function(){cj.unqueued--;if(!bI.queue(b7,"fx").length){cj.empty.fire()}})})}if(b7.nodeType===1&&("height" in cc||"width" in cc)){e.overflow=[i.overflow,i.overflowX,i.overflowY];cb=bI.css(b7,"display");ce=cb==="none"?bI._data(b7,"olddisplay")||a0(b7.nodeName):cb;if(ce==="inline"&&bI.css(b7,"float")==="none"){if(!D.inlineBlockNeedsLayout||a0(b7.nodeName)==="inline"){i.display="inline-block"}else{i.zoom=1}}}if(e.overflow){i.overflow="hidden";if(!D.shrinkWrapBlocks()){b8.always(function(){i.overflow=e.overflow[0];i.overflowX=e.overflow[1];i.overflowY=e.overflow[2]})}}for(b6 in cc){cf=cc[b6];if(bR.exec(cf)){delete cc[b6];b9=b9||cf==="toggle";if(cf===(ca?"hide":"show")){if(cf==="show"&&ch&&ch[b6]!==undefined){ca=true}else{continue}}cd[b6]=ch&&ch[b6]||bI.style(b7,b6)}else{cb=undefined}}if(!bI.isEmptyObject(cd)){if(ch){if("hidden" in ch){ca=ch.hidden}}else{ch=bI._data(b7,"fxshow",{})}if(b9){ch.hidden=!ca}if(ca){bI(b7).show()}else{b8.done(function(){bI(b7).hide()})}b8.done(function(){var ck;bI._removeData(b7,"fxshow");for(ck in cd){bI.style(b7,ck,cd[ck])}});for(b6 in cd){ci=bd(ca?ch[b6]:0,b6,b8);if(!(b6 in ch)){ch[b6]=ci.start;if(ca){ci.end=ci.start;ci.start=b6==="width"||b6==="height"?1:0}}}}else{if((cb==="none"?a0(b7.nodeName):cb)==="inline"){i.display=cb}}}function ao(b7,b9){var b6,i,ca,b8,e;for(b6 in b7){i=bI.camelCase(b6);ca=b9[i];b8=b7[b6];if(bI.isArray(b8)){ca=b8[1];b8=b7[b6]=b8[0]}if(b6!==i){b7[i]=b8;delete b7[b6]}e=bI.cssHooks[i];if(e&&"expand" in e){b8=e.expand(b8);delete b7[i];for(b6 in b8){if(!(b6 in b7)){b7[b6]=b8[b6];b9[b6]=ca}}}else{b9[i]=ca}}}function f(b6,ca,cd){var ce,e,b9=0,i=aG.length,cc=bI.Deferred().always(function(){delete b8.elem}),b8=function(){if(e){return false}var ck=N||bn(),ch=Math.max(0,b7.startTime+b7.duration-ck),cf=ch/b7.duration||0,cj=1-cf,cg=0,ci=b7.tweens.length;for(;cg<ci;cg++){b7.tweens[cg].run(cj)}cc.notifyWith(b6,[b7,cj,ch]);if(cj<1&&ci){return ch}else{cc.resolveWith(b6,[b7]);return false}},b7=cc.promise({elem:b6,props:bI.extend({},ca),opts:bI.extend(true,{specialEasing:{}},cd),originalProperties:ca,originalOptions:cd,startTime:N||bn(),duration:cd.duration,tweens:[],createTween:function(ch,cf){var cg=bI.Tween(b6,b7.opts,ch,cf,b7.opts.specialEasing[ch]||b7.opts.easing);b7.tweens.push(cg);return cg},stop:function(cg){var cf=0,ch=cg?b7.tweens.length:0;if(e){return this}e=true;for(;cf<ch;cf++){b7.tweens[cf].run(1)}if(cg){cc.resolveWith(b6,[b7,cg])}else{cc.rejectWith(b6,[b7,cg])}return this}}),cb=b7.props;ao(cb,b7.opts.specialEasing);for(;b9<i;b9++){ce=aG[b9].call(b7,b6,cb,b7.opts);if(ce){return ce}}bI.map(cb,bd,b7);if(bI.isFunction(b7.opts.start)){b7.opts.start.call(b6,b7)}bI.fx.timer(bI.extend(b8,{elem:b6,anim:b7,queue:b7.opts.queue}));return b7.progress(b7.opts.progress).done(b7.opts.done,b7.opts.complete).fail(b7.opts.fail).always(b7.opts.always)}bI.Animation=bI.extend(f,{tweener:function(i,b8){if(bI.isFunction(i)){b8=i;i=["*"]}else{i=i.split(" ")}var b7,e=0,b6=i.length;for(;e<b6;e++){b7=i[e];a2[b7]=a2[b7]||[];a2[b7].unshift(b8)}},prefilter:function(i,e){if(e){aG.unshift(i)}else{aG.push(i)}}});bI.speed=function(b6,b7,i){var e=b6&&typeof b6==="object"?bI.extend({},b6):{complete:i||!i&&b7||bI.isFunction(b6)&&b6,duration:b6,easing:i&&b7||b7&&!bI.isFunction(b7)&&b7};e.duration=bI.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in bI.fx.speeds?bI.fx.speeds[e.duration]:bI.fx.speeds._default;if(e.queue==null||e.queue===true){e.queue="fx"}e.old=e.complete;e.complete=function(){if(bI.isFunction(e.old)){e.old.call(this)}if(e.queue){bI.dequeue(this,e.queue)}};return e};bI.fn.extend({fadeTo:function(e,b7,b6,i){return this.filter(S).css("opacity",0).show().end().animate({opacity:b7},e,b6,i)},animate:function(ca,b7,b9,b8){var b6=bI.isEmptyObject(ca),e=bI.speed(b7,b9,b8),i=function(){var cb=f(this,bI.extend({},ca),e);if(b6||bI._data(this,"finish")){cb.stop(true)}};i.finish=i;return b6||e.queue===false?this.each(i):this.queue(e.queue,i)},stop:function(b6,i,e){var b7=function(b8){var b9=b8.stop;delete b8.stop;b9(e)};if(typeof b6!=="string"){e=i;i=b6;b6=undefined}if(i&&b6!==false){this.queue(b6||"fx",[])}return this.each(function(){var cb=true,b8=b6!=null&&b6+"queueHooks",ca=bI.timers,b9=bI._data(this);if(b8){if(b9[b8]&&b9[b8].stop){b7(b9[b8])}}else{for(b8 in b9){if(b9[b8]&&b9[b8].stop&&bP.test(b8)){b7(b9[b8])}}}for(b8=ca.length;b8--;){if(ca[b8].elem===this&&(b6==null||ca[b8].queue===b6)){ca[b8].anim.stop(e);cb=false;ca.splice(b8,1)}}if(cb||!e){bI.dequeue(this,b6)}})},finish:function(e){if(e!==false){e=e||"fx"}return this.each(function(){var b7,ca=bI._data(this),b6=ca[e+"queue"],i=ca[e+"queueHooks"],b9=bI.timers,b8=b6?b6.length:0;ca.finish=true;bI.queue(this,e,[]);if(i&&i.stop){i.stop.call(this,true)}for(b7=b9.length;b7--;){if(b9[b7].elem===this&&b9[b7].queue===e){b9[b7].anim.stop(true);b9.splice(b7,1)}}for(b7=0;b7<b8;b7++){if(b6[b7]&&b6[b7].finish){b6[b7].finish.call(this)}}delete ca.finish})}});bI.each(["toggle","show","hide"],function(b6,e){var b7=bI.fn[e];bI.fn[e]=function(i,b9,b8){return i==null||typeof i==="boolean"?b7.apply(this,arguments):this.animate(bH(e,true),i,b9,b8)}});bI.each({slideDown:bH("show"),slideUp:bH("hide"),slideToggle:bH("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,i){bI.fn[e]=function(b6,b8,b7){return this.animate(i,b6,b8,b7)}});bI.timers=[];bI.fx.tick=function(){var b7,b6=bI.timers,e=0;N=bI.now();for(;e<b6.length;e++){b7=b6[e];if(!b7()&&b6[e]===b7){b6.splice(e--,1)}}if(!b6.length){bI.fx.stop()}N=undefined};bI.fx.timer=function(e){bI.timers.push(e);if(e()){bI.fx.start()}else{bI.timers.pop()}};bI.fx.interval=13;bI.fx.start=function(){if(!ae){ae=setInterval(bI.fx.tick,bI.fx.interval)}};bI.fx.stop=function(){clearInterval(ae);ae=null};bI.fx.speeds={slow:600,fast:200,_default:400};bI.fn.delay=function(i,e){i=bI.fx?bI.fx.speeds[i]||i:i;e=e||"fx";return this.queue(e,function(b7,b6){var b8=setTimeout(b7,i);b6.stop=function(){clearTimeout(b8)}})};(function(){var b6,b8,e,i,b7;b8=n.createElement("div");b8.setAttribute("className","t");b8.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";i=b8.getElementsByTagName("a")[0];e=n.createElement("select");b7=e.appendChild(n.createElement("option"));b6=b8.getElementsByTagName("input")[0];i.style.cssText="top:1px";D.getSetAttribute=b8.className!=="t";D.style=/top/.test(i.getAttribute("style"));D.hrefNormalized=i.getAttribute("href")==="/a";D.checkOn=!!b6.value;D.optSelected=b7.selected;D.enctype=!!n.createElement("form").enctype;e.disabled=true;D.optDisabled=!b7.disabled;b6=n.createElement("input");b6.setAttribute("value","");D.input=b6.getAttribute("value")==="";b6.value="t";b6.setAttribute("type","radio");D.radioValue=b6.value==="t"})();var al=/\r/g;bI.fn.extend({val:function(b7){var e,i,b8,b6=this[0];if(!arguments.length){if(b6){e=bI.valHooks[b6.type]||bI.valHooks[b6.nodeName.toLowerCase()];if(e&&"get" in e&&(i=e.get(b6,"value"))!==undefined){return i}i=b6.value;return typeof i==="string"?i.replace(al,""):i==null?"":i}return}b8=bI.isFunction(b7);return this.each(function(b9){var ca;if(this.nodeType!==1){return}if(b8){ca=b7.call(this,b9,bI(this).val())}else{ca=b7}if(ca==null){ca=""}else{if(typeof ca==="number"){ca+=""}else{if(bI.isArray(ca)){ca=bI.map(ca,function(cb){return cb==null?"":cb+""})}}}e=bI.valHooks[this.type]||bI.valHooks[this.nodeName.toLowerCase()];if(!e||!("set" in e)||e.set(this,ca,"value")===undefined){this.value=ca}})}});bI.extend({valHooks:{option:{get:function(e){var i=bI.find.attr(e,"value");return i!=null?i:bI.trim(bI.text(e))}},select:{get:function(e){var cb,b7,cd=e.options,b9=e.selectedIndex,b8=e.type==="select-one"||b9<0,cc=b8?null:[],ca=b8?b9+1:cd.length,b6=b9<0?ca:b8?b9:0;for(;b6<ca;b6++){b7=cd[b6];if((b7.selected||b6===b9)&&(D.optDisabled?!b7.disabled:b7.getAttribute("disabled")===null)&&(!b7.parentNode.disabled||!bI.nodeName(b7.parentNode,"optgroup"))){cb=bI(b7).val();if(b8){return cb}cc.push(cb)}}return cc},set:function(ca,cb){var cc,b9,b7=ca.options,e=bI.makeArray(cb),b8=b7.length;while(b8--){b9=b7[b8];if(bI.inArray(bI.valHooks.option.get(b9),e)>=0){try{b9.selected=cc=true}catch(b6){b9.scrollHeight}}else{b9.selected=false}}if(!cc){ca.selectedIndex=-1}return b7}}}});bI.each(["radio","checkbox"],function(){bI.valHooks[this]={set:function(e,i){if(bI.isArray(i)){return(e.checked=bI.inArray(bI(e).val(),i)>=0)}}};if(!D.checkOn){bI.valHooks[this].get=function(e){return e.getAttribute("value")===null?"on":e.value}}});var ba,b3,bO=bI.expr.attrHandle,aq=/^(?:checked|selected)$/i,bN=D.getSetAttribute,bF=D.input;bI.fn.extend({attr:function(e,i){return aB(this,bI.attr,e,i,arguments.length>1)},removeAttr:function(e){return this.each(function(){bI.removeAttr(this,e)})}});bI.extend({attr:function(b8,b7,b9){var e,b6,i=b8.nodeType;if(!b8||i===3||i===8||i===2){return}if(typeof b8.getAttribute===aC){return bI.prop(b8,b7,b9)}if(i!==1||!bI.isXMLDoc(b8)){b7=b7.toLowerCase();e=bI.attrHooks[b7]||(bI.expr.match.bool.test(b7)?b3:ba)}if(b9!==undefined){if(b9===null){bI.removeAttr(b8,b7)}else{if(e&&"set" in e&&(b6=e.set(b8,b9,b7))!==undefined){return b6}else{b8.setAttribute(b7,b9+"");return b9}}}else{if(e&&"get" in e&&(b6=e.get(b8,b7))!==null){return b6}else{b6=bI.find.attr(b8,b7);return b6==null?undefined:b6}}},removeAttr:function(b7,b9){var e,b8,b6=0,ca=b9&&b9.match(aF);if(ca&&b7.nodeType===1){while((e=ca[b6++])){b8=bI.propFix[e]||e;if(bI.expr.match.bool.test(e)){if(bF&&bN||!aq.test(e)){b7[b8]=false}else{b7[bI.camelCase("default-"+e)]=b7[b8]=false}}else{bI.attr(b7,e,"")}b7.removeAttribute(bN?e:b8)}}},attrHooks:{type:{set:function(e,i){if(!D.radioValue&&i==="radio"&&bI.nodeName(e,"input")){var b6=e.value;e.setAttribute("type",i);if(b6){e.value=b6}return i}}}}});b3={set:function(i,b6,e){if(b6===false){bI.removeAttr(i,e)}else{if(bF&&bN||!aq.test(e)){i.setAttribute(!bN&&bI.propFix[e]||e,e)}else{i[bI.camelCase("default-"+e)]=i[e]=true}}return e}};bI.each(bI.expr.match.bool.source.match(/\w+/g),function(b7,b6){var e=bO[b6]||bI.find.attr;bO[b6]=bF&&bN||!aq.test(b6)?function(b9,b8,cb){var i,ca;if(!cb){ca=bO[b8];bO[b8]=i;i=e(b9,b8,cb)!=null?b8.toLowerCase():null;bO[b8]=ca}return i}:function(b8,i,b9){if(!b9){return b8[bI.camelCase("default-"+i)]?i.toLowerCase():null}}});if(!bF||!bN){bI.attrHooks.value={set:function(i,b6,e){if(bI.nodeName(i,"input")){i.defaultValue=b6}else{return ba&&ba.set(i,b6,e)}}}}if(!bN){ba={set:function(b6,b7,i){var e=b6.getAttributeNode(i);if(!e){b6.setAttributeNode((e=b6.ownerDocument.createAttribute(i)))}e.value=b7+="";if(i==="value"||b7===b6.getAttribute(i)){return b7}}};bO.id=bO.name=bO.coords=function(b6,i,b7){var e;if(!b7){return(e=b6.getAttributeNode(i))&&e.value!==""?e.value:null}};bI.valHooks.button={get:function(b6,i){var e=b6.getAttributeNode(i);if(e&&e.specified){return e.value}},set:ba.set};bI.attrHooks.contenteditable={set:function(i,b6,e){ba.set(i,b6===""?false:b6,e)}};bI.each(["width","height"],function(b6,e){bI.attrHooks[e]={set:function(i,b7){if(b7===""){i.setAttribute(e,"auto");return b7}}}})}if(!D.style){bI.attrHooks.style={get:function(e){return e.style.cssText||undefined},set:function(e,i){return(e.style.cssText=i+"")}}}var aJ=/^(?:input|select|textarea|button|object)$/i,F=/^(?:a|area)$/i;bI.fn.extend({prop:function(e,i){return aB(this,bI.prop,e,i,arguments.length>1)},removeProp:function(e){e=bI.propFix[e]||e;return this.each(function(){try{this[e]=undefined;delete this[e]}catch(i){}})}});bI.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(b9,b7,ca){var b6,e,b8,i=b9.nodeType;if(!b9||i===3||i===8||i===2){return}b8=i!==1||!bI.isXMLDoc(b9);if(b8){b7=bI.propFix[b7]||b7;e=bI.propHooks[b7]}if(ca!==undefined){return e&&"set" in e&&(b6=e.set(b9,ca,b7))!==undefined?b6:(b9[b7]=ca)}else{return e&&"get" in e&&(b6=e.get(b9,b7))!==null?b6:b9[b7]}},propHooks:{tabIndex:{get:function(i){var e=bI.find.attr(i,"tabindex");return e?parseInt(e,10):aJ.test(i.nodeName)||F.test(i.nodeName)&&i.href?0:-1}}}});if(!D.hrefNormalized){bI.each(["href","src"],function(b6,e){bI.propHooks[e]={get:function(i){return i.getAttribute(e,4)}}})}if(!D.optSelected){bI.propHooks.selected={get:function(i){var e=i.parentNode;if(e){e.selectedIndex;if(e.parentNode){e.parentNode.selectedIndex}}return null}}}bI.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){bI.propFix[this.toLowerCase()]=this});if(!D.enctype){bI.propFix.enctype="encoding"}var bL=/[\t\r\n\f]/g;bI.fn.extend({addClass:function(cd){var b7,b6,ce,cb,b8,e,b9=0,ca=this.length,cc=typeof cd==="string"&&cd;if(bI.isFunction(cd)){return this.each(function(i){bI(this).addClass(cd.call(this,i,this.className))})}if(cc){b7=(cd||"").match(aF)||[];for(;b9<ca;b9++){b6=this[b9];ce=b6.nodeType===1&&(b6.className?(" "+b6.className+" ").replace(bL," "):" ");if(ce){b8=0;while((cb=b7[b8++])){if(ce.indexOf(" "+cb+" ")<0){ce+=cb+" "}}e=bI.trim(ce);if(b6.className!==e){b6.className=e}}}}return this},removeClass:function(cd){var b7,b6,ce,cb,b8,e,b9=0,ca=this.length,cc=arguments.length===0||typeof cd==="string"&&cd;if(bI.isFunction(cd)){return this.each(function(i){bI(this).removeClass(cd.call(this,i,this.className))})}if(cc){b7=(cd||"").match(aF)||[];for(;b9<ca;b9++){b6=this[b9];ce=b6.nodeType===1&&(b6.className?(" "+b6.className+" ").replace(bL," "):"");if(ce){b8=0;while((cb=b7[b8++])){while(ce.indexOf(" "+cb+" ")>=0){ce=ce.replace(" "+cb+" "," ")}}e=cd?bI.trim(ce):"";if(b6.className!==e){b6.className=e}}}}return this},toggleClass:function(b6,e){var i=typeof b6;if(typeof e==="boolean"&&i==="string"){return e?this.addClass(b6):this.removeClass(b6)}if(bI.isFunction(b6)){return this.each(function(b7){bI(this).toggleClass(b6.call(this,b7,this.className,e),e)})}return this.each(function(){if(i==="string"){var b9,b8=0,b7=bI(this),ca=b6.match(aF)||[];while((b9=ca[b8++])){if(b7.hasClass(b9)){b7.removeClass(b9)}else{b7.addClass(b9)}}}else{if(i===aC||i==="boolean"){if(this.className){bI._data(this,"__className__",this.className)}this.className=this.className||b6===false?"":bI._data(this,"__className__")||""}}})},hasClass:function(e){var b8=" "+e+" ",b7=0,b6=this.length;for(;b7<b6;b7++){if(this[b7].nodeType===1&&(" "+this[b7].className+" ").replace(bL," ").indexOf(b8)>=0){return true}}return false}});bI.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(b6,e){bI.fn[e]=function(b7,i){return arguments.length>0?this.on(e,null,b7,i):this.trigger(e)}});bI.fn.extend({hover:function(e,i){return this.mouseenter(e).mouseleave(i||e)},bind:function(e,b6,i){return this.on(e,null,b6,i)},unbind:function(e,i){return this.off(e,null,i)},delegate:function(e,i,b7,b6){return this.on(i,e,b7,b6)},undelegate:function(e,i,b6){return arguments.length===1?this.off(e,"**"):this.off(i,e||"**",b6)}});var bp=bI.now();var bQ=(/\?/);var a1=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;bI.parseJSON=function(e){if(a5.JSON&&a5.JSON.parse){return a5.JSON.parse(e+"")}var b7,b6=null,i=bI.trim(e+"");return i&&!bI.trim(i.replace(a1,function(ca,b8,b9,cb){if(b7&&b8){b6=0}if(b6===0){return ca}b7=b9||b8;b6+=!cb-!b9;return""}))?(Function("return "+i))():bI.error("Invalid JSON: "+e)};bI.parseXML=function(b7){var i,b6;if(!b7||typeof b7!=="string"){return null}try{if(a5.DOMParser){b6=new DOMParser();i=b6.parseFromString(b7,"text/xml")}else{i=new ActiveXObject("Microsoft.XMLDOM");i.async="false";i.loadXML(b7)}}catch(b8){i=undefined}if(!i||!i.documentElement||i.getElementsByTagName("parsererror").length){bI.error("Invalid XML: "+b7)}return i};var b4,aa,ap=/#.*$/,R=/([?&])_=[^&]*/,ah=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,C=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,r=/^(?:GET|HEAD)$/,aK=/^\/\//,aV=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,w={},a9={},aX="*/".concat("*");try{aa=location.href}catch(bi){aa=n.createElement("a");aa.href="";aa=aa.href}b4=aV.exec(aa.toLowerCase())||[];function bK(e){return function(b9,ca){if(typeof b9!=="string"){ca=b9;b9="*"}var b6,b7=0,b8=b9.toLowerCase().match(aF)||[];if(bI.isFunction(ca)){while((b6=b8[b7++])){if(b6.charAt(0)==="+"){b6=b6.slice(1)||"*";(e[b6]=e[b6]||[]).unshift(ca)}else{(e[b6]=e[b6]||[]).push(ca)}}}}}function p(e,b6,ca,b7){var i={},b8=(e===a9);function b9(cb){var cc;i[cb]=true;bI.each(e[cb]||[],function(ce,cd){var cf=cd(b6,ca,b7);if(typeof cf==="string"&&!b8&&!i[cf]){b6.dataTypes.unshift(cf);b9(cf);return false}else{if(b8){return !(cc=cf)}}});return cc}return b9(b6.dataTypes[0])||!i["*"]&&b9("*")}function t(b6,b7){var e,i,b8=bI.ajaxSettings.flatOptions||{};for(i in b7){if(b7[i]!==undefined){(b8[i]?b6:(e||(e={})))[i]=b7[i]}}if(e){bI.extend(true,b6,e)}return b6}function g(cc,cb,b8){var e,b7,b6,b9,i=cc.contents,ca=cc.dataTypes;while(ca[0]==="*"){ca.shift();if(b7===undefined){b7=cc.mimeType||cb.getResponseHeader("Content-Type")}}if(b7){for(b9 in i){if(i[b9]&&i[b9].test(b7)){ca.unshift(b9);break}}}if(ca[0] in b8){b6=ca[0]}else{for(b9 in b8){if(!ca[0]||cc.converters[b9+" "+ca[0]]){b6=b9;break}if(!e){e=b9}}b6=b6||e}if(b6){if(b6!==ca[0]){ca.unshift(b6)}return b8[b6]}}function ag(cg,b8,cd,b6){var i,cb,ce,b9,b7,cf={},cc=cg.dataTypes.slice();if(cc[1]){for(ce in cg.converters){cf[ce.toLowerCase()]=cg.converters[ce]}}cb=cc.shift();while(cb){if(cg.responseFields[cb]){cd[cg.responseFields[cb]]=b8}if(!b7&&b6&&cg.dataFilter){b8=cg.dataFilter(b8,cg.dataType)}b7=cb;cb=cc.shift();if(cb){if(cb==="*"){cb=b7}else{if(b7!=="*"&&b7!==cb){ce=cf[b7+" "+cb]||cf["* "+cb];if(!ce){for(i in cf){b9=i.split(" ");if(b9[1]===cb){ce=cf[b7+" "+b9[0]]||cf["* "+b9[0]];if(ce){if(ce===true){ce=cf[i]}else{if(cf[i]!==true){cb=b9[0];cc.unshift(b9[1])}}break}}}}if(ce!==true){if(ce&&cg["throws"]){b8=ce(b8)}else{try{b8=ce(b8)}catch(ca){return{state:"parsererror",error:ce?ca:"No conversion from "+b7+" to "+cb}}}}}}}}return{state:"success",data:b8}}bI.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:aa,type:"GET",isLocal:C.test(b4[1]),global:true,processData:true,async:true,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":aX,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":true,"text json":bI.parseJSON,"text xml":bI.parseXML},flatOptions:{url:true,context:true}},ajaxSetup:function(i,e){return e?t(t(i,bI.ajaxSettings),e):t(bI.ajaxSettings,i)},ajaxPrefilter:bK(w),ajaxTransport:bK(a9),ajax:function(ca,b7){if(typeof ca==="object"){b7=ca;ca=undefined}b7=b7||{};var cj,cl,cb,cq,cf,b6,cm,b8,ce=bI.ajaxSetup({},b7),cs=ce.context||ce,ch=ce.context&&(cs.nodeType||cs.jquery)?bI(cs):bI.event,cr=bI.Deferred(),co=bI.Callbacks("once memory"),cc=ce.statusCode||{},ci={},cp={},b9=0,cd="canceled",ck={readyState:0,getResponseHeader:function(i){var e;if(b9===2){if(!b8){b8={};while((e=ah.exec(cq))){b8[e[1].toLowerCase()]=e[2]}}e=b8[i.toLowerCase()]}return e==null?null:e},getAllResponseHeaders:function(){return b9===2?cq:null},setRequestHeader:function(i,ct){var e=i.toLowerCase();if(!b9){i=cp[e]=cp[e]||i;ci[i]=ct}return this},overrideMimeType:function(e){if(!b9){ce.mimeType=e}return this},statusCode:function(i){var e;if(i){if(b9<2){for(e in i){cc[e]=[cc[e],i[e]]}}else{ck.always(i[ck.status])}}return this},abort:function(i){var e=i||cd;if(cm){cm.abort(e)}cg(0,e);return this}};cr.promise(ck).complete=co.add;ck.success=ck.done;ck.error=ck.fail;ce.url=((ca||ce.url||aa)+"").replace(ap,"").replace(aK,b4[1]+"//");ce.type=b7.method||b7.type||ce.method||ce.type;ce.dataTypes=bI.trim(ce.dataType||"*").toLowerCase().match(aF)||[""];if(ce.crossDomain==null){cj=aV.exec(ce.url.toLowerCase());ce.crossDomain=!!(cj&&(cj[1]!==b4[1]||cj[2]!==b4[2]||(cj[3]||(cj[1]==="http:"?"80":"443"))!==(b4[3]||(b4[1]==="http:"?"80":"443"))))}if(ce.data&&ce.processData&&typeof ce.data!=="string"){ce.data=bI.param(ce.data,ce.traditional)}p(w,ce,b7,ck);if(b9===2){return ck}b6=bI.event&&ce.global;if(b6&&bI.active++===0){bI.event.trigger("ajaxStart")}ce.type=ce.type.toUpperCase();ce.hasContent=!r.test(ce.type);cb=ce.url;if(!ce.hasContent){if(ce.data){cb=(ce.url+=(bQ.test(cb)?"&":"?")+ce.data);delete ce.data}if(ce.cache===false){ce.url=R.test(cb)?cb.replace(R,"$1_="+bp++):cb+(bQ.test(cb)?"&":"?")+"_="+bp++}}if(ce.ifModified){if(bI.lastModified[cb]){ck.setRequestHeader("If-Modified-Since",bI.lastModified[cb])}if(bI.etag[cb]){ck.setRequestHeader("If-None-Match",bI.etag[cb])}}if(ce.data&&ce.hasContent&&ce.contentType!==false||b7.contentType){ck.setRequestHeader("Content-Type",ce.contentType)}ck.setRequestHeader("Accept",ce.dataTypes[0]&&ce.accepts[ce.dataTypes[0]]?ce.accepts[ce.dataTypes[0]]+(ce.dataTypes[0]!=="*"?", "+aX+"; q=0.01":""):ce.accepts["*"]);for(cl in ce.headers){ck.setRequestHeader(cl,ce.headers[cl])}if(ce.beforeSend&&(ce.beforeSend.call(cs,ck,ce)===false||b9===2)){return ck.abort()}cd="abort";for(cl in {success:1,error:1,complete:1}){ck[cl](ce[cl])}cm=p(a9,ce,b7,ck);if(!cm){cg(-1,"No Transport")}else{ck.readyState=1;if(b6){ch.trigger("ajaxSend",[ck,ce])}if(ce.async&&ce.timeout>0){cf=setTimeout(function(){ck.abort("timeout")},ce.timeout)}try{b9=1;cm.send(ci,cg)}catch(cn){if(b9<2){cg(-1,cn)}else{throw cn}}}function cg(cw,i,cx,cu){var e,cA,cy,cv,cz,ct=i;if(b9===2){return}b9=2;if(cf){clearTimeout(cf)}cm=undefined;cq=cu||"";ck.readyState=cw>0?4:0;e=cw>=200&&cw<300||cw===304;if(cx){cv=g(ce,ck,cx)}cv=ag(ce,cv,ck,e);if(e){if(ce.ifModified){cz=ck.getResponseHeader("Last-Modified");if(cz){bI.lastModified[cb]=cz}cz=ck.getResponseHeader("etag");if(cz){bI.etag[cb]=cz}}if(cw===204||ce.type==="HEAD"){ct="nocontent"}else{if(cw===304){ct="notmodified"}else{ct=cv.state;cA=cv.data;cy=cv.error;e=!cy}}}else{cy=ct;if(cw||!ct){ct="error";if(cw<0){cw=0}}}ck.status=cw;ck.statusText=(i||ct)+"";if(e){cr.resolveWith(cs,[cA,ct,ck])}else{cr.rejectWith(cs,[ck,ct,cy])}ck.statusCode(cc);cc=undefined;if(b6){ch.trigger(e?"ajaxSuccess":"ajaxError",[ck,ce,e?cA:cy])}co.fireWith(cs,[ck,ct]);if(b6){ch.trigger("ajaxComplete",[ck,ce]);if(!(--bI.active)){bI.event.trigger("ajaxStop")}}}return ck},getJSON:function(e,i,b6){return bI.get(e,i,b6,"json")},getScript:function(e,i){return bI.get(e,undefined,i,"script")}});bI.each(["get","post"],function(e,b6){bI[b6]=function(i,b8,b9,b7){if(bI.isFunction(b8)){b7=b7||b9;b9=b8;b8=undefined}return bI.ajax({url:i,type:b6,dataType:b7,data:b8,success:b9})}});bI._evalUrl=function(e){return bI.ajax({url:e,type:"GET",dataType:"script",async:false,global:false,"throws":true})};bI.fn.extend({wrapAll:function(e){if(bI.isFunction(e)){return this.each(function(b6){bI(this).wrapAll(e.call(this,b6))})}if(this[0]){var i=bI(e,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){i.insertBefore(this[0])}i.map(function(){var b6=this;while(b6.firstChild&&b6.firstChild.nodeType===1){b6=b6.firstChild}return b6}).append(this)}return this},wrapInner:function(e){if(bI.isFunction(e)){return this.each(function(b6){bI(this).wrapInner(e.call(this,b6))})}return this.each(function(){var i=bI(this),b6=i.contents();if(b6.length){b6.wrapAll(e)}else{i.append(e)}})},wrap:function(e){var i=bI.isFunction(e);return this.each(function(b6){bI(this).wrapAll(i?e.call(this,b6):e)})},unwrap:function(){return this.parent().each(function(){if(!bI.nodeName(this,"body")){bI(this).replaceWith(this.childNodes)}}).end()}});bI.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||(!D.reliableHiddenOffsets()&&((e.style&&e.style.display)||bI.css(e,"display"))==="none")};bI.expr.filters.visible=function(e){return !bI.expr.filters.hidden(e)};var bw=/%20/g,aS=/\[\]$/,X=/\r?\n/g,b=/^(?:submit|button|image|reset|file)$/i,au=/^(?:input|select|textarea|keygen)/i;function j(b6,b8,i,b7){var e;if(bI.isArray(b8)){bI.each(b8,function(ca,b9){if(i||aS.test(b6)){b7(b6,b9)}else{j(b6+"["+(typeof b9==="object"?ca:"")+"]",b9,i,b7)}})}else{if(!i&&bI.type(b8)==="object"){for(e in b8){j(b6+"["+e+"]",b8[e],i,b7)}}else{b7(b6,b8)}}}bI.param=function(e,b6){var b7,i=[],b8=function(b9,ca){ca=bI.isFunction(ca)?ca():(ca==null?"":ca);i[i.length]=encodeURIComponent(b9)+"="+encodeURIComponent(ca)};if(b6===undefined){b6=bI.ajaxSettings&&bI.ajaxSettings.traditional}if(bI.isArray(e)||(e.jquery&&!bI.isPlainObject(e))){bI.each(e,function(){b8(this.name,this.value)})}else{for(b7 in e){j(b7,e[b7],b6,b8)}}return i.join("&").replace(bw,"+")};bI.fn.extend({serialize:function(){return bI.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=bI.prop(this,"elements");return e?bI.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!bI(this).is(":disabled")&&au.test(this.nodeName)&&!b.test(e)&&(this.checked||!aM.test(e))}).map(function(e,b6){var b7=bI(this).val();return b7==null?null:bI.isArray(b7)?bI.map(b7,function(i){return{name:b6.name,value:i.replace(X,"\r\n")}}):{name:b6.name,value:b7.replace(X,"\r\n")}}).get()}});bI.ajaxSettings.xhr=a5.ActiveXObject!==undefined?function(){return !this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&bE()||bg()}:bE;var aA=0,aj={},ay=bI.ajaxSettings.xhr();if(a5.attachEvent){a5.attachEvent("onunload",function(){for(var e in aj){aj[e](undefined,true)}})}D.cors=!!ay&&("withCredentials" in ay);ay=D.ajax=!!ay;if(ay){bI.ajaxTransport(function(e){if(!e.crossDomain||D.cors){var i;return{send:function(b9,b6){var b7,b8=e.xhr(),ca=++aA;b8.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields){for(b7 in e.xhrFields){b8[b7]=e.xhrFields[b7]}}if(e.mimeType&&b8.overrideMimeType){b8.overrideMimeType(e.mimeType)}if(!e.crossDomain&&!b9["X-Requested-With"]){b9["X-Requested-With"]="XMLHttpRequest"}for(b7 in b9){if(b9[b7]!==undefined){b8.setRequestHeader(b7,b9[b7]+"")}}b8.send((e.hasContent&&e.data)||null);i=function(cd,cc){var cb,cg,ce;if(i&&(cc||b8.readyState===4)){delete aj[ca];i=undefined;b8.onreadystatechange=bI.noop;if(cc){if(b8.readyState!==4){b8.abort()}}else{ce={};cb=b8.status;if(typeof b8.responseText==="string"){ce.text=b8.responseText}try{cg=b8.statusText}catch(cf){cg=""}if(!cb&&e.isLocal&&!e.crossDomain){cb=ce.text?200:404}else{if(cb===1223){cb=204}}}}if(ce){b6(cb,cg,ce,b8.getAllResponseHeaders())}};if(!e.async){i()}else{if(b8.readyState===4){setTimeout(i)}else{b8.onreadystatechange=aj[ca]=i}}},abort:function(){if(i){i(undefined,true)}}}}})}function bE(){try{return new a5.XMLHttpRequest()}catch(i){}}function bg(){try{return new a5.ActiveXObject("Microsoft.XMLHTTP")}catch(i){}}bI.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){bI.globalEval(e);return e}}});bI.ajaxPrefilter("script",function(e){if(e.cache===undefined){e.cache=false}if(e.crossDomain){e.type="GET";e.global=false}});bI.ajaxTransport("script",function(b6){if(b6.crossDomain){var e,i=n.head||bI("head")[0]||n.documentElement;return{send:function(b7,b8){e=n.createElement("script");e.async=true;if(b6.scriptCharset){e.charset=b6.scriptCharset}e.src=b6.url;e.onload=e.onreadystatechange=function(ca,b9){if(b9||!e.readyState||/loaded|complete/.test(e.readyState)){e.onload=e.onreadystatechange=null;if(e.parentNode){e.parentNode.removeChild(e)}e=null;if(!b9){b8(200,"success")}}};i.insertBefore(e,i.firstChild)},abort:function(){if(e){e.onload(undefined,true)}}}}});var bs=[],a8=/(=)\?(?=&|$)|\?\?/;bI.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=bs.pop()||(bI.expando+"_"+(bp++));this[e]=true;return e}});bI.ajaxPrefilter("json jsonp",function(b7,e,b8){var ca,i,b6,b9=b7.jsonp!==false&&(a8.test(b7.url)?"url":typeof b7.data==="string"&&!(b7.contentType||"").indexOf("application/x-www-form-urlencoded")&&a8.test(b7.data)&&"data");if(b9||b7.dataTypes[0]==="jsonp"){ca=b7.jsonpCallback=bI.isFunction(b7.jsonpCallback)?b7.jsonpCallback():b7.jsonpCallback;if(b9){b7[b9]=b7[b9].replace(a8,"$1"+ca)}else{if(b7.jsonp!==false){b7.url+=(bQ.test(b7.url)?"&":"?")+b7.jsonp+"="+ca}}b7.converters["script json"]=function(){if(!b6){bI.error(ca+" was not called")}return b6[0]};b7.dataTypes[0]="json";i=a5[ca];a5[ca]=function(){b6=arguments};b8.always(function(){a5[ca]=i;if(b7[ca]){b7.jsonpCallback=e.jsonpCallback;bs.push(ca)}if(b6&&bI.isFunction(i)){i(b6[0])}b6=i=undefined});return"script"}});bI.parseHTML=function(b8,b6,b7){if(!b8||typeof b8!=="string"){return null}if(typeof b6==="boolean"){b7=b6;b6=false}b6=b6||n;var i=a.exec(b8),e=!b7&&[];if(i){return[b6.createElement(i[1])]}i=bI.buildFragment([b8],b6,e);if(e&&e.length){bI(e).remove()}return bI.merge([],i.childNodes)};var b1=bI.fn.load;bI.fn.load=function(b7,ca,cb){if(typeof b7!=="string"&&b1){return b1.apply(this,arguments)}var e,b6,b8,i=this,b9=b7.indexOf(" ");if(b9>=0){e=bI.trim(b7.slice(b9,b7.length));b7=b7.slice(0,b9)}if(bI.isFunction(ca)){cb=ca;ca=undefined}else{if(ca&&typeof ca==="object"){b8="POST"}}if(i.length>0){bI.ajax({url:b7,type:b8,dataType:"html",data:ca}).done(function(cc){b6=arguments;i.html(e?bI("<div>").append(bI.parseHTML(cc)).find(e):cc)}).complete(cb&&function(cd,cc){i.each(cb,b6||[cd.responseText,cc,cd])})}return this};bI.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,b6){bI.fn[b6]=function(i){return this.on(b6,i)}});bI.expr.filters.animated=function(e){return bI.grep(bI.timers,function(i){return e===i.elem}).length};var bX=a5.document.documentElement;function br(e){return bI.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:false}bI.offset={setOffset:function(b7,ch,cb){var cd,ca,e,b8,b6,cf,cg,cc=bI.css(b7,"position"),b9=bI(b7),ce={};if(cc==="static"){b7.style.position="relative"}b6=b9.offset();e=bI.css(b7,"top");cf=bI.css(b7,"left");cg=(cc==="absolute"||cc==="fixed")&&bI.inArray("auto",[e,cf])>-1;if(cg){cd=b9.position();b8=cd.top;ca=cd.left}else{b8=parseFloat(e)||0;ca=parseFloat(cf)||0}if(bI.isFunction(ch)){ch=ch.call(b7,cb,b6)}if(ch.top!=null){ce.top=(ch.top-b6.top)+b8}if(ch.left!=null){ce.left=(ch.left-b6.left)+ca}if("using" in ch){ch.using.call(b7,ce)}else{b9.css(ce)}}};bI.fn.extend({offset:function(i){if(arguments.length){return i===undefined?this:this.each(function(ca){bI.offset.setOffset(this,i,ca)})}var e,b9,b7={top:0,left:0},b6=this[0],b8=b6&&b6.ownerDocument;if(!b8){return}e=b8.documentElement;if(!bI.contains(e,b6)){return b7}if(typeof b6.getBoundingClientRect!==aC){b7=b6.getBoundingClientRect()}b9=br(b8);return{top:b7.top+(b9.pageYOffset||e.scrollTop)-(e.clientTop||0),left:b7.left+(b9.pageXOffset||e.scrollLeft)-(e.clientLeft||0)}},position:function(){if(!this[0]){return}var b6,b7,e={top:0,left:0},i=this[0];if(bI.css(i,"position")==="fixed"){b7=i.getBoundingClientRect()}else{b6=this.offsetParent();b7=this.offset();if(!bI.nodeName(b6[0],"html")){e=b6.offset()}e.top+=bI.css(b6[0],"borderTopWidth",true);e.left+=bI.css(b6[0],"borderLeftWidth",true)}return{top:b7.top-e.top-bI.css(i,"marginTop",true),left:b7.left-e.left-bI.css(i,"marginLeft",true)}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||bX;while(e&&(!bI.nodeName(e,"html")&&bI.css(e,"position")==="static")){e=e.offsetParent}return e||bX})}});bI.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b6,i){var e=/Y/.test(i);bI.fn[b6]=function(b7){return aB(this,function(b8,cb,ca){var b9=br(b8);if(ca===undefined){return b9?(i in b9)?b9[i]:b9.document.documentElement[cb]:b8[cb]}if(b9){b9.scrollTo(!e?ca:bI(b9).scrollLeft(),e?ca:bI(b9).scrollTop())}else{b8[cb]=ca}},b6,b7,arguments.length,null)}});bI.each(["top","left"],function(e,b6){bI.cssHooks[b6]=a7(D.pixelPosition,function(b7,i){if(i){i=G(b7,b6);return Y.test(i)?bI(b7).position()[b6]+"px":i}})});bI.each({Height:"height",Width:"width"},function(e,i){bI.each({padding:"inner"+e,content:i,"":"outer"+e},function(b6,b7){bI.fn[b7]=function(cb,ca){var b9=arguments.length&&(b6||typeof cb!=="boolean"),b8=b6||(cb===true||ca===true?"margin":"border");return aB(this,function(cd,cc,ce){var cf;if(bI.isWindow(cd)){return cd.document.documentElement["client"+e]}if(cd.nodeType===9){cf=cd.documentElement;return Math.max(cd.body["scroll"+e],cf["scroll"+e],cd.body["offset"+e],cf["offset"+e],cf["client"+e])}return ce===undefined?bI.css(cd,cc,b8):bI.style(cd,cc,ce,b8)},i,b9?cb:undefined,b9,null)}})});bI.fn.size=function(){return this.length};bI.fn.andSelf=bI.fn.addBack;if(typeof define==="function"&&define.amd){define("jquery",[],function(){return bI})}var bk=a5.jQuery,I=a5.$;bI.noConflict=function(e){if(a5.$===bI){a5.$=I}if(e&&a5.jQuery===bI){a5.jQuery=bk}return bI};if(typeof av===aC){a5.jQuery=a5.$=bI}return bI}));!function(a){a(function(){a.support.transition=(function(){var b=(function(){var e=document.createElement("bootstrap"),d={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},c;for(c in d){if(e.style[c]!==undefined){return d[c]}}}());return b&&{end:b}})()})}(window.jQuery);!function(d){var c='[data-dismiss="alert"]',b=function(e){d(e).on("click",c,this.close)};b.prototype.close=function(j){var i=d(this),g=i.attr("data-target"),h;if(!g){g=i.attr("href");g=g&&g.replace(/.*(?=#[^\s]*$)/,"")}h=d(g);j&&j.preventDefault();h.length||(h=i.hasClass("alert")?i:i.parent());h.trigger(j=d.Event("close"));if(j.isDefaultPrevented()){return}h.removeClass("in");function f(){h.trigger("closed").remove()}d.support.transition&&h.hasClass("fade")?h.on(d.support.transition.end,f):f()};var a=d.fn.alert;d.fn.alert=function(e){return this.each(function(){var g=d(this),f=g.data("alert");if(!f){g.data("alert",(f=new b(this)))}if(typeof e=="string"){f[e].call(g)}})};d.fn.alert.Constructor=b;d.fn.alert.noConflict=function(){d.fn.alert=a;return this};d(document).on("click.alert.data-api",c,b.prototype.close)}(window.jQuery);!function(c){var b=function(e,d){this.$element=c(e);this.options=c.extend({},c.fn.button.defaults,d)};b.prototype.setState=function(g){var i="disabled",e=this.$element,f=e.data(),h=e.is("input")?"val":"html";g=g+"Text";f.resetText||e.data("resetText",e[h]());e[h](f[g]||this.options[g]);setTimeout(function(){g=="loadingText"?e.addClass(i).attr(i,i):e.removeClass(i).removeAttr(i)},0)};b.prototype.toggle=function(){var d=this.$element.closest('[data-toggle="buttons-radio"]');d&&d.find(".active").removeClass("active");this.$element.toggleClass("active")};var a=c.fn.button;c.fn.button=function(d){return this.each(function(){var g=c(this),f=g.data("button"),e=typeof d=="object"&&d;if(!f){g.data("button",(f=new b(this,e)))}if(d=="toggle"){f.toggle()}else{if(d){f.setState(d)}}})};c.fn.button.defaults={loadingText:"loading..."};c.fn.button.Constructor=b;c.fn.button.noConflict=function(){c.fn.button=a;return this};c(document).on("click.button.data-api","[data-toggle^=button]",function(f){var d=c(f.target);if(!d.hasClass("btn")){d=d.closest(".btn")}d.button("toggle")})}(window.jQuery);!function(b){var c=function(e,d){this.$element=b(e);this.$indicators=this.$element.find(".carousel-indicators");this.options=d;this.options.pause=="hover"&&this.$element.on("mouseenter",b.proxy(this.pause,this)).on("mouseleave",b.proxy(this.cycle,this))};c.prototype={cycle:function(d){if(!d){this.paused=false}if(this.interval){clearInterval(this.interval)}this.options.interval&&!this.paused&&(this.interval=setInterval(b.proxy(this.next,this),this.options.interval));return this},getActiveIndex:function(){this.$active=this.$element.find(".item.active");this.$items=this.$active.parent().children();return this.$items.index(this.$active)},to:function(f){var d=this.getActiveIndex(),e=this;if(f>(this.$items.length-1)||f<0){return}if(this.sliding){return this.$element.one("slid",function(){e.to(f)})}if(d==f){return this.pause().cycle()}return this.slide(f>d?"next":"prev",b(this.$items[f]))},pause:function(d){if(!d){this.paused=true}if(this.$element.find(".next, .prev").length&&b.support.transition.end){this.$element.trigger(b.support.transition.end);this.cycle(true)}clearInterval(this.interval);this.interval=null;return this},next:function(){if(this.sliding){return}return this.slide("next")},prev:function(){if(this.sliding){return}return this.slide("prev")},slide:function(k,f){var m=this.$element.find(".item.active"),d=f||m[k](),j=this.interval,l=k=="next"?"left":"right",g=k=="next"?"first":"last",h=this,i;this.sliding=true;j&&this.pause();d=d.length?d:this.$element.find(".item")[g]();i=b.Event("slide",{relatedTarget:d[0],direction:l});if(d.hasClass("active")){return}if(this.$indicators.length){this.$indicators.find(".active").removeClass("active");this.$element.one("slid",function(){var e=b(h.$indicators.children()[h.getActiveIndex()]);e&&e.addClass("active")})}if(b.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(i);if(i.isDefaultPrevented()){return}d.addClass(k);d[0].offsetWidth;m.addClass(l);d.addClass(l);this.$element.one(b.support.transition.end,function(){d.removeClass([k,l].join(" ")).addClass("active");m.removeClass(["active",l].join(" "));h.sliding=false;setTimeout(function(){h.$element.trigger("slid")},0)})}else{this.$element.trigger(i);if(i.isDefaultPrevented()){return}m.removeClass("active");d.addClass("active");this.sliding=false;this.$element.trigger("slid")}j&&this.cycle();return this}};var a=b.fn.carousel;b.fn.carousel=function(d){return this.each(function(){var h=b(this),g=h.data("carousel"),e=b.extend({},b.fn.carousel.defaults,typeof d=="object"&&d),f=typeof d=="string"?d:e.slide;if(!g){h.data("carousel",(g=new c(this,e)))}if(typeof d=="number"){g.to(d)}else{if(f){g[f]()}else{if(e.interval){g.pause().cycle()}}}})};b.fn.carousel.defaults={interval:5000,pause:"hover"};b.fn.carousel.Constructor=c;b.fn.carousel.noConflict=function(){b.fn.carousel=a;return this};b(document).on("click.carousel.data-api","[data-slide], [data-slide-to]",function(j){var i=b(this),f,d=b(i.attr("data-target")||(f=i.attr("href"))&&f.replace(/.*(?=#[^\s]+$)/,"")),g=b.extend({},d.data(),i.data()),h;d.carousel(g);if(h=i.attr("data-slide-to")){d.data("carousel").pause().to(h).cycle()}j.preventDefault()})}(window.jQuery);!function(b){var c=function(e,d){this.$element=b(e);this.options=b.extend({},b.fn.collapse.defaults,d);if(this.options.parent){this.$parent=b(this.options.parent)}this.options.toggle&&this.toggle()};c.prototype={constructor:c,dimension:function(){var d=this.$element.hasClass("width");return d?"width":"height"},show:function(){var g,d,f,e;if(this.transitioning||this.$element.hasClass("in")){return}g=this.dimension();d=b.camelCase(["scroll",g].join("-"));f=this.$parent&&this.$parent.find("> .accordion-group > .in");if(f&&f.length){e=f.data("collapse");if(e&&e.transitioning){return}f.collapse("hide");e||f.data("collapse",null)}this.$element[g](0);this.transition("addClass",b.Event("show"),"shown");b.support.transition&&this.$element[g](this.$element[0][d])},hide:function(){var d;if(this.transitioning||!this.$element.hasClass("in")){return}d=this.dimension();this.reset(this.$element[d]());this.transition("removeClass",b.Event("hide"),"hidden");this.$element[d](0)},reset:function(d){var e=this.dimension();this.$element.removeClass("collapse")[e](d||"auto")[0].offsetWidth;this.$element[d!==null?"addClass":"removeClass"]("collapse");return this},transition:function(h,e,f){var g=this,d=function(){if(e.type=="show"){g.reset()}g.transitioning=0;g.$element.trigger(f)};this.$element.trigger(e);if(e.isDefaultPrevented()){return}this.transitioning=1;this.$element[h]("in");b.support.transition&&this.$element.hasClass("collapse")?this.$element.one(b.support.transition.end,d):d()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}};var a=b.fn.collapse;b.fn.collapse=function(d){return this.each(function(){var g=b(this),f=g.data("collapse"),e=b.extend({},b.fn.collapse.defaults,g.data(),typeof d=="object"&&d);if(!f){g.data("collapse",(f=new c(this,e)))}if(typeof d=="string"){f[d]()}})};b.fn.collapse.defaults={toggle:true};b.fn.collapse.Constructor=c;b.fn.collapse.noConflict=function(){b.fn.collapse=a;return this};b(document).on("click.collapse.data-api","[data-toggle=collapse]",function(i){var h=b(this),d,g=h.attr("data-target")||i.preventDefault()||(d=h.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),f=b(g).data("collapse")?"toggle":h.data();h[b(g).hasClass("in")?"addClass":"removeClass"]("collapsed");b(g).collapse(f)})}(window.jQuery);!function(f){var b="[data-toggle=dropdown]",a=function(h){var g=f(h).on("click.dropdown.data-api",this.toggle);f("html").on("click.dropdown.data-api",function(){g.parent().removeClass("open")})};a.prototype={constructor:a,toggle:function(j){var i=f(this),h,g;if(i.is(".disabled, :disabled")){return}h=e(i);g=h.hasClass("open");d();if(!g){if("ontouchstart" in document.documentElement){f('<div class="dropdown-backdrop"/>').insertBefore(f(this)).on("click",d)}h.toggleClass("open")}i.focus();return false},keydown:function(l){var k,m,g,j,i,h;if(!/(38|40|27)/.test(l.keyCode)){return}k=f(this);l.preventDefault();l.stopPropagation();if(k.is(".disabled, :disabled")){return}j=e(k);i=j.hasClass("open");if(!i||(i&&l.keyCode==27)){if(l.which==27){j.find(b).focus()}return k.click()}m=f("[role=menu] li:not(.divider):visible a",j);if(!m.length){return}h=m.index(m.filter(":focus"));if(l.keyCode==38&&h>0){h--}if(l.keyCode==40&&h<m.length-1){h++}if(!~h){h=0}m.eq(h).focus()}};function d(){f(".dropdown-backdrop").remove();f(b).each(function(){e(f(this)).removeClass("open")})}function e(i){var g=i.attr("data-target"),h;if(!g){g=i.attr("href");g=g&&/#/.test(g)&&g.replace(/.*(?=#[^\s]*$)/,"")}h=g&&f(g);if(!h||!h.length){h=i.parent()}return h}var c=f.fn.dropdown;f.fn.dropdown=function(g){return this.each(function(){var i=f(this),h=i.data("dropdown");if(!h){i.data("dropdown",(h=new a(this)))}if(typeof g=="string"){h[g].call(i)}})};f.fn.dropdown.Constructor=a;f.fn.dropdown.noConflict=function(){f.fn.dropdown=c;return this};f(document).on("click.dropdown.data-api",d).on("click.dropdown.data-api",".dropdown form",function(g){g.stopPropagation()}).on("click.dropdown.data-api",b,a.prototype.toggle).on("keydown.dropdown.data-api",b+", [role=menu]",a.prototype.keydown)}(window.jQuery);!function(c){var b=function(e,d){this.options=d;this.$element=c(e).delegate('[data-dismiss="modal"]',"click.dismiss.modal",c.proxy(this.hide,this));this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};b.prototype={constructor:b,toggle:function(){return this[!this.isShown?"show":"hide"]()},show:function(){var d=this,f=c.Event("show");this.$element.trigger(f);if(this.isShown||f.isDefaultPrevented()){return}this.isShown=true;this.escape();this.backdrop(function(){var e=c.support.transition&&d.$element.hasClass("fade");if(!d.$element.parent().length){d.$element.appendTo(document.body)}d.$element.show();if(e){d.$element[0].offsetWidth}d.$element.addClass("in").attr("aria-hidden",false);d.enforceFocus();e?d.$element.one(c.support.transition.end,function(){d.$element.focus().trigger("shown")}):d.$element.focus().trigger("shown")})},hide:function(f){f&&f.preventDefault();var d=this;f=c.Event("hide");this.$element.trigger(f);if(!this.isShown||f.isDefaultPrevented()){return}this.isShown=false;this.escape();c(document).off("focusin.modal");this.$element.removeClass("in").attr("aria-hidden",true);c.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},enforceFocus:function(){var d=this;c(document).on("focusin.modal",function(f){if(d.$element[0]!==f.target&&!d.$element.has(f.target).length){d.$element.focus()}})},escape:function(){var d=this;if(this.isShown&&this.options.keyboard){this.$element.on("keyup.dismiss.modal",function(f){f.which==27&&d.hide()})}else{if(!this.isShown){this.$element.off("keyup.dismiss.modal")}}},hideWithTransition:function(){var d=this,e=setTimeout(function(){d.$element.off(c.support.transition.end);d.hideModal()},500);this.$element.one(c.support.transition.end,function(){clearTimeout(e);d.hideModal()})},hideModal:function(){var d=this;this.$element.hide();this.backdrop(function(){d.removeBackdrop();d.$element.trigger("hidden")})},removeBackdrop:function(){this.$backdrop&&this.$backdrop.remove();this.$backdrop=null},backdrop:function(g){var f=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var d=c.support.transition&&e;this.$backdrop=c('<div class="modal-backdrop '+e+'" />').appendTo(document.body);this.$backdrop.click(this.options.backdrop=="static"?c.proxy(this.$element[0].focus,this.$element[0]):c.proxy(this.hide,this));if(d){this.$backdrop[0].offsetWidth}this.$backdrop.addClass("in");if(!g){return}d?this.$backdrop.one(c.support.transition.end,g):g()}else{if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");c.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(c.support.transition.end,g):g()}else{if(g){g()}}}}};var a=c.fn.modal;c.fn.modal=function(d){return this.each(function(){var g=c(this),f=g.data("modal"),e=c.extend({},c.fn.modal.defaults,g.data(),typeof d=="object"&&d);if(!f){g.data("modal",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}else{if(e.show){f.show()}}})};c.fn.modal.defaults={backdrop:true,keyboard:true,show:true};c.fn.modal.Constructor=b;c.fn.modal.noConflict=function(){c.fn.modal=a;return this};c(document).on("click.modal.data-api",'[data-toggle="modal"]',function(i){var h=c(this),f=h.attr("href"),d=c(h.attr("data-target")||(f&&f.replace(/.*(?=#[^\s]+$)/,""))),g=d.data("modal")?"toggle":c.extend({remote:!/#/.test(f)&&f},d.data(),h.data());i.preventDefault();d.modal(g).one("hide",function(){h.focus()})})}(window.jQuery);!function(c){var b=function(e,d){this.init("tooltip",e,d)};b.prototype={constructor:b,init:function(k,h,f){var l,d,j,e,g;this.type=k;this.$element=c(h);this.options=this.getOptions(f);this.enabled=true;j=this.options.trigger.split(" ");for(g=j.length;g--;){e=j[g];if(e=="click"){this.$element.on("click."+this.type,this.options.selector,c.proxy(this.toggle,this))}else{if(e!="manual"){l=e=="hover"?"mouseenter":"focus";d=e=="hover"?"mouseleave":"blur";this.$element.on(l+"."+this.type,this.options.selector,c.proxy(this.enter,this));this.$element.on(d+"."+this.type,this.options.selector,c.proxy(this.leave,this))}}}this.options.selector?(this._options=c.extend({},this.options,{trigger:"manual",selector:""})):this.fixTitle()},getOptions:function(d){d=c.extend({},c.fn[this.type].defaults,this.$element.data(),d);if(d.delay&&typeof d.delay=="number"){d.delay={show:d.delay,hide:d.delay}}return d},enter:function(h){var g=c.fn[this.type].defaults,f={},d;this._options&&c.each(this._options,function(e,i){if(g[e]!=i){f[e]=i}},this);d=c(h.currentTarget)[this.type](f).data(this.type);if(!d.options.delay||!d.options.delay.show){return d.show()}clearTimeout(this.timeout);d.hoverState="in";this.timeout=setTimeout(function(){if(d.hoverState=="in"){d.show()}},d.options.delay.show)},leave:function(f){var d=c(f.currentTarget)[this.type](this._options).data(this.type);if(this.timeout){clearTimeout(this.timeout)}if(!d.options.delay||!d.options.delay.hide){return d.hide()}d.hoverState="out";this.timeout=setTimeout(function(){if(d.hoverState=="out"){d.hide()}},d.options.delay.hide)},show:function(){var i,k,g,j,d,h,f=c.Event("show");if(this.hasContent()&&this.enabled){this.$element.trigger(f);if(f.isDefaultPrevented()){return}i=this.tip();this.setContent();if(this.options.animation){i.addClass("fade")}d=typeof this.options.placement=="function"?this.options.placement.call(this,i[0],this.$element[0]):this.options.placement;i.detach().css({top:0,left:0,display:"block"});this.options.container?i.appendTo(this.options.container):i.insertAfter(this.$element);k=this.getPosition();g=i[0].offsetWidth;j=i[0].offsetHeight;switch(d){case"bottom":h={top:k.top+k.height,left:k.left+k.width/2-g/2};break;case"top":h={top:k.top-j,left:k.left+k.width/2-g/2};break;case"left":h={top:k.top+k.height/2-j/2,left:k.left-g};break;case"right":h={top:k.top+k.height/2-j/2,left:k.left+k.width};break}this.applyPlacement(h,d);this.$element.trigger("shown")}},applyPlacement:function(g,h){var i=this.tip(),e=i[0].offsetWidth,l=i[0].offsetHeight,d,j,k,f;i.offset(g).addClass(h).addClass("in");d=i[0].offsetWidth;j=i[0].offsetHeight;if(h=="top"&&j!=l){g.top=g.top+l-j;f=true}if(h=="bottom"||h=="top"){k=0;if(g.left<0){k=g.left*-2;g.left=0;i.offset(g);d=i[0].offsetWidth;j=i[0].offsetHeight}this.replaceArrow(k-e+d,d,"left")}else{this.replaceArrow(j-l,j,"top")}if(f){i.offset(g)}},replaceArrow:function(f,e,d){this.arrow().css(d,f?(50*(1-f/e)+"%"):"")},setContent:function(){var e=this.tip(),d=this.getTitle();e.find(".tooltip-inner")[this.options.html?"html":"text"](d);e.removeClass("fade in top bottom left right")},hide:function(){var d=this,g=this.tip(),f=c.Event("hide");this.$element.trigger(f);if(f.isDefaultPrevented()){return}g.removeClass("in");function h(){var e=setTimeout(function(){g.off(c.support.transition.end).detach()},500);g.one(c.support.transition.end,function(){clearTimeout(e);g.detach()})}c.support.transition&&this.$tip.hasClass("fade")?h():g.detach();this.$element.trigger("hidden");return this},fixTitle:function(){var d=this.$element;if(d.attr("title")||typeof(d.attr("data-original-title"))!="string"){d.attr("data-original-title",d.attr("title")||"").attr("title","")}},hasContent:function(){return this.getTitle()},getPosition:function(){var d=this.$element[0];return c.extend({},(typeof d.getBoundingClientRect=="function")?d.getBoundingClientRect():{width:d.offsetWidth,height:d.offsetHeight},this.$element.offset())},getTitle:function(){var f,d=this.$element,e=this.options;f=d.attr("data-original-title")||(typeof e.title=="function"?e.title.call(d[0]):e.title);return f},tip:function(){return this.$tip=this.$tip||c(this.options.template)},arrow:function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},validate:function(){if(!this.$element[0].parentNode){this.hide();this.$element=null;this.options=null}},enable:function(){this.enabled=true},disable:function(){this.enabled=false},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(f){var d=f?c(f.currentTarget)[this.type](this._options).data(this.type):this;d.tip().hasClass("in")?d.hide():d.show()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}};var a=c.fn.tooltip;c.fn.tooltip=function(d){return this.each(function(){var g=c(this),f=g.data("tooltip"),e=typeof d=="object"&&d;if(!f){g.data("tooltip",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}})};c.fn.tooltip.Constructor=b;c.fn.tooltip.defaults={animation:true,placement:"top",selector:false,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:false,container:false};c.fn.tooltip.noConflict=function(){c.fn.tooltip=a;return this}}(window.jQuery);!function(c){var b=function(e,d){this.init("popover",e,d)};b.prototype=c.extend({},c.fn.tooltip.Constructor.prototype,{constructor:b,setContent:function(){var f=this.tip(),e=this.getTitle(),d=this.getContent();f.find(".popover-title")[this.options.html?"html":"text"](e);f.find(".popover-content")[this.options.html?"html":"text"](d);f.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var e,d=this.$element,f=this.options;e=(typeof f.content=="function"?f.content.call(d[0]):f.content)||d.attr("data-content");return e},tip:function(){if(!this.$tip){this.$tip=c(this.options.template)}return this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}});var a=c.fn.popover;c.fn.popover=function(d){return this.each(function(){var g=c(this),f=g.data("popover"),e=typeof d=="object"&&d;if(!f){g.data("popover",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}})};c.fn.popover.Constructor=b;c.fn.popover.defaults=c.extend({},c.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'});c.fn.popover.noConflict=function(){c.fn.popover=a;return this}}(window.jQuery);!function(c){function b(g,f){var h=c.proxy(this.process,this),d=c(g).is("body")?c(window):c(g),e;this.options=c.extend({},c.fn.scrollspy.defaults,f);this.$scrollElement=d.on("scroll.scroll-spy.data-api",h);this.selector=(this.options.target||((e=c(g).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,""))||"")+" .nav li > a";this.$body=c("body");this.refresh();this.process()}b.prototype={constructor:b,refresh:function(){var d=this,e;this.offsets=c([]);this.targets=c([]);e=this.$body.find(this.selector).map(function(){var g=c(this),f=g.data("target")||g.attr("href"),h=/^#\w/.test(f)&&c(f);return(h&&h.length&&[[h.position().top+(!c.isWindow(d.$scrollElement.get(0))&&d.$scrollElement.scrollTop()),f]])||null}).sort(function(g,f){return g[0]-f[0]}).each(function(){d.offsets.push(this[0]);d.targets.push(this[1])})},process:function(){var j=this.$scrollElement.scrollTop()+this.options.offset,f=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,h=f-this.$scrollElement.height(),g=this.offsets,d=this.targets,k=this.activeTarget,e;if(j>=h){return k!=(e=d.last()[0])&&this.activate(e)}for(e=g.length;e--;){k!=d[e]&&j>=g[e]&&(!g[e+1]||j<=g[e+1])&&this.activate(d[e])}},activate:function(f){var e,d;this.activeTarget=f;c(this.selector).parent(".active").removeClass("active");d=this.selector+'[data-target="'+f+'"],'+this.selector+'[href="'+f+'"]';e=c(d).parent("li").addClass("active");if(e.parent(".dropdown-menu").length){e=e.closest("li.dropdown").addClass("active")}e.trigger("activate")}};var a=c.fn.scrollspy;c.fn.scrollspy=function(d){return this.each(function(){var g=c(this),f=g.data("scrollspy"),e=typeof d=="object"&&d;if(!f){g.data("scrollspy",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}})};c.fn.scrollspy.Constructor=b;c.fn.scrollspy.defaults={offset:10};c.fn.scrollspy.noConflict=function(){c.fn.scrollspy=a;return this};c(window).on("load",function(){c('[data-spy="scroll"]').each(function(){var d=c(this);d.scrollspy(d.data())})})}(window.jQuery);!function(c){var b=function(d){this.element=c(d)};b.prototype={constructor:b,show:function(){var j=this.element,g=j.closest("ul:not(.dropdown-menu)"),f=j.attr("data-target"),h,d,i;if(!f){f=j.attr("href");f=f&&f.replace(/.*(?=#[^\s]*$)/,"")}if(j.parent("li").hasClass("active")){return}h=g.find(".active:last a")[0];i=c.Event("show",{relatedTarget:h});j.trigger(i);if(i.isDefaultPrevented()){return}d=c(f);this.activate(j.parent("li"),g);this.activate(d,d.parent(),function(){j.trigger({type:"shown",relatedTarget:h})})},activate:function(f,e,i){var d=e.find("> .active"),h=i&&c.support.transition&&d.hasClass("fade");function g(){d.removeClass("active").find("> .dropdown-menu > .active").removeClass("active");f.addClass("active");if(h){f[0].offsetWidth;f.addClass("in")}else{f.removeClass("fade")}if(f.parent(".dropdown-menu")){f.closest("li.dropdown").addClass("active")}i&&i()}h?d.one(c.support.transition.end,g):g();d.removeClass("in")}};var a=c.fn.tab;c.fn.tab=function(d){return this.each(function(){var f=c(this),e=f.data("tab");if(!e){f.data("tab",(e=new b(this)))}if(typeof d=="string"){e[d]()}})};c.fn.tab.Constructor=b;c.fn.tab.noConflict=function(){c.fn.tab=a;return this};c(document).on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(d){d.preventDefault();c(this).tab("show")})}(window.jQuery);!function(b){var c=function(e,d){this.$element=b(e);this.options=b.extend({},b.fn.typeahead.defaults,d);this.matcher=this.options.matcher||this.matcher;this.sorter=this.options.sorter||this.sorter;this.highlighter=this.options.highlighter||this.highlighter;this.updater=this.options.updater||this.updater;this.source=this.options.source;this.$menu=b(this.options.menu);this.shown=false;this.listen()};c.prototype={constructor:c,select:function(){var d=this.$menu.find(".active").attr("data-value");this.$element.val(this.updater(d)).change();return this.hide()},updater:function(d){return d},show:function(){var d=b.extend({},this.$element.position(),{height:this.$element[0].offsetHeight});this.$menu.insertAfter(this.$element).css({top:d.top+d.height,left:d.left}).show();this.shown=true;return this},hide:function(){this.$menu.hide();this.shown=false;return this},lookup:function(e){var d;this.query=this.$element.val();if(!this.query||this.query.length<this.options.minLength){return this.shown?this.hide():this}d=b.isFunction(this.source)?this.source(this.query,b.proxy(this.process,this)):this.source;return d?this.process(d):this},process:function(d){var e=this;d=b.grep(d,function(f){return e.matcher(f)});d=this.sorter(d);if(!d.length){return this.shown?this.hide():this}return this.render(d.slice(0,this.options.items)).show()},matcher:function(d){return ~d.toLowerCase().indexOf(this.query.toLowerCase())},sorter:function(f){var g=[],e=[],d=[],h;while(h=f.shift()){if(!h.toLowerCase().indexOf(this.query.toLowerCase())){g.push(h)}else{if(~h.indexOf(this.query)){e.push(h)}else{d.push(h)}}}return g.concat(e,d)},highlighter:function(d){var e=this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");return d.replace(new RegExp("("+e+")","ig"),function(f,g){return"<strong>"+g+"</strong>"})},render:function(d){var e=this;d=b(d).map(function(f,g){f=b(e.options.item).attr("data-value",g);f.find("a").html(e.highlighter(g));return f[0]});d.first().addClass("active");this.$menu.html(d);return this},next:function(e){var f=this.$menu.find(".active").removeClass("active"),d=f.next();if(!d.length){d=b(this.$menu.find("li")[0])}d.addClass("active")},prev:function(e){var f=this.$menu.find(".active").removeClass("active"),d=f.prev();if(!d.length){d=this.$menu.find("li").last()}d.addClass("active")},listen:function(){this.$element.on("focus",b.proxy(this.focus,this)).on("blur",b.proxy(this.blur,this)).on("keypress",b.proxy(this.keypress,this)).on("keyup",b.proxy(this.keyup,this));if(this.eventSupported("keydown")){this.$element.on("keydown",b.proxy(this.keydown,this))}this.$menu.on("click",b.proxy(this.click,this)).on("mouseenter","li",b.proxy(this.mouseenter,this)).on("mouseleave","li",b.proxy(this.mouseleave,this))},eventSupported:function(d){var e=d in this.$element;if(!e){this.$element.setAttribute(d,"return;");e=typeof this.$element[d]==="function"}return e},move:function(d){if(!this.shown){return}switch(d.keyCode){case 9:case 13:case 27:d.preventDefault();break;case 38:d.preventDefault();this.prev();break;case 40:d.preventDefault();this.next();break}d.stopPropagation()},keydown:function(d){this.suppressKeyPressRepeat=~b.inArray(d.keyCode,[40,38,9,13,27]);this.move(d)},keypress:function(d){if(this.suppressKeyPressRepeat){return}this.move(d)},keyup:function(d){switch(d.keyCode){case 40:case 38:case 16:case 17:case 18:break;case 9:case 13:if(!this.shown){return}this.select();break;case 27:if(!this.shown){return}this.hide();break;default:this.lookup()}d.stopPropagation();d.preventDefault()},focus:function(d){this.focused=true},blur:function(d){this.focused=false;if(!this.mousedover&&this.shown){this.hide()}},click:function(d){d.stopPropagation();d.preventDefault();this.select();this.$element.focus()},mouseenter:function(d){this.mousedover=true;this.$menu.find(".active").removeClass("active");b(d.currentTarget).addClass("active")},mouseleave:function(d){this.mousedover=false;if(!this.focused&&this.shown){this.hide()}}};var a=b.fn.typeahead;b.fn.typeahead=function(d){return this.each(function(){var g=b(this),f=g.data("typeahead"),e=typeof d=="object"&&d;if(!f){g.data("typeahead",(f=new c(this,e)))}if(typeof d=="string"){f[d]()}})};b.fn.typeahead.defaults={source:[],items:8,menu:'<ul class="typeahead dropdown-menu"></ul>',item:'<li><a href="#"></a></li>',minLength:1};b.fn.typeahead.Constructor=c;b.fn.typeahead.noConflict=function(){b.fn.typeahead=a;return this};b(document).on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(f){var d=b(this);if(d.data("typeahead")){return}d.typeahead(d.data())})}(window.jQuery);!function(c){var b=function(e,d){this.options=c.extend({},c.fn.affix.defaults,d);this.$window=c(window).on("scroll.affix.data-api",c.proxy(this.checkPosition,this)).on("click.affix.data-api",c.proxy(function(){setTimeout(c.proxy(this.checkPosition,this),1)},this));this.$element=c(e);this.checkPosition()};b.prototype.checkPosition=function(){if(!this.$element.is(":visible")){return}var h=c(document).height(),j=this.$window.scrollTop(),d=this.$element.offset(),k=this.options.offset,f=k.bottom,g=k.top,i="affix affix-top affix-bottom",e;if(typeof k!="object"){f=g=k}if(typeof g=="function"){g=k.top()}if(typeof f=="function"){f=k.bottom()}e=this.unpin!=null&&(j+this.unpin<=d.top)?false:f!=null&&(d.top+this.$element.height()>=h-f)?"bottom":g!=null&&j<=g?"top":false;if(this.affixed===e){return}this.affixed=e;this.unpin=e=="bottom"?d.top-j:null;this.$element.removeClass(i).addClass("affix"+(e?"-"+e:""))};var a=c.fn.affix;c.fn.affix=function(d){return this.each(function(){var g=c(this),f=g.data("affix"),e=typeof d=="object"&&d;if(!f){g.data("affix",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}})};c.fn.affix.Constructor=b;c.fn.affix.defaults={offset:0};c.fn.affix.noConflict=function(){c.fn.affix=a;return this};c(window).on("load",function(){c('[data-spy="affix"]').each(function(){var e=c(this),d=e.data();d.offset=d.offset||{};d.offsetBottom&&(d.offset.bottom=d.offsetBottom);d.offsetTop&&(d.offset.top=d.offsetTop);e.affix(d)})})}(window.jQuery);var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;(function(){function d(F){function w(J){var K=J.charCodeAt(0);if(K!==92){return K}var I=J.charAt(1);return(K=k[I])?K:"0"<=I&&I<="7"?parseInt(J.substring(1),8):I==="u"||I==="x"?parseInt(J.substring(2),16):J.charCodeAt(1)}function C(I){if(I<32){return(I<16?"\\x0":"\\x")+I.toString(16)}I=String.fromCharCode(I);if(I==="\\"||I==="-"||I==="["||I==="]"){I="\\"+I}return I}function A(J){for(var M=J.substring(1,J.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),J=[],I=[],O=M[0]==="^",P=O?1:0,L=M.length;P<L;++P){var K=M[P];if(/\\[bdsw]/i.test(K)){J.push(K)}else{var K=w(K),N;P+2<L&&"-"===M[P+1]?(N=w(M[P+2]),P+=2):N=K;I.push([K,N]);N<65||K>122||(N<65||K>90||I.push([Math.max(65,K)|32,Math.min(N,90)|32]),N<97||K>122||I.push([Math.max(97,K)&-33,Math.min(N,122)&-33]))}}I.sort(function(Q,R){return Q[0]-R[0]||R[1]-Q[1]});M=[];K=[NaN,NaN];for(P=0;P<I.length;++P){L=I[P],L[0]<=K[1]+1?K[1]=Math.max(K[1],L[1]):M.push(K=L)}I=["["];O&&I.push("^");I.push.apply(I,J);for(P=0;P<M.length;++P){L=M[P],I.push(C(L[0])),L[1]>L[0]&&(L[1]+1>L[0]&&I.push("-"),I.push(C(L[1])))}I.push("]");return I.join("")}function E(J){for(var M=J.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),I=M.length,N=[],O=0,L=0;O<I;++O){var K=M[O];K==="("?++L:"\\"===K.charAt(0)&&(K=+K.substring(1))&&K<=L&&(N[K]=-1)}for(O=1;O<N.length;++O){-1===N[O]&&(N[O]=++G)}for(L=O=0;O<I;++O){K=M[O],K==="("?(++L,N[L]===void 0&&(M[O]="(?:")):"\\"===K.charAt(0)&&(K=+K.substring(1))&&K<=L&&(M[O]="\\"+N[L])}for(L=O=0;O<I;++O){"^"===M[O]&&"^"!==M[O+1]&&(M[O]="")}if(J.ignoreCase&&H){for(O=0;O<I;++O){K=M[O],J=K.charAt(0),K.length>=2&&J==="["?M[O]=A(K):J!=="\\"&&(M[O]=K.replace(/[A-Za-z]/g,function(P){P=P.charCodeAt(0);return"["+String.fromCharCode(P&-33,P|32)+"]"}))}}return M.join("")}for(var G=0,H=!1,x=!1,u=0,D=F.length;u<D;++u){var B=F[u];if(B.ignoreCase){x=!0}else{if(/[a-z]/i.test(B.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){H=!0;x=!1;break}}}for(var k={b:8,t:9,n:10,v:11,f:12,r:13},v=[],u=0,D=F.length;u<D;++u){B=F[u];if(B.global||B.multiline){throw Error(""+B)}v.push("(?:"+E(B)+")")}return RegExp(v.join("|"),x?"gi":"g")}function c(B){function u(E){switch(E.nodeType){case 1:if(x.test(E.className)){break}for(var F=E.firstChild;F;F=F.nextSibling){u(F)}F=E.nodeName;if("BR"===F||"LI"===F){w[D]="\n",C[D<<1]=A++,C[D++<<1|1]=E}break;case 3:case 4:F=E.nodeValue,F.length&&(F=k?F.replace(/\r\n?/g,"\n"):F.replace(/[\t\n\r ]+/g," "),w[D]=F,C[D<<1]=A,A+=F.length,C[D++<<1|1]=E)}}var x=/(?:^|\s)nocode(?:\s|$)/,w=[],A=0,C=[],D=0,v;B.currentStyle?v=B.currentStyle.whiteSpace:window.getComputedStyle&&(v=document.defaultView.getComputedStyle(B,q).getPropertyValue("white-space"));var k=v&&"pre"===v.substring(0,3);u(B);return{a:w.join("").replace(/\n$/,""),c:C}}function t(u,k,w,v){k&&(u={a:k,d:u},w(u),v.push.apply(v,u.e))}function h(u,k){function x(P){for(var F=P.d,C=[F,"pln"],L=0,J=P.a.match(A)||[],B={},E=0,N=J.length;E<N;++E){var K=J[E],O=B[K],D=void 0,M;if(typeof O==="string"){M=!1}else{var I=w[K.charAt(0)];if(I){D=K.match(I[1]),O=I[0]}else{for(M=0;M<v;++M){if(I=k[M],D=K.match(I[1])){O=I[0];break}}D||(O="pln")}if((M=O.length>=5&&"lang-"===O.substring(0,5))&&!(D&&typeof D[1]==="string")){M=!1,O="src"}M||(B[K]=O)}I=L;L+=K.length;if(M){M=D[1];var H=K.indexOf(M),G=H+M.length;D[2]&&(G=K.length-D[2].length,H=G-M.length);O=O.substring(5);t(F+I,K.substring(0,H),x,C);t(F+I+H,M,s(O,M),C);t(F+I+G,K.substring(G),x,C)}else{C.push(F+I,O)}}P.e=C}var w={},A;(function(){for(var G=u.concat(k),B=[],F={},H=0,E=G.length;H<E;++H){var D=G[H],I=D[3];if(I){for(var C=I.length;--C>=0;){w[I.charAt(C)]=D}}D=D[1];I=""+D;F.hasOwnProperty(I)||(B.push(D),F[I]=q)}B.push(/[\S\s]/);A=d(B)})();var v=k.length;return x}function o(u){var k=[],w=[];u.tripleQuotedStrings?k.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):u.multiLineStrings?k.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,q,"'\"`"]):k.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);u.verbatimStrings&&w.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var v=u.hashComments;v&&(u.cStyleComments?(v>1?k.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):k.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),w.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):k.push(["com",/^#[^\n\r]*/,q,"#"]));u.cStyleComments&&(w.push(["com",/^\/\/[^\n\r]*/,q]),w.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));u.regexLiterals&&w.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(v=u.types)&&w.push(["typ",v]);u=(""+u.keywords).replace(/^ | $/g,"");u.length&&w.push(["kwd",RegExp("^(?:"+u.replace(/[\s,]+/g,"|")+")\\b"),q]);k.push(["pln",/^\s+/,q," \r\n\t\xa0"]);w.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return h(k,w)}function r(H,x){function E(K){switch(K.nodeType){case 1:if(B.test(K.className)){break}if("BR"===K.nodeName){C(K),K.parentNode&&K.parentNode.removeChild(K)}else{for(K=K.firstChild;K;K=K.nextSibling){E(K)}}break;case 3:case 4:if(v){var k=K.nodeValue,L=k.match(I);if(L){var M=k.substring(0,L.index);K.nodeValue=M;(k=k.substring(L.index+L[0].length))&&K.parentNode.insertBefore(J.createTextNode(k),K.nextSibling);C(K);M||K.parentNode.removeChild(K)}}}}function C(K){function k(M,R){var Q=R?M.cloneNode(!1):M,P=M.parentNode;if(P){var P=k(P,1),O=M.nextSibling;P.appendChild(Q);for(var N=O;N;N=O){O=N.nextSibling,P.appendChild(N)}}return Q}for(;!K.nextSibling;){if(K=K.parentNode,!K){return}}for(var K=k(K.nextSibling,0),L;(L=K.parentNode)&&L.nodeType===1;){K=L}F.push(K)}var B=/(?:^|\s)nocode(?:\s|$)/,I=/\r\n?|\n/,J=H.ownerDocument,A;H.currentStyle?A=H.currentStyle.whiteSpace:window.getComputedStyle&&(A=J.defaultView.getComputedStyle(H,q).getPropertyValue("white-space"));var v=A&&"pre"===A.substring(0,3);for(A=J.createElement("LI");H.firstChild;){A.appendChild(H.firstChild)}for(var F=[A],D=0;D<F.length;++D){E(F[D])}x===(x|0)&&F[0].setAttribute("value",x);var u=J.createElement("OL");u.className="linenums";for(var w=Math.max(0,x-1|0)||0,D=0,G=F.length;D<G;++D){A=F[D],A.className="L"+(D+w)%10,A.firstChild||A.appendChild(J.createTextNode("\xa0")),u.appendChild(A)}H.appendChild(u)}function z(u,k){for(var w=k.length;--w>=0;){var v=k[w];y.hasOwnProperty(v)?window.console&&console.warn("cannot override language handler %s",v):y[v]=u}}function s(u,k){if(!u||!y.hasOwnProperty(u)){u=/^\s*</.test(k)?"default-markup":"default-code"}return y[u]}function p(X){var L=X.g;try{var T=c(X.h),Q=T.a;X.a=Q;X.c=T.c;X.d=0;s(L,Q)(X);var N=/\bMSIE\b/.test(navigator.userAgent),L=/\n/g,F=X.a,G=F.length,T=0,M=X.c,I=M.length,Q=0,U=X.e,R=U.length,X=0;U[R]=G;var H,K;for(K=H=0;K<R;){U[K]!==U[K+2]?(U[H++]=U[K++],U[H++]=U[K++]):K+=2}R=H;for(K=H=0;K<R;){for(var A=U[K],S=U[K+1],W=K+2;W+2<=R&&U[W+1]===S;){W+=2}U[H++]=A;U[H++]=S;K=W}for(U.length=H;Q<I;){var J=M[Q+2]||G,V=U[X+2]||G,W=Math.min(J,V),P=M[Q+1],O;if(P.nodeType!==1&&(O=F.substring(T,W))){N&&(O=O.replace(L,"\r"));P.nodeValue=O;var E=P.ownerDocument,D=E.createElement("SPAN");D.className=U[X+1];var B=P.parentNode;B.replaceChild(D,P);D.appendChild(P);T<J&&(M[Q+1]=P=E.createTextNode(F.substring(W,J)),B.insertBefore(P,D.nextSibling))}T=W;T>=J&&(Q+=2);T>=V&&(X+=2)}}catch(C){"console" in window&&console.log(C&&C.stack?C.stack:C)}}var m=["break,continue,do,else,for,if,return,while"],j=[[m,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],n=[j,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],l=[j,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],i=[l,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],j=[j,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],g=[m,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],f=[m,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],m=[m,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,b=/\S/,a=o({keywords:[n,i,j,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+g,f,m],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),y={};z(a,["default-code"]);z(h([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);z(h([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);z(h([],[["atv",/^[\S\s]+/]]),["uq.val"]);z(o({keywords:n,hashComments:!0,cStyleComments:!0,types:e}),["c","cc","cpp","cxx","cyc","m"]);z(o({keywords:"null,true,false"}),["json"]);z(o({keywords:i,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:e}),["cs"]);z(o({keywords:l,cStyleComments:!0}),["java"]);z(o({keywords:m,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);z(o({keywords:g,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),["cv","py"]);z(o({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);z(o({keywords:f,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);z(o({keywords:j,cStyleComments:!0,regexLiterals:!0}),["js"]);z(o({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes",hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);z(h([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(u,k,w){var v=document.createElement("PRE");v.innerHTML=u;w&&r(v,w);p({g:k,i:w,h:v});return v.innerHTML};window.prettyPrint=function(E){function v(){for(var L=window.PR_SHOULD_USE_CONTINUATION?w.now()+250:Infinity;u<A.length&&w.now()<L;u++){var O=A[u],I=O.className;if(I.indexOf("prettyprint")>=0){var I=I.match(B),K,H;if(H=!I){H=O;for(var M=void 0,N=H.firstChild;N;N=N.nextSibling){var J=N.nodeType,M=J===1?M?H:N:J===3?b.test(N.nodeValue)?H:M:M}H=(K=M===H?void 0:M)&&"CODE"===K.tagName}H&&(I=K.className.match(B));I&&(I=I[1]);H=!1;for(M=O.parentNode;M;M=M.parentNode){if((M.tagName==="pre"||M.tagName==="code"||M.tagName==="xmp")&&M.className&&M.className.indexOf("prettyprint")>=0){H=!0;break}}H||((H=(H=O.className.match(/\blinenums\b(?::(\d+))?/))?H[1]&&H[1].length?+H[1]:!0:!1)&&r(O,H),D={g:I,h:O,i:H},p(D))}}u<A.length?setTimeout(v,250):E&&E()}for(var C=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],A=[],x=0;x<C.length;++x){for(var F=0,G=C[x].length;F<G;++F){A.push(C[x][F])}}var C=q,w=Date;w.now||(w={now:function(){return +new Date}});var u=0,D,B=/\blang(?:uage)?-([\w.]+)(?!\S)/;v()};window.PR={createSimpleLexer:h,registerLangHandler:z,sourceDecorator:o,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();jQuery(document).ready(function(){$(".topbar").dropdown();prettyPrint()});function asyncJs(a){(function(){var c=document.createElement("script"),b=document.getElementsByTagName("script")[0];c.type="text/javascript";c.async=true;c.src=a;b.parentNode.insertBefore(c,b)})()}; |
ajax/libs/jquery.fancytree/2.6.0/src/jquery.fancytree.js | sullivanmatt/cdnjs | /*!
* jquery.fancytree.js
* Dynamic tree view control, with support for lazy loading of branches.
* https://github.com/mar10/fancytree/
*
* Copyright (c) 2006-2014, Martin Wendt (http://wwWendt.de)
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.6.0
* @date 2014-11-29T08:33
*/
/** Core Fancytree module.
*/
// Start of local namespace
;(function($, window, document, undefined) {
"use strict";
// prevent duplicate loading
if ( $.ui && $.ui.fancytree ) {
$.ui.fancytree.warn("Fancytree: ignored duplicate include");
return;
}
/* *****************************************************************************
* Private functions and variables
*/
function _assert(cond, msg){
// TODO: see qunit.js extractStacktrace()
if(!cond){
msg = msg ? ": " + msg : "";
// consoleApply("assert", [!!cond, msg]);
$.error("Fancytree assertion failed" + msg);
}
}
_assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)");
function consoleApply(method, args){
var i, s,
fn = window.console ? window.console[method] : null;
if(fn){
try{
fn.apply(window.console, args);
} catch(e) {
// IE 8?
s = "";
for( i=0; i<args.length; i++){
s += args[i];
}
fn(s);
}
}
}
/*Return true if x is a FancytreeNode.*/
function _isNode(x){
return !!(x.tree && x.statusNodeType !== undefined);
}
/** Return true if dotted version string is equal or higher than requested version.
*
* See http://jsfiddle.net/mar10/FjSAN/
*/
function isVersionAtLeast(dottedVersion, major, minor, patch){
var i, v, t,
verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }),
testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); });
for( i = 0; i < testParts.length; i++ ){
v = verParts[i] || 0;
t = testParts[i] || 0;
if( v !== t ){
return ( v > t );
}
}
return true;
}
/** Return a wrapper that calls sub.methodName() and exposes
* this : tree
* this._local : tree.ext.EXTNAME
* this._super : base.methodName()
*/
function _makeVirtualFunction(methodName, tree, base, extension, extName){
// $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName);
// if(rexTestSuper && !rexTestSuper.test(func)){
// // extension.methodName() doesn't call _super(), so no wrapper required
// return func;
// }
// Use an immediate function as closure
var proxy = (function(){
var prevFunc = tree[methodName], // org. tree method or prev. proxy
baseFunc = extension[methodName], //
_local = tree.ext[extName],
_super = function(){
return prevFunc.apply(tree, arguments);
};
// Return the wrapper function
return function(){
var prevLocal = tree._local,
prevSuper = tree._super;
try{
tree._local = _local;
tree._super = _super;
return baseFunc.apply(tree, arguments);
}finally{
tree._local = prevLocal;
tree._super = prevSuper;
}
};
})(); // end of Immediate Function
return proxy;
}
/**
* Subclass `base` by creating proxy functions
*/
function _subclassObject(tree, base, extension, extName){
// $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
for(var attrName in extension){
if(typeof extension[attrName] === "function"){
if(typeof tree[attrName] === "function"){
// override existing method
tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
}else if(attrName.charAt(0) === "_"){
// Create private methods in tree.ext.EXTENSION namespace
tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
}else{
$.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName);
}
}else{
// Create member variables in tree.ext.EXTENSION namespace
if(attrName !== "options"){
tree.ext[extName][attrName] = extension[attrName];
}
}
}
}
function _getResolvedPromise(context, argArray){
if(context === undefined){
return $.Deferred(function(){this.resolve();}).promise();
}else{
return $.Deferred(function(){this.resolveWith(context, argArray);}).promise();
}
}
function _getRejectedPromise(context, argArray){
if(context === undefined){
return $.Deferred(function(){this.reject();}).promise();
}else{
return $.Deferred(function(){this.rejectWith(context, argArray);}).promise();
}
}
function _makeResolveFunc(deferred, context){
return function(){
deferred.resolveWith(context);
};
}
function _getElementDataAsDict($el){
// Evaluate 'data-NAME' attributes with special treatment for 'data-json'.
var d = $.extend({}, $el.data()),
json = d.json;
delete d.fancytree; // added to container by widget factory
if( json ) {
delete d.json;
// <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5)
d = $.extend(d, json);
}
return d;
}
// TODO: use currying
function _makeNodeTitleMatcher(s){
s = s.toLowerCase();
return function(node){
return node.title.toLowerCase().indexOf(s) >= 0;
};
}
function _makeNodeTitleStartMatcher(s){
var reMatch = new RegExp("^" + s, "i");
return function(node){
return reMatch.test(node.title);
};
}
var i,
FT = null, // initialized below
ENTITY_MAP = {"&": "&", "<": "<", ">": ">", "\"": """, "'": "'", "/": "/"},
//boolean attributes that can be set with equivalent class names in the LI tags
CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "),
CLASS_ATTR_MAP = {},
// Top-level Fancytree node attributes, that can be set by dict
NODE_ATTRS = "expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "),
NODE_ATTR_MAP = {},
// Attribute names that should NOT be added to node.data
NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true};
for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; }
for(i=0; i<NODE_ATTRS.length; i++){ NODE_ATTR_MAP[NODE_ATTRS[i]] = true; }
/* *****************************************************************************
* FancytreeNode
*/
/**
* Creates a new FancytreeNode
*
* @class FancytreeNode
* @classdesc A FancytreeNode represents the hierarchical data model and operations.
*
* @param {FancytreeNode} parent
* @param {NodeData} obj
*
* @property {Fancytree} tree The tree instance
* @property {FancytreeNode} parent The parent node
* @property {string} key Node id (must be unique inside the tree)
* @property {string} title Display name (may contain HTML)
* @property {object} data Contains all extra data that was passed on node creation
* @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br>
* For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array
* to define a node that has no children.
* @property {boolean} expanded Use isExpanded(), setExpanded() to access this property.
* @property {string} extraClasses Addtional CSS classes, added to the node's `<span>`
* @property {boolean} folder Folder nodes have different default icons and click behavior.<br>
* Note: Also non-folders may have children.
* @property {string} statusNodeType null or type of temporarily generated system node like 'loading', or 'error'.
* @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion.
* @property {boolean} selected Use isSelected(), setSelected() to access this property.
* @property {string} tooltip Alternative description used as hover banner
*/
function FancytreeNode(parent, obj){
var i, l, name, cl;
this.parent = parent;
this.tree = parent.tree;
this.ul = null;
this.li = null; // <li id='key' ftnode=this> tag
this.statusNodeType = null; // if this is a temp. node to display the status of its parent
this._isLoading = false; // if this node itself is loading
this._error = null; // {message: '...'} if a load error occured
this.data = {};
// TODO: merge this code with node.toDict()
// copy attributes from obj object
for(i=0, l=NODE_ATTRS.length; i<l; i++){
name = NODE_ATTRS[i];
this[name] = obj[name];
}
// node.data += obj.data
if(obj.data){
$.extend(this.data, obj.data);
}
// copy all other attributes to this.data.NAME
for(name in obj){
if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){
// node.data.NAME = obj.NAME
this.data[name] = obj[name];
}
}
// Fix missing key
if( this.key == null ){ // test for null OR undefined
if( this.tree.options.defaultKey ) {
this.key = this.tree.options.defaultKey(this);
_assert(this.key, "defaultKey() must return a unique key");
} else {
this.key = "_" + (FT._nextNodeKey++);
}
} else {
this.key = "" + this.key; // Convert to string (#217)
}
// Fix tree.activeNode
// TODO: not elegant: we use obj.active as marker to set tree.activeNode
// when loading from a dictionary.
if(obj.active){
_assert(this.tree.activeNode === null, "only one active node allowed");
this.tree.activeNode = this;
}
if( obj.selected ){ // #186
this.tree.lastSelectedNode = this;
}
// TODO: handle obj.focus = true
// Create child nodes
this.children = null;
cl = obj.children;
if(cl && cl.length){
this._setChildren(cl);
}
// Add to key/ref map (except for root node)
// if( parent ) {
this.tree._callHook("treeRegisterNode", this.tree, true, this);
// }
}
FancytreeNode.prototype = /** @lends FancytreeNode# */{
/* Return the direct child FancytreeNode with a given key, index. */
_findDirectChild: function(ptr){
var i, l,
cl = this.children;
if(cl){
if(typeof ptr === "string"){
for(i=0, l=cl.length; i<l; i++){
if(cl[i].key === ptr){
return cl[i];
}
}
}else if(typeof ptr === "number"){
return this.children[ptr];
}else if(ptr.parent === this){
return ptr;
}
}
return null;
},
// TODO: activate()
// TODO: activateSilently()
/* Internal helper called in recursive addChildren sequence.*/
_setChildren: function(children){
_assert(children && (!this.children || this.children.length === 0), "only init supported");
this.children = [];
for(var i=0, l=children.length; i<l; i++){
this.children.push(new FancytreeNode(this, children[i]));
}
},
/**
* Append (or insert) a list of child nodes.
*
* @param {NodeData[]} children array of child node definitions (also single child accepted)
* @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such).
* If omitted, the new children are appended.
* @returns {FancytreeNode} first child added
*
* @see FancytreeNode#applyPatch
*/
addChildren: function(children, insertBefore){
var i, l, pos,
firstNode = null,
nodeList = [];
if($.isPlainObject(children) ){
children = [children];
}
if(!this.children){
this.children = [];
}
for(i=0, l=children.length; i<l; i++){
nodeList.push(new FancytreeNode(this, children[i]));
}
firstNode = nodeList[0];
if(insertBefore == null){
this.children = this.children.concat(nodeList);
}else{
insertBefore = this._findDirectChild(insertBefore);
pos = $.inArray(insertBefore, this.children);
_assert(pos >= 0, "insertBefore must be an existing child");
// insert nodeList after children[pos]
this.children.splice.apply(this.children, [pos, 0].concat(nodeList));
}
if( !this.parent || this.parent.ul || this.tr ){
// render if the parent was rendered (or this is a root node)
this.render();
}
if( this.tree.options.selectMode === 3 ){
this.fixSelection3FromEndNodes();
}
return firstNode;
},
/**
* Append or prepend a node, or append a child node.
*
* This a convenience function that calls addChildren()
*
* @param {NodeData} node node definition
* @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child')
* @returns {FancytreeNode} new node
*/
addNode: function(node, mode){
if(mode === undefined || mode === "over"){
mode = "child";
}
switch(mode){
case "after":
return this.getParent().addChildren(node, this.getNextSibling());
case "before":
return this.getParent().addChildren(node, this);
case "firstChild":
// Insert before the first child if any
var insertBefore = (this.children ? this.children[0] : null);
return this.addChildren(node, insertBefore);
case "child":
case "over":
return this.addChildren(node);
}
_assert(false, "Invalid mode: " + mode);
},
/**
* Append new node after this.
*
* This a convenience function that calls addNode(node, 'after')
*
* @param {NodeData} node node definition
* @returns {FancytreeNode} new node
*/
appendSibling: function(node){
return this.addNode(node, "after");
},
/**
* Modify existing child nodes.
*
* @param {NodePatch} patch
* @returns {$.Promise}
* @see FancytreeNode#addChildren
*/
applyPatch: function(patch) {
// patch [key, null] means 'remove'
if(patch === null){
this.remove();
return _getResolvedPromise(this);
}
// TODO: make sure that root node is not collapsed or modified
// copy (most) attributes to node.ATTR or node.data.ATTR
var name, promise, v,
IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global
for(name in patch){
v = patch[name];
if( !IGNORE_MAP[name] && !$.isFunction(v)){
if(NODE_ATTR_MAP[name]){
this[name] = v;
}else{
this.data[name] = v;
}
}
}
// Remove and/or create children
if(patch.hasOwnProperty("children")){
this.removeChildren();
if(patch.children){ // only if not null and not empty list
// TODO: addChildren instead?
this._setChildren(patch.children);
}
// TODO: how can we APPEND or INSERT child nodes?
}
if(this.isVisible()){
this.renderTitle();
this.renderStatus();
}
// Expand collapse (final step, since this may be async)
if(patch.hasOwnProperty("expanded")){
promise = this.setExpanded(patch.expanded);
}else{
promise = _getResolvedPromise(this);
}
return promise;
},
/** Collapse all sibling nodes.
* @returns {$.Promise}
*/
collapseSiblings: function() {
return this.tree._callHook("nodeCollapseSiblings", this);
},
/** Copy this node as sibling or child of `node`.
*
* @param {FancytreeNode} node source node
* @param {string} [mode=child] 'before' | 'after' | 'child'
* @param {Function} [map] callback function(NodeData) that could modify the new node
* @returns {FancytreeNode} new
*/
copyTo: function(node, mode, map) {
return node.addNode(this.toDict(true, map), mode);
},
/** Count direct and indirect children.
*
* @param {boolean} [deep=true] pass 'false' to only count direct children
* @returns {int} number of child nodes
*/
countChildren: function(deep) {
var cl = this.children, i, l, n;
if( !cl ){
return 0;
}
n = cl.length;
if(deep !== false){
for(i=0, l=n; i<l; i++){
n += cl[i].countChildren();
}
}
return n;
},
// TODO: deactivate()
/** Write to browser console if debugLevel >= 2 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.tree.options.debugLevel >= 2 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
/** Deprecated.
* @deprecated since 2014-02-16. Use resetLazy() instead.
*/
discard: function(){
this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead.");
return this.resetLazy();
},
// TODO: expand(flag)
/**Find all nodes that contain `match` in the title.
*
* @param {string | function(node)} match string to search for, of a function that
* returns `true` if a node is matched.
* @returns {FancytreeNode[]} array of nodes (may be empty)
* @see FancytreeNode#findAll
*/
findAll: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = [];
this.visit(function(n){
if(match(n)){
res.push(n);
}
});
return res;
},
/**Find first node that contains `match` in the title (not including self).
*
* @param {string | function(node)} match string to search for, of a function that
* returns `true` if a node is matched.
* @returns {FancytreeNode} matching node or null
* @example
* <b>fat</b> text
*/
findFirst: function(match) {
match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
var res = null;
this.visit(function(n){
if(match(n)){
res = n;
return false;
}
});
return res;
},
/* Apply selection state (internal use only) */
_changeSelectStatusAttrs: function (state) {
var changed = false;
switch(state){
case false:
changed = ( this.selected || this.partsel );
this.selected = false;
this.partsel = false;
break;
case true:
changed = ( !this.selected || !this.partsel );
this.selected = true;
this.partsel = true;
break;
case undefined:
changed = ( this.selected || !this.partsel );
this.selected = false;
this.partsel = true;
break;
default:
_assert(false, "invalid state: " + state);
}
// this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed);
if( changed ){
this.renderStatus();
}
return changed;
},
/**
* Fix selection status, after this node was (de)selected in multi-hier mode.
* This includes (de)selecting all children.
*/
fixSelection3AfterClick: function() {
var flag = this.isSelected();
// this.debug("fixSelection3AfterClick()");
this.visit(function(node){
node._changeSelectStatusAttrs(flag);
});
this.fixSelection3FromEndNodes();
},
/**
* Fix selection status for multi-hier mode.
* Only end-nodes are considered to update the descendants branch and parents.
* Should be called after this node has loaded new children or after
* children have been modified using the API.
*/
fixSelection3FromEndNodes: function() {
// this.debug("fixSelection3FromEndNodes()");
_assert(this.tree.options.selectMode === 3, "expected selectMode 3");
// Visit all end nodes and adjust their parent's `selected` and `partsel`
// attributes. Return selection state true, false, or undefined.
function _walk(node){
var i, l, child, s, state, allSelected,someSelected,
children = node.children;
if( children && children.length ){
// check all children recursively
allSelected = true;
someSelected = false;
for( i=0, l=children.length; i<l; i++ ){
child = children[i];
// the selection state of a node is not relevant; we need the end-nodes
s = _walk(child);
if( s !== false ) {
someSelected = true;
}
if( s !== true ) {
allSelected = false;
}
}
state = allSelected ? true : (someSelected ? undefined : false);
}else{
// This is an end-node: simply report the status
// state = ( node.unselectable ) ? undefined : !!node.selected;
state = !!node.selected;
}
node._changeSelectStatusAttrs(state);
return state;
}
_walk(this);
// Update parent's state
this.visitParents(function(node){
var i, l, child, state,
children = node.children,
allSelected = true,
someSelected = false;
for( i=0, l=children.length; i<l; i++ ){
child = children[i];
// When fixing the parents, we trust the sibling status (i.e.
// we don't recurse)
if( child.selected || child.partsel ) {
someSelected = true;
}
if( !child.unselectable && !child.selected ) {
allSelected = false;
}
}
state = allSelected ? true : (someSelected ? undefined : false);
node._changeSelectStatusAttrs(state);
});
},
// TODO: focus()
/**
* Update node data. If dict contains 'children', then also replace
* the hole sub tree.
* @param {NodeData} dict
*
* @see FancytreeNode#addChildren
* @see FancytreeNode#applyPatch
*/
fromDict: function(dict) {
// copy all other attributes to this.data.xxx
for(var name in dict){
if(NODE_ATTR_MAP[name]){
// node.NAME = dict.NAME
this[name] = dict[name];
}else if(name === "data"){
// node.data += dict.data
$.extend(this.data, dict.data);
}else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){
// node.data.NAME = dict.NAME
this.data[name] = dict[name];
}
}
if(dict.children){
// recursively set children and render
this.removeChildren();
this.addChildren(dict.children);
}
this.renderTitle();
/*
var children = dict.children;
if(children === undefined){
this.data = $.extend(this.data, dict);
this.render();
return;
}
dict = $.extend({}, dict);
dict.children = undefined;
this.data = $.extend(this.data, dict);
this.removeChildren();
this.addChild(children);
*/
},
/** Return the list of child nodes (undefined for unexpanded lazy nodes).
* @returns {FancytreeNode[] | undefined}
*/
getChildren: function() {
if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes?
return undefined; // Lazy node: unloaded, currently loading, or load error
}
return this.children;
},
/** Return the first child node or null.
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.children ? this.children[0] : null;
},
/** Return the 0-based child index.
* @returns {int}
*/
getIndex: function() {
// return this.parent.children.indexOf(this);
return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7
},
/** Return the hierarchical child index (1-based, e.g. '3.2.4').
* @returns {string}
*/
getIndexHier: function(separator) {
separator = separator || ".";
var res = [];
$.each(this.getParentList(false, true), function(i, o){
res.push(o.getIndex() + 1);
});
return res.join(separator);
},
/** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32".
* @param {boolean} [excludeSelf=false]
* @returns {string}
*/
getKeyPath: function(excludeSelf) {
var path = [],
sep = this.tree.options.keyPathSeparator;
this.visitParents(function(n){
if(n.parent){
path.unshift(n.key);
}
}, !excludeSelf);
return sep + path.join(sep);
},
/** Return the last child of this node or null.
* @returns {FancytreeNode | null}
*/
getLastChild: function() {
return this.children ? this.children[this.children.length - 1] : null;
},
/** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... .
* @returns {int}
*/
getLevel: function() {
var level = 0,
dtn = this.parent;
while( dtn ) {
level++;
dtn = dtn.parent;
}
return level;
},
/** Return the successor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getNextSibling: function() {
// TODO: use indexOf, if available: (not in IE6)
if( this.parent ){
var i, l,
ac = this.parent.children;
for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null
if( ac[i] === this ){
return ac[i+1];
}
}
}
return null;
},
/** Return the parent node (null for the system root node).
* @returns {FancytreeNode | null}
*/
getParent: function() {
// TODO: return null for top-level nodes?
return this.parent;
},
/** Return an array of all parent nodes (top-down).
* @param {boolean} [includeRoot=false] Include the invisible system root node.
* @param {boolean} [includeSelf=false] Include the node itself.
* @returns {FancytreeNode[]}
*/
getParentList: function(includeRoot, includeSelf) {
var l = [],
dtn = includeSelf ? this : this.parent;
while( dtn ) {
if( includeRoot || dtn.parent ){
l.unshift(dtn);
}
dtn = dtn.parent;
}
return l;
},
/** Return the predecessor node (under the same parent) or null.
* @returns {FancytreeNode | null}
*/
getPrevSibling: function() {
if( this.parent ){
var i, l,
ac = this.parent.children;
for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null
if( ac[i] === this ){
return ac[i-1];
}
}
}
return null;
},
/** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded).
* @returns {boolean | undefined}
*/
hasChildren: function() {
if(this.lazy){
if(this.children == null ){
// null or undefined: Not yet loaded
return undefined;
}else if(this.children.length === 0){
// Loaded, but response was empty
return false;
}else if(this.children.length === 1 && this.children[0].isStatusNode() ){
// Currently loading or load error
return undefined;
}
return true;
}
return !!( this.children && this.children.length );
},
/** Return true if node has keyboard focus.
* @returns {boolean}
*/
hasFocus: function() {
return (this.tree.hasFocus() && this.tree.focusNode === this);
},
/** Write to browser console if debugLevel >= 1 (prepending node info)
*
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.tree.options.debugLevel >= 1 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/** Return true if node is active (see also FancytreeNode#isSelected).
* @returns {boolean}
*/
isActive: function() {
return (this.tree.activeNode === this);
},
/** Return true if node is a direct child of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isChildOf: function(otherNode) {
return (this.parent && this.parent === otherNode);
},
/** Return true, if node is a direct or indirect sub node of otherNode.
* @param {FancytreeNode} otherNode
* @returns {boolean}
*/
isDescendantOf: function(otherNode) {
if(!otherNode || otherNode.tree !== this.tree){
return false;
}
var p = this.parent;
while( p ) {
if( p === otherNode ){
return true;
}
p = p.parent;
}
return false;
},
/** Return true if node is expanded.
* @returns {boolean}
*/
isExpanded: function() {
return !!this.expanded;
},
/** Return true if node is the first node of its parent's children.
* @returns {boolean}
*/
isFirstSibling: function() {
var p = this.parent;
return !p || p.children[0] === this;
},
/** Return true if node is a folder, i.e. has the node.folder attribute set.
* @returns {boolean}
*/
isFolder: function() {
return !!this.folder;
},
/** Return true if node is the last node of its parent's children.
* @returns {boolean}
*/
isLastSibling: function() {
var p = this.parent;
return !p || p.children[p.children.length-1] === this;
},
/** Return true if node is lazy (even if data was already loaded)
* @returns {boolean}
*/
isLazy: function() {
return !!this.lazy;
},
/** Return true if node is lazy and loaded. For non-lazy nodes always return true.
* @returns {boolean}
*/
isLoaded: function() {
return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node
},
/** Return true if children are currently beeing loaded, i.e. a Ajax request is pending.
* @returns {boolean}
*/
isLoading: function() {
return !!this._isLoading;
},
/**
* @deprecated since v2.4.0: Use isRootNode() instead
*/
isRoot: function() {
return this.isRootNode();
},
/** Return true if this is the (invisible) system root node.
* @returns {boolean}
*/
isRootNode: function() {
return (this.tree.rootNode === this);
},
/** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive).
* @returns {boolean}
*/
isSelected: function() {
return !!this.selected;
},
/** Return true if this node is a temporarily generated system node like
* 'loading', or 'error' (node.statusNodeType contains the type).
* @returns {boolean}
*/
isStatusNode: function() {
return !!this.statusNodeType;
},
/** Return true if this a top level node, i.e. a direct child of the (invisible) system root node.
* @returns {boolean}
*/
isTopLevel: function() {
return (this.tree.rootNode === this.parent);
},
/** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false.
* @returns {boolean}
*/
isUndefined: function() {
return this.hasChildren() === undefined; // also checks if the only child is a status node
},
/** Return true if all parent nodes are expanded. Note: this does not check
* whether the node is scrolled into the visible part of the screen.
* @returns {boolean}
*/
isVisible: function() {
var i, l,
parents = this.getParentList(false, false);
for(i=0, l=parents.length; i<l; i++){
if( ! parents[i].expanded ){ return false; }
}
return true;
},
/** Deprecated.
* @deprecated since 2014-02-16: use load() instead.
*/
lazyLoad: function(discard) {
this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead.");
return this.load(discard);
},
/**
* Load all children of a lazy node if neccessary. The *expanded* state is maintained.
* @param {boolean} [forceReload=false] Pass true to discard any existing nodes before.
* @returns {$.Promise}
*/
load: function(forceReload) {
var res, source,
that = this;
_assert( this.isLazy(), "load() requires a lazy node" );
// _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" );
if( !forceReload && !this.isUndefined() ) {
return _getResolvedPromise(this);
}
if( this.isLoaded() ){
this.resetLazy(); // also collapses
}
// This method is also called by setExpanded() and loadKeyPath(), so we
// have to avoid recursion.
source = this.tree._triggerNodeEvent("lazyLoad", this);
if( source === false ) { // #69
return _getResolvedPromise(this);
}
_assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
res = this.tree._callHook("nodeLoadChildren", this, source);
if( this.expanded ) {
res.always(function(){
that.render();
});
}
return res;
},
/** Expand all parents and optionally scroll into visible area as neccessary.
* Promise is resolved, when lazy loading and animations are done.
* @param {object} [opts] passed to `setExpanded()`.
* Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true}
* @returns {$.Promise}
*/
makeVisible: function(opts) {
var i,
that = this,
deferreds = [],
dfd = new $.Deferred(),
parents = this.getParentList(false, false),
len = parents.length,
effects = !(opts && opts.noAnimation === true),
scroll = !(opts && opts.scrollIntoView === false);
// Expand bottom-up, so only the top node is animated
for(i = len - 1; i >= 0; i--){
// that.debug("pushexpand" + parents[i]);
deferreds.push(parents[i].setExpanded(true, opts));
}
$.when.apply($, deferreds).done(function(){
// All expands have finished
// that.debug("expand DONE", scroll);
if( scroll ){
that.scrollIntoView(effects).done(function(){
// that.debug("scroll DONE");
dfd.resolve();
});
} else {
dfd.resolve();
}
});
return dfd.promise();
},
/** Move this node to targetNode.
* @param {FancytreeNode} targetNode
* @param {string} mode <pre>
* 'child': append this node as last child of targetNode.
* This is the default. To be compatble with the D'n'd
* hitMode, we also accept 'over'.
* 'before': add this node as sibling before targetNode.
* 'after': add this node as sibling after targetNode.</pre>
* @param {function} [map] optional callback(FancytreeNode) to allow modifcations
*/
moveTo: function(targetNode, mode, map) {
if(mode === undefined || mode === "over"){
mode = "child";
}
var pos,
prevParent = this.parent,
targetParent = (mode === "child") ? targetNode : targetNode.parent;
if(this === targetNode){
return;
}else if( !this.parent ){
throw "Cannot move system root";
}else if( targetParent.isDescendantOf(this) ){
throw "Cannot move a node to its own descendant";
}
// Unlink this node from current parent
if( this.parent.children.length === 1 ) {
if( this.parent === targetParent ){
return; // #258
}
this.parent.children = this.parent.lazy ? [] : null;
this.parent.expanded = false;
} else {
pos = $.inArray(this, this.parent.children);
_assert(pos >= 0);
this.parent.children.splice(pos, 1);
}
// Remove from source DOM parent
// if(this.parent.ul){
// this.parent.ul.removeChild(this.li);
// }
// Insert this node to target parent's child list
this.parent = targetParent;
if( targetParent.hasChildren() ) {
switch(mode) {
case "child":
// Append to existing target children
targetParent.children.push(this);
break;
case "before":
// Insert this node before target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0);
targetParent.children.splice(pos, 0, this);
break;
case "after":
// Insert this node after target node
pos = $.inArray(targetNode, targetParent.children);
_assert(pos >= 0);
targetParent.children.splice(pos+1, 0, this);
break;
default:
throw "Invalid mode " + mode;
}
} else {
targetParent.children = [ this ];
}
// Parent has no <ul> tag yet:
// if( !targetParent.ul ) {
// // This is the parent's first child: create UL tag
// // (Hidden, because it will be
// targetParent.ul = document.createElement("ul");
// targetParent.ul.style.display = "none";
// targetParent.li.appendChild(targetParent.ul);
// }
// // Issue 319: Add to target DOM parent (only if node was already rendered(expanded))
// if(this.li){
// targetParent.ul.appendChild(this.li);
// }^
// Let caller modify the nodes
if( map ){
targetNode.visit(map, true);
}
// Handle cross-tree moves
if( this.tree !== targetNode.tree ) {
// Fix node.tree for all source nodes
// _assert(false, "Cross-tree move is not yet implemented.");
this.warn("Cross-tree moveTo is experimantal!");
this.visit(function(n){
// TODO: fix selection state and activation, ...
n.tree = targetNode.tree;
}, true);
}
// A collaposed node won't re-render children, so we have to remove it manually
// if( !targetParent.expanded ){
// prevParent.ul.removeChild(this.li);
// }
// Update HTML markup
if( !prevParent.isDescendantOf(targetParent)) {
prevParent.render();
}
if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) {
targetParent.render();
}
// TODO: fix selection state
// TODO: fix active state
/*
var tree = this.tree;
var opts = tree.options;
var pers = tree.persistence;
// Always expand, if it's below minExpandLevel
// tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel());
if ( opts.minExpandLevel >= ftnode.getLevel() ) {
// tree.logDebug ("Force expand for %o", ftnode);
this.bExpanded = true;
}
// In multi-hier mode, update the parents selection state
// DT issue #82: only if not initializing, because the children may not exist yet
// if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing )
// ftnode._fixSelectionState();
// In multi-hier mode, update the parents selection state
if( ftnode.bSelected && opts.selectMode==3 ) {
var p = this;
while( p ) {
if( !p.hasSubSel )
p._setSubSel(true);
p = p.parent;
}
}
// render this node and the new child
if ( tree.bEnableUpdate )
this.render();
return ftnode;
*/
},
/** Set focus relative to this node and optionally activate.
*
* @param {number} where The keyCode that would normally trigger this move,
* e.g. `$.ui.keyCode.LEFT` would collapse the node if it
* is expanded or move to the parent oterwise.
* @param {boolean} [activate=true]
* @returns {$.Promise}
*/
// navigate: function(where, activate) {
// console.time("navigate")
// this._navigate(where, activate)
// console.timeEnd("navigate")
// },
navigate: function(where, activate) {
var i, parents,
handled = true,
KC = $.ui.keyCode,
sib = null;
// Navigate to node
function _goto(n){
if( n ){
try { n.makeVisible(); } catch(e) {} // #272
// Node may still be hidden by a filter
if( ! $(n.span).is(":visible") ) {
n.debug("Navigate: skipping hidden node");
n.navigate(where, activate);
return;
}
return activate === false ? n.setFocus() : n.setActive();
}
}
switch( where ) {
case KC.BACKSPACE:
if( this.parent && this.parent.parent ) {
_goto(this.parent);
}
break;
case KC.LEFT:
if( this.expanded ) {
this.setExpanded(false);
_goto(this);
} else if( this.parent && this.parent.parent ) {
_goto(this.parent);
}
break;
case KC.RIGHT:
if( !this.expanded && (this.children || this.lazy) ) {
this.setExpanded();
_goto(this);
} else if( this.children && this.children.length ) {
_goto(this.children[0]);
}
break;
case KC.UP:
sib = this.getPrevSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getPrevSibling();
}
while( sib && sib.expanded && sib.children && sib.children.length ) {
sib = sib.children[sib.children.length - 1];
}
if( !sib && this.parent && this.parent.parent ){
sib = this.parent;
}
_goto(sib);
break;
case KC.DOWN:
if( this.expanded && this.children && this.children.length ) {
sib = this.children[0];
} else {
parents = this.getParentList(false, true);
for(i=parents.length-1; i>=0; i--) {
sib = parents[i].getNextSibling();
// #359: skip hidden sibling nodes, preventing a _goto() recursion
while( sib && !$(sib.span).is(":visible") ) {
sib = sib.getNextSibling();
}
if( sib ){ break; }
}
}
_goto(sib);
break;
default:
handled = false;
}
},
/**
* Remove this node (not allowed for system root).
*/
remove: function() {
return this.parent.removeChild(this);
},
/**
* Remove childNode from list of direct children.
* @param {FancytreeNode} childNode
*/
removeChild: function(childNode) {
return this.tree._callHook("nodeRemoveChild", this, childNode);
},
/**
* Remove all child nodes and descendents. This converts the node into a leaf.<br>
* If this was a lazy node, it is still considered 'loaded'; call node.resetLazy()
* in order to trigger lazyLoad on next expand.
*/
removeChildren: function() {
return this.tree._callHook("nodeRemoveChildren", this);
},
/**
* This method renders and updates all HTML markup that is required
* to display this node in its current state.<br>
* Note:
* <ul>
* <li>It should only be neccessary to call this method after the node object
* was modified by direct access to its properties, because the common
* API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...)
* already handle this.
* <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus}
* are implied. If changes are more local, calling only renderTitle() or
* renderStatus() may be sufficient and faster.
* <li>If a node was created/removed, node.render() must be called <i>on the parent</i>.
* </ul>
*
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
*/
render: function(force, deep) {
return this.tree._callHook("nodeRender", this, force, deep);
},
/** Create HTML markup for the node's outer <span> (expander, checkbox, icon, and title).
* @see Fancytree_Hooks#nodeRenderTitle
*/
renderTitle: function() {
return this.tree._callHook("nodeRenderTitle", this);
},
/** Update element's CSS classes according to node state.
* @see Fancytree_Hooks#nodeRenderStatus
*/
renderStatus: function() {
return this.tree._callHook("nodeRenderStatus", this);
},
/**
* Remove all children, collapse, and set the lazy-flag, so that the lazyLoad
* event is triggered on next expand.
*/
resetLazy: function() {
this.removeChildren();
this.expanded = false;
this.lazy = true;
this.children = undefined;
this.renderStatus();
},
/** Schedule activity for delayed execution (cancel any pending request).
* scheduleAction('cancel') will only cancel a pending request (if any).
* @param {string} mode
* @param {number} ms
*/
scheduleAction: function(mode, ms) {
if( this.tree.timer ) {
clearTimeout(this.tree.timer);
// this.tree.debug("clearTimeout(%o)", this.tree.timer);
}
this.tree.timer = null;
var self = this; // required for closures
switch (mode) {
case "cancel":
// Simply made sure that timer was cleared
break;
case "expand":
this.tree.timer = setTimeout(function(){
self.tree.debug("setTimeout: trigger expand");
self.setExpanded(true);
}, ms);
break;
case "activate":
this.tree.timer = setTimeout(function(){
self.tree.debug("setTimeout: trigger activate");
self.setActive(true);
}, ms);
break;
default:
throw "Invalid mode " + mode;
}
// this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer);
},
/**
*
* @param {boolean | PlainObject} [effects=false] animation options.
* @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in
* any case, even if `this` is outside the scroll pane.
* @returns {$.Promise}
*/
scrollIntoView: function(effects, options) {
if( options !== undefined && _isNode(options) ) {
this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead.");
options = {topNode: options};
}
// this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent);
// this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container;
var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop,
opts = $.extend({
effects: (effects === true) ? {duration: 200, queue: false} : effects,
scrollOfs: this.tree.options.scrollOfs,
scrollParent: this.tree.options.scrollParent || this.tree.$container,
topNode: null
}, options),
dfd = new $.Deferred(),
that = this,
nodeHeight = $(this.span).height(),
$container = $(opts.scrollParent),
topOfs = opts.scrollOfs.top || 0,
bottomOfs = opts.scrollOfs.bottom || 0,
containerHeight = $container.height(),// - topOfs - bottomOfs,
scrollTop = $container.scrollTop(),
$animateTarget = $container,
isParentWindow = $container[0] === window,
topNode = opts.topNode || null,
newScrollTop = null;
// this.debug("scrollIntoView(), scrollTop=", scrollTop, opts.scrollOfs);
_assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets
if( isParentWindow ) {
nodeY = $(this.span).offset().top;
topNodeY = (topNode && topNode.span) ? $(topNode.span).offset().top : 0;
$animateTarget = $("html,body");
} else {
_assert($container[0] !== document && $container[0] !== document.body, "scrollParent should be an simple element or `window`, not document or body.");
containerOffsetTop = $container.offset().top,
nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent
topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0;
horzScrollbarHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight));
containerHeight -= horzScrollbarHeight;
}
// this.debug(" scrollIntoView(), nodeY=", nodeY, "containerHeight=", containerHeight);
if( nodeY < (scrollTop + topOfs) ){
// Node is above visible container area
newScrollTop = nodeY - topOfs;
// this.debug(" scrollIntoView(), UPPER newScrollTop=", newScrollTop);
}else if((nodeY + nodeHeight) > (scrollTop + containerHeight - bottomOfs)){
newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs;
// this.debug(" scrollIntoView(), LOWER newScrollTop=", newScrollTop);
// If a topNode was passed, make sure that it is never scrolled
// outside the upper border
if(topNode){
_assert(topNode.isRoot() || $(topNode.span).is(":visible"), "topNode must be visible");
if( topNodeY < newScrollTop ){
newScrollTop = topNodeY - topOfs;
// this.debug(" scrollIntoView(), TOP newScrollTop=", newScrollTop);
}
}
}
if(newScrollTop !== null){
// this.debug(" scrollIntoView(), SET newScrollTop=", newScrollTop);
if(opts.effects){
opts.effects.complete = function(){
dfd.resolveWith(that);
};
$animateTarget.stop(true).animate({
scrollTop: newScrollTop
}, opts.effects);
}else{
$animateTarget[0].scrollTop = newScrollTop;
dfd.resolveWith(this);
}
}else{
dfd.resolveWith(this);
}
return dfd.promise();
},
/**Activate this node.
* @param {boolean} [flag=true] pass false to deactivate
* @param {object} [opts] additional options. Defaults to {noEvents: false}
*/
setActive: function(flag, opts){
return this.tree._callHook("nodeSetActive", this, flag, opts);
},
/**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done.
* @param {boolean} [flag=true] pass false to collapse
* @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
* @returns {$.Promise}
*/
setExpanded: function(flag, opts){
return this.tree._callHook("nodeSetExpanded", this, flag, opts);
},
/**Set keyboard focus to this node.
* @param {boolean} [flag=true] pass false to blur
* @see Fancytree#setFocus
*/
setFocus: function(flag){
return this.tree._callHook("nodeSetFocus", this, flag);
},
/**Select this node, i.e. check the checkbox.
* @param {boolean} [flag=true] pass false to deselect
*/
setSelected: function(flag){
return this.tree._callHook("nodeSetSelected", this, flag);
},
/**Mark a lazy node as 'error', 'loading', or 'ok'.
* @param {string} status 'error', 'ok'
* @param {string} [message]
* @param {string} [details]
*/
setStatus: function(status, message, details){
return this.tree._callHook("nodeSetStatus", this, status, message, details);
},
/**Rename this node.
* @param {string} title
*/
setTitle: function(title){
this.title = title;
this.renderTitle();
},
/**Sort child list by title.
* @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title).
* @param {boolean} [deep=false] pass true to sort all descendant nodes
*/
sortChildren: function(cmp, deep) {
var i,l,
cl = this.children;
if( !cl ){
return;
}
cmp = cmp || function(a, b) {
var x = a.title.toLowerCase(),
y = b.title.toLowerCase();
return x === y ? 0 : x > y ? 1 : -1;
};
cl.sort(cmp);
if( deep ){
for(i=0, l=cl.length; i<l; i++){
if( cl[i].children ){
cl[i].sortChildren(cmp, "$norender$");
}
}
}
if( deep !== "$norender$" ){
this.render();
}
},
/** Convert node (or whole branch) into a plain object.
*
* The result is compatible with node.addChildren().
*
* @param {boolean} [recursive=false] include child nodes
* @param {function} [callback] callback(dict) is called for every node, in order to allow modifications
* @returns {NodeData}
*/
toDict: function(recursive, callback) {
var i, l, node,
dict = {},
self = this;
$.each(NODE_ATTRS, function(i, a){
if(self[a] || self[a] === false){
dict[a] = self[a];
}
});
if(!$.isEmptyObject(this.data)){
dict.data = $.extend({}, this.data);
if($.isEmptyObject(dict.data)){
delete dict.data;
}
}
if( callback ){
callback(dict);
}
if( recursive ) {
if(this.hasChildren()){
dict.children = [];
for(i=0, l=this.children.length; i<l; i++ ){
node = this.children[i];
if( !node.isStatusNode() ){
dict.children.push(node.toDict(true, callback));
}
}
}else{
// dict.children = null;
}
}
return dict;
},
/** Flip expanded status. */
toggleExpanded: function(){
return this.tree._callHook("nodeToggleExpanded", this);
},
/** Flip selection status. */
toggleSelected: function(){
return this.tree._callHook("nodeToggleSelected", this);
},
toString: function() {
return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>";
},
/** Call fn(node) for all child nodes.<br>
* Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visit: function(fn, includeSelf) {
var i, l,
res = true,
children = this.children;
if( includeSelf === true ) {
res = fn(this);
if( res === false || res === "skip" ){
return res;
}
}
if(children){
for(i=0, l=children.length; i<l; i++){
res = children[i].visit(fn, true);
if( res === false ){
break;
}
}
}
return res;
},
/** Call fn(node) for all child nodes and recursively load lazy children.<br>
* <b>Note:</b> If you need this method, you probably should consider to review
* your architecture! Recursivley loading nodes is a perfect way for lazy
* programmers to flood the server with requests ;-)
*
* @param {function} [fn] optional callback function.
* Return false to stop iteration, return "skip" to skip this node and
* its children only.
* @param {boolean} [includeSelf=false]
* @returns {$.Promise}
*/
visitAndLoad: function(fn, includeSelf, _recursion) {
var dfd, res, loaders,
node = this;
// node.debug("visitAndLoad");
if( fn && includeSelf === true ) {
res = fn(node);
if( res === false || res === "skip" ) {
return _recursion ? res : _getResolvedPromise();
}
}
if( !node.children && !node.lazy ) {
return _getResolvedPromise();
}
dfd = new $.Deferred();
loaders = [];
// node.debug("load()...");
node.load().done(function(){
// node.debug("load()... done.");
for(var i=0, l=node.children.length; i<l; i++){
res = node.children[i].visitAndLoad(fn, true, true);
if( res === false ) {
dfd.reject();
break;
} else if ( res !== "skip" ) {
loaders.push(res); // Add promise to the list
}
}
$.when.apply(this, loaders).then(function(){
dfd.resolve();
});
});
return dfd.promise();
},
/** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br>
* Stop iteration, if fn() returns false.<br>
* Return false if iteration was stopped.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @param {boolean} [includeSelf=false]
* @returns {boolean}
*/
visitParents: function(fn, includeSelf) {
// Visit parent nodes (bottom up)
if(includeSelf && fn(this) === false){
return false;
}
var p = this.parent;
while( p ) {
if(fn(p) === false){
return false;
}
p = p.parent;
}
return true;
},
/** Write warning to browser console (prepending node info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
};
/* *****************************************************************************
* Fancytree
*/
/**
* Construct a new tree object.
*
* @class Fancytree
* @classdesc The controller behind a fancytree.
* This class also contains 'hook methods': see {@link Fancytree_Hooks}.
*
* @param {Widget} widget
*
* @property {FancytreeOptions} options
* @property {FancytreeNode} rootNode
* @property {FancytreeNode} activeNode
* @property {FancytreeNode} focusNode
* @property {jQueryObject} $div
* @property {object} widget
* @property {object} ext
* @property {object} data
* @property {object} options
* @property {string} _id
* @property {string} statusClassPropName
* @property {string} ariaPropName
* @property {string} nodeContainerAttrName
* @property {string} $container
* @property {FancytreeNode} lastSelectedNode
*/
function Fancytree(widget) {
this.widget = widget;
this.$div = widget.element;
this.options = widget.options;
if( this.options && $.isFunction(this.options.lazyload) ) {
if( ! $.isFunction(this.options.lazyLoad ) ) {
this.options.lazyLoad = function() {
FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead.");
widget.options.lazyload.apply(this, arguments);
};
}
}
if( this.options && $.isFunction(this.options.loaderror) ) {
$.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead.");
}
this.ext = {}; // Active extension instances
// allow to init tree.data.foo from <div data-foo=''>
this.data = _getElementDataAsDict(this.$div);
this._id = $.ui.fancytree._nextId++;
this._ns = ".fancytree-" + this._id; // append for namespaced events
this.activeNode = null;
this.focusNode = null;
this._hasFocus = null;
this.lastSelectedNode = null;
this.systemFocusElement = null;
this.lastQuicksearchTerm = "";
this.lastQuicksearchTime = 0;
this.statusClassPropName = "span";
this.ariaPropName = "li";
this.nodeContainerAttrName = "li";
// Remove previous markup if any
this.$div.find(">ul.fancytree-container").remove();
// Create a node without parent.
var fakeParent = { tree: this },
$ul;
this.rootNode = new FancytreeNode(fakeParent, {
title: "root",
key: "root_" + this._id,
children: null,
expanded: true
});
this.rootNode.parent = null;
// Create root markup
$ul = $("<ul>", {
"class": "ui-fancytree fancytree-container"
}).appendTo(this.$div);
this.$container = $ul;
this.rootNode.ul = $ul[0];
if(this.options.debugLevel == null){
this.options.debugLevel = FT.debugLevel;
}
// Add container to the TAB chain
// See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
if(this.options.aria){
this.$container
.attr("role", "tree")
.attr("aria-multiselectable", true);
}
}
Fancytree.prototype = /** @lends Fancytree# */{
/* Return a context object that can be re-used for _callHook().
* @param {Fancytree | FancytreeNode | EventData} obj
* @param {Event} originalEvent
* @param {Object} extra
* @returns {EventData}
*/
_makeHookContext: function(obj, originalEvent, extra) {
var ctx, tree;
if(obj.node !== undefined){
// obj is already a context object
if(originalEvent && obj.originalEvent !== originalEvent){
$.error("invalid args");
}
ctx = obj;
}else if(obj.tree){
// obj is a FancytreeNode
tree = obj.tree;
ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent };
}else if(obj.widget){
// obj is a Fancytree
ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent };
}else{
$.error("invalid args");
}
if(extra){
$.extend(ctx, extra);
}
return ctx;
},
/* Trigger a hook function: funcName(ctx, [...]).
*
* @param {string} funcName
* @param {Fancytree|FancytreeNode|EventData} contextObject
* @param {any} [_extraArgs] optional additional arguments
* @returns {any}
*/
_callHook: function(funcName, contextObject, _extraArgs) {
var ctx = this._makeHookContext(contextObject),
fn = this[funcName],
args = Array.prototype.slice.call(arguments, 2);
if(!$.isFunction(fn)){
$.error("_callHook('" + funcName + "') is not a function");
}
args.unshift(ctx);
// this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args);
return fn.apply(this, args);
},
/* Check if current extensions dependencies are met and throw an error if not.
*
* This method may be called inside the `treeInit` hook for custom extensions.
*
* @param {string} extension name of the required extension
* @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present
* @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter)
* @param {string} [message] optional error message (defaults to a descriptve error message)
*/
_requireExtension: function(name, required, before, message) {
before = !!before;
var thisName = this._local.name,
extList = this.options.extensions,
isBefore = $.inArray(name, extList) < $.inArray(thisName, extList),
isMissing = required && this.ext[name] == null,
badOrder = !isMissing && before != null && (before !== isBefore);
_assert(thisName && thisName !== name);
if( isMissing || badOrder ){
if( !message ){
if( isMissing || required ){
message = "'" + thisName + "' extension requires '" + name + "'";
if( badOrder ){
message += " to be registered " + (before ? "before" : "after") + " itself";
}
}else{
message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`";
}
}
$.error(message);
return false;
}
return true;
},
/** Activate node with a given key and fire focus and activate events.
*
* A prevously activated node will be deactivated.
* If activeVisible option is set, all parents will be expanded as necessary.
* Pass key = false, to deactivate the current node only.
* @param {string} key
* @returns {FancytreeNode} activated node (null, if not found)
*/
activateKey: function(key) {
var node = this.getNodeByKey(key);
if(node){
node.setActive();
}else if(this.activeNode){
this.activeNode.setActive(false);
}
return node;
},
/** (experimental)
*
* @param {Array} patchList array of [key, NodePatch] arrays
* @returns {$.Promise} resolved, when all patches have been applied
* @see TreePatch
*/
applyPatch: function(patchList) {
var dfd, i, p2, key, patch, node,
patchCount = patchList.length,
deferredList = [];
for(i=0; i<patchCount; i++){
p2 = patchList[i];
_assert(p2.length === 2, "patchList must be an array of length-2-arrays");
key = p2[0];
patch = p2[1];
node = (key === null) ? this.rootNode : this.getNodeByKey(key);
if(node){
dfd = new $.Deferred();
deferredList.push(dfd);
node.applyPatch(patch).always(_makeResolveFunc(dfd, node));
}else{
this.warn("could not find node with key '" + key + "'");
}
}
// Return a promise that is resovled, when ALL patches were applied
return $.when.apply($, deferredList).promise();
},
/* TODO: implement in dnd extension
cancelDrag: function() {
var dd = $.ui.ddmanager.current;
if(dd){
dd.cancel();
}
},
*/
/** Return the number of nodes.
* @returns {integer}
*/
count: function() {
return this.rootNode.countChildren();
},
/** Write to browser console if debugLevel >= 2 (prepending tree name)
*
* @param {*} msg string or object or array of such
*/
debug: function(msg){
if( this.options.debugLevel >= 2 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("log", arguments);
}
},
// TODO: disable()
// TODO: enable()
// TODO: enableUpdate()
/** Find the next visible node that starts with `match`, starting at `startNode`
* and wrap-around at the end.
*
* @param {string|function} match
* @param {FancytreeNode} [startNode] defaults to first node
* @returns {FancytreeNode} matching node or null
*/
findNextNode: function(match, startNode, visibleOnly) {
var stopNode = null,
parentChildren = startNode.parent.children,
matchingNode = null,
walkVisible = function(parent, idx, fn) {
var i, grandParent,
parentChildren = parent.children,
siblingCount = parentChildren.length,
node = parentChildren[idx];
// visit node itself
if( node && fn(node) === false ) {
return false;
}
// visit descendants
if( node && node.children && node.expanded ) {
if( walkVisible(node, 0, fn) === false ) {
return false;
}
}
// visit subsequent siblings
for( i = idx + 1; i < siblingCount; i++ ) {
if( walkVisible(parent, i, fn) === false ) {
return false;
}
}
// visit parent's subsequent siblings
grandParent = parent.parent;
if( grandParent ) {
return walkVisible(grandParent, grandParent.children.indexOf(parent) + 1, fn);
} else {
// wrap-around: restart with first node
return walkVisible(parent, 0, fn);
}
};
match = (typeof match === "string") ? _makeNodeTitleStartMatcher(match) : match;
startNode = startNode || this.getFirstChild();
walkVisible(startNode.parent, parentChildren.indexOf(startNode), function(node){
// Stop iteration if we see the start node a second time
if( node === stopNode ) {
return false;
}
stopNode = stopNode || node;
// Ignore nodes hidden by a filter
if( ! $(node.span).is(":visible") ) {
node.debug("quicksearch: skipping hidden node");
return;
}
// Test if we found a match, but search for a second match if this
// was the currently active node
if( match(node) ) {
// node.debug("quicksearch match " + node.title, startNode);
matchingNode = node;
if( matchingNode !== startNode ) {
return false;
}
}
});
return matchingNode;
},
// TODO: fromDict
/**
* Generate INPUT elements that can be submitted with html forms.
*
* In selectMode 3 only the topmost selected nodes are considered.
*
* @param {boolean | string} [selected=true]
* @param {boolean | string} [active=true]
*/
generateFormElements: function(selected, active) {
// TODO: test case
var nodeList,
selectedName = (selected !== false) ? "ft_" + this._id + "[]" : selected,
activeName = (active !== false) ? "ft_" + this._id + "_active" : active,
id = "fancytree_result_" + this._id,
$result = $("#" + id);
if($result.length){
$result.empty();
}else{
$result = $("<div>", {
id: id
}).hide().insertAfter(this.$container);
}
if(selectedName){
nodeList = this.getSelectedNodes( this.options.selectMode === 3 );
$.each(nodeList, function(idx, node){
$result.append($("<input>", {
type: "checkbox",
name: selectedName,
value: node.key,
checked: true
}));
});
}
if(activeName && this.activeNode){
$result.append($("<input>", {
type: "radio",
name: activeName,
value: this.activeNode.key,
checked: true
}));
}
},
/**
* Return the currently active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.activeNode;
},
/** Return the first top level node if any (not the invisible root node).
* @returns {FancytreeNode | null}
*/
getFirstChild: function() {
return this.rootNode.getFirstChild();
},
/**
* Return node that has keyboard focus.
* @param {boolean} [ifTreeHasFocus=false] (not yet implemented)
* @returns {FancytreeNode}
*/
getFocusNode: function(ifTreeHasFocus) {
// TODO: implement ifTreeHasFocus
return this.focusNode;
},
/**
* Return node with a given key or null if not found.
* @param {string} key
* @param {FancytreeNode} [searchRoot] only search below this node
* @returns {FancytreeNode | null}
*/
getNodeByKey: function(key, searchRoot) {
// Search the DOM by element ID (assuming this is faster than traversing all nodes).
// $("#...") has problems, if the key contains '.', so we use getElementById()
var el, match;
if(!searchRoot){
el = document.getElementById(this.options.idPrefix + key);
if( el ){
return el.ftnode ? el.ftnode : null;
}
}
// Not found in the DOM, but still may be in an unrendered part of tree
// TODO: optimize with specialized loop
// TODO: consider keyMap?
searchRoot = searchRoot || this.rootNode;
match = null;
searchRoot.visit(function(node){
// window.console.log("getNodeByKey(" + key + "): ", node.key);
if(node.key === key) {
match = node;
return false;
}
}, true);
return match;
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.rootNode;
},
/**
* Return an array of selected nodes.
* @param {boolean} [stopOnParents=false] only return the topmost selected
* node (useful with selectMode 3)
* @returns {FancytreeNode[]}
*/
getSelectedNodes: function(stopOnParents) {
var nodeList = [];
this.rootNode.visit(function(node){
if( node.selected ) {
nodeList.push(node);
if( stopOnParents === true ){
return "skip"; // stop processing this branch
}
}
});
return nodeList;
},
/** Return true if the tree control has keyboard focus
* @returns {boolean}
*/
hasFocus: function(){
return !!this._hasFocus;
},
/** Write to browser console if debugLevel >= 1 (prepending tree name)
* @param {*} msg string or object or array of such
*/
info: function(msg){
if( this.options.debugLevel >= 1 ) {
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("info", arguments);
}
},
/*
TODO: isInitializing: function() {
return ( this.phase=="init" || this.phase=="postInit" );
},
TODO: isReloading: function() {
return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound;
},
TODO: isUserEvent: function() {
return ( this.phase=="userEvent" );
},
*/
/**
* Make sure that a node with a given ID is loaded, by traversing - and
* loading - its parents. This method is ment for lazy hierarchies.
* A callback is executed for every node as we go.
* @example
* tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
* if(status === "loaded") {
* console.log("loaded intermiediate node " + node);
* }else if(status === "ok") {
* node.activate();
* }
* });
*
* @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7')
* @param {function} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error')
* @returns {$.Promise}
*/
loadKeyPath: function(keyPathList, callback, _rootNode) {
var deferredList, dfd, i, path, key, loadMap, node, root, segList,
sep = this.options.keyPathSeparator,
self = this;
if(!$.isArray(keyPathList)){
keyPathList = [keyPathList];
}
// Pass 1: handle all path segments for nodes that are already loaded
// Collect distinct top-most lazy nodes in a map
loadMap = {};
for(i=0; i<keyPathList.length; i++){
root = _rootNode || this.rootNode;
path = keyPathList[i];
// strip leading slash
if(path.charAt(0) === sep){
path = path.substr(1);
}
// traverse and strip keys, until we hit a lazy, unloaded node
segList = path.split(sep);
while(segList.length){
key = segList.shift();
// node = _findDirectChild(root, key);
node = root._findDirectChild(key);
if(!node){
this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")");
callback.call(this, key, "error");
break;
}else if(segList.length === 0){
callback.call(this, node, "ok");
break;
}else if(!node.lazy || (node.hasChildren() !== undefined )){
callback.call(this, node, "loaded");
root = node;
}else{
callback.call(this, node, "loaded");
// segList.unshift(key);
if(loadMap[key]){
loadMap[key].push(segList.join(sep));
}else{
loadMap[key] = [segList.join(sep)];
}
break;
}
}
}
// alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap));
// Now load all lazy nodes and continue itearation for remaining paths
deferredList = [];
// Avoid jshint warning 'Don't make functions within a loop.':
function __lazyload(key, node, dfd){
callback.call(self, node, "loading");
node.load().done(function(){
self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self));
}).fail(function(errMsg){
self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")");
callback.call(self, node, "error");
dfd.reject();
});
}
for(key in loadMap){
node = root._findDirectChild(key);
// alert("loadKeyPath: lazy node(" + key + ") = " + node);
dfd = new $.Deferred();
deferredList.push(dfd);
__lazyload(key, node, dfd);
}
// Return a promise that is resovled, when ALL paths were loaded
return $.when.apply($, deferredList).promise();
},
/** Re-fire beforeActivate and activate events. */
reactivate: function(setFocus) {
var node = this.activeNode;
if( node ) {
this.activeNode = null; // Force re-activating
node.setActive();
if( setFocus ){
node.setFocus();
}
}
},
/** Reload tree from source and return a promise.
* @param [source] optional new source (defaults to initial source data)
* @returns {$.Promise}
*/
reload: function(source) {
this._callHook("treeClear", this);
return this._callHook("treeLoad", this, source);
},
/**Render tree (i.e. create DOM elements for all top-level nodes).
* @param {boolean} [force=false] create DOM elemnts, even is parent is collapsed
* @param {boolean} [deep=false]
*/
render: function(force, deep) {
return this.rootNode.render(force, deep);
},
// TODO: selectKey: function(key, select)
// TODO: serializeArray: function(stopOnParents)
/**
* @param {boolean} [flag=true]
*/
setFocus: function(flag) {
return this._callHook("treeSetFocus", this, flag);
},
/**
* Return all nodes as nested list of {@link NodeData}.
*
* @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children)
* @param {function} [callback(node)] Called for every node
* @returns {Array | object}
* @see FancytreeNode#toDict
*/
toDict: function(includeRoot, callback){
var res = this.rootNode.toDict(true, callback);
return includeRoot ? res : res.children;
},
/* Implicitly called for string conversions.
* @returns {string}
*/
toString: function(){
return "<Fancytree(#" + this._id + ")>";
},
/* _trigger a widget event with additional node ctx.
* @see EventData
*/
_triggerNodeEvent: function(type, node, originalEvent, extra) {
// this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx);
var ctx = this._makeHookContext(node, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if(res !== false && ctx.result !== undefined){
return ctx.result;
}
return res;
},
/* _trigger a widget event with additional tree data. */
_triggerTreeEvent: function(type, originalEvent, extra) {
// this.debug("_trigger(" + type + ")", ctx);
var ctx = this._makeHookContext(this, originalEvent, extra),
res = this.widget._trigger(type, originalEvent, ctx);
if(res !== false && ctx.result !== undefined){
return ctx.result;
}
return res;
},
/** Call fn(node) for all nodes.
*
* @param {function} fn the callback function.
* Return false to stop iteration, return "skip" to skip this node and children only.
* @returns {boolean} false, if the iterator was stopped.
*/
visit: function(fn) {
return this.rootNode.visit(fn, false);
},
/** Write warning to browser console (prepending tree info)
*
* @param {*} msg string or object or array of such
*/
warn: function(msg){
Array.prototype.unshift.call(arguments, this.toString());
consoleApply("warn", arguments);
}
};
/**
* These additional methods of the {@link Fancytree} class are 'hook functions'
* that can be used and overloaded by extensions.
* (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.)
* @mixin Fancytree_Hooks
*/
$.extend(Fancytree.prototype,
/** @lends Fancytree_Hooks# */
{
/** Default handling for mouse click events.
*
* @param {EventData} ctx
*/
nodeClick: function(ctx) {
// this.tree.logDebug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which);
var activate, expand,
// event = ctx.originalEvent,
targetType = ctx.targetType,
node = ctx.node;
// TODO: use switch
// TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample)
if( targetType === "expander" ) {
// Clicking the expander icon always expands/collapses
this._callHook("nodeToggleExpanded", ctx);
} else if( targetType === "checkbox" ) {
// Clicking the checkbox always (de)selects
this._callHook("nodeToggleSelected", ctx);
if( ctx.options.focusOnSelect ) { // #358
this._callHook("nodeSetFocus", ctx, true);
}
} else {
// Honor `clickFolderMode` for
expand = false;
activate = true;
if( node.folder ) {
switch( ctx.options.clickFolderMode ) {
case 2: // expand only
expand = true;
activate = false;
break;
case 3: // expand and activate
activate = true;
expand = true; //!node.isExpanded();
break;
// else 1 or 4: just activate
}
}
if( activate ) {
this.nodeSetFocus(ctx);
this._callHook("nodeSetActive", ctx, true);
}
if( expand ) {
if(!activate){
// this._callHook("nodeSetFocus", ctx);
}
// this._callHook("nodeSetExpanded", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
}
// Make sure that clicks stop, otherwise <a href='#'> jumps to the top
// if(event.target.localName === "a" && event.target.className === "fancytree-title"){
// event.preventDefault();
// }
// TODO: return promise?
},
/** Collapse all other children of same parent.
*
* @param {EventData} ctx
* @param {object} callOpts
*/
nodeCollapseSiblings: function(ctx, callOpts) {
// TODO: return promise?
var ac, i, l,
node = ctx.node;
if( node.parent ){
ac = node.parent.children;
for (i=0, l=ac.length; i<l; i++) {
if ( ac[i] !== node && ac[i].expanded ){
this._callHook("nodeSetExpanded", ac[i], false, callOpts);
}
}
}
},
/** Default handling for mouse douleclick events.
* @param {EventData} ctx
*/
nodeDblclick: function(ctx) {
// TODO: return promise?
if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) {
// this.nodeSetFocus(ctx);
// this._callHook("nodeSetActive", ctx, true);
this._callHook("nodeToggleExpanded", ctx);
}
// TODO: prevent text selection on dblclicks
if( ctx.targetType === "title" ) {
ctx.originalEvent.preventDefault();
}
},
/** Default handling for mouse keydown events.
*
* NOTE: this may be called with node == null if tree (but no node) has focus.
* @param {EventData} ctx
*/
nodeKeydown: function(ctx) {
// TODO: return promise?
var matchNode, stamp, res,
event = ctx.originalEvent,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
which = event.which,
whichChar = String.fromCharCode(which),
clean = !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey),
$target = $(event.target),
handled = true,
activate = !(event.ctrlKey || !opts.autoActivate ),
KC = $.ui.keyCode;
// node.debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
// Set focus to first node, if no other node has the focus yet
if( !node ){
this.getFirstChild().setFocus();
node = ctx.node = this.focusNode;
node.debug("Keydown force focus on first node");
}
if( opts.quicksearch && clean && /\w/.test(whichChar) && !$target.is(":input:enabled") ) {
// Allow to search for longer streaks if typed in quickly
stamp = new Date().getTime();
if( stamp - tree.lastQuicksearchTime > 500 ) {
tree.lastQuicksearchTerm = "";
}
tree.lastQuicksearchTime = stamp;
tree.lastQuicksearchTerm += whichChar;
// tree.debug("quicksearch find", tree.lastQuicksearchTerm);
matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode());
if( matchNode ) {
matchNode.setActive();
}
event.preventDefault();
return;
}
switch( which ) {
// charCodes:
case KC.NUMPAD_ADD: //107: // '+'
case 187: // '+' @ Chrome, Safari
tree.nodeSetExpanded(ctx, true);
break;
case KC.NUMPAD_SUBTRACT: // '-'
case 189: // '-' @ Chrome, Safari
tree.nodeSetExpanded(ctx, false);
break;
case KC.SPACE:
if(opts.checkbox){
tree.nodeToggleSelected(ctx);
}else{
tree.nodeSetActive(ctx, true);
}
break;
case KC.ENTER:
tree.nodeSetActive(ctx, true);
break;
case KC.BACKSPACE:
case KC.LEFT:
case KC.RIGHT:
case KC.UP:
case KC.DOWN:
res = node.navigate(event.which, activate);
break;
default:
handled = false;
}
if(handled){
event.preventDefault();
}
},
// /** Default handling for mouse keypress events. */
// nodeKeypress: function(ctx) {
// var event = ctx.originalEvent;
// },
// /** Trigger lazyLoad event (async). */
// nodeLazyLoad: function(ctx) {
// var node = ctx.node;
// if(this._triggerNodeEvent())
// },
/** Load child nodes (async).
*
* @param {EventData} ctx
* @param {object[]|object|string|$.Promise|function} source
* @returns {$.Promise} The deferred will be resolved as soon as the (ajax)
* data was rendered.
*/
nodeLoadChildren: function(ctx, source) {
var ajax, delay, dfd,
tree = ctx.tree,
node = ctx.node;
if($.isFunction(source)){
source = source();
}
// TOTHINK: move to 'ajax' extension?
if(source.url){
// `source` is an Ajax options object
ajax = $.extend({}, ctx.options.ajax, source);
if(ajax.debugDelay){
// simulate a slow server
delay = ajax.debugDelay;
if($.isArray(delay)){ // random delay range [min..max]
delay = delay[0] + Math.random() * (delay[1] - delay[0]);
}
node.debug("nodeLoadChildren waiting debug delay " + Math.round(delay) + "ms");
ajax.debugDelay = false;
dfd = $.Deferred(function (dfd) {
setTimeout(function () {
$.ajax(ajax)
.done(function () { dfd.resolveWith(this, arguments); })
.fail(function () { dfd.rejectWith(this, arguments); });
}, delay);
});
}else{
dfd = $.ajax(ajax);
}
// Defer the deferred: we want to be able to reject, even if ajax
// resolved ok.
source = new $.Deferred();
dfd.done(function (data, textStatus, jqXHR) {
var errorObj, res;
if(typeof data === "string"){
$.error("Ajax request returned a string (did you get the JSON dataType wrong?).");
}
// postProcess is similar to the standard ajax dataFilter hook,
// but it is also called for JSONP
if( ctx.options.postProcess ){
res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {response: data, error: null, dataType: this.dataType});
if( res.error ) {
errorObj = $.isPlainObject(res.error) ? res.error : {message: res.error};
errorObj = tree._makeHookContext(node, null, errorObj);
source.rejectWith(this, [errorObj]);
return;
}
data = $.isArray(res) ? res : data;
} else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) {
// Process ASPX WebMethod JSON object inside "d" property
data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d;
}
source.resolveWith(this, [data]);
}).fail(function (jqXHR, textStatus, errorThrown) {
var errorObj = tree._makeHookContext(node, null, {
error: jqXHR,
args: Array.prototype.slice.call(arguments),
message: errorThrown,
details: jqXHR.status + ": " + errorThrown
});
source.rejectWith(this, [errorObj]);
});
}
if($.isFunction(source.promise)){
// `source` is a deferred, i.e. ajax request
_assert(!node.isLoading());
// node._isLoading = true;
tree.nodeSetStatus(ctx, "loading");
source.done(function (children) {
tree.nodeSetStatus(ctx, "ok");
}).fail(function(error){
var ctxErr;
if (error.node && error.error && error.message) {
// error is already a context object
ctxErr = error;
} else {
ctxErr = tree._makeHookContext(node, null, {
error: error, // it can be jqXHR or any custom error
args: Array.prototype.slice.call(arguments),
message: error ? (error.message || error.toString()) : ""
});
}
if( tree._triggerNodeEvent("loadError", ctxErr, null) !== false ) {
tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details);
}
});
}
// $.when(source) resolves also for non-deferreds
return $.when(source).done(function(children){
var metaData;
if( $.isPlainObject(children) ){
// We got {foo: 'abc', children: [...]}
// Copy extra properties to tree.data.foo
_assert($.isArray(children.children), "source must contain (or be) an array of children");
_assert(node.isRoot(), "source may only be an object for root nodes");
metaData = children;
children = children.children;
delete metaData.children;
$.extend(tree.data, metaData);
}
_assert($.isArray(children), "expected array of children");
node._setChildren(children);
// trigger fancytreeloadchildren
tree._triggerNodeEvent("loadChildren", node);
// }).always(function(){
// node._isLoading = false;
});
},
/** [Not Implemented] */
nodeLoadKeyPath: function(ctx, keyPathList) {
// TODO: implement and improve
// http://code.google.com/p/dynatree/issues/detail?id=222
},
/**
* Remove a single direct child of ctx.node.
* @param {EventData} ctx
* @param {FancytreeNode} childNode dircect child of ctx.node
*/
nodeRemoveChild: function(ctx, childNode) {
var idx,
node = ctx.node,
opts = ctx.options,
subCtx = $.extend({}, ctx, {node: childNode}),
children = node.children;
// FT.debug("nodeRemoveChild()", node.toString(), childNode.toString());
if( children.length === 1 ) {
_assert(childNode === children[0]);
return this.nodeRemoveChildren(ctx);
}
if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){
this.activeNode.setActive(false); // TODO: don't fire events
}
if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveMarkup(subCtx);
this.nodeRemoveChildren(subCtx);
idx = $.inArray(childNode, children);
_assert(idx >= 0);
// Unlink to support GC
childNode.visit(function(n){
n.parent = null;
}, true);
this._callHook("treeRegisterNode", this, false, childNode);
if ( opts.removeNode ){
opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
}
// remove from child list
children.splice(idx, 1);
},
/**Remove HTML markup for all descendents of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveChildMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if(node.ul){
if( node.isRoot() ) {
$(node.ul).empty();
} else {
$(node.ul).remove();
node.ul = null;
}
node.visit(function(n){
n.li = n.ul = null;
});
}
},
/**Remove all descendants of ctx.node.
* @param {EventData} ctx
*/
nodeRemoveChildren: function(ctx) {
var subCtx,
tree = ctx.tree,
node = ctx.node,
children = node.children,
opts = ctx.options;
// FT.debug("nodeRemoveChildren()", node.toString());
if(!children){
return;
}
if( this.activeNode && this.activeNode.isDescendantOf(node)){
this.activeNode.setActive(false); // TODO: don't fire events
}
if( this.focusNode && this.focusNode.isDescendantOf(node)){
this.focusNode = null;
}
// TODO: persist must take care to clear select and expand cookies
this.nodeRemoveChildMarkup(ctx);
// Unlink children to support GC
// TODO: also delete this.children (not possible using visit())
subCtx = $.extend({}, ctx);
node.visit(function(n){
n.parent = null;
tree._callHook("treeRegisterNode", tree, false, n);
if ( opts.removeNode ){
subCtx.node = n;
opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
}
});
if( node.lazy ){
// 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
node.children = [];
} else{
node.children = null;
}
this.nodeRenderStatus(ctx);
},
/**Remove HTML markup for ctx.node and all its descendents.
* @param {EventData} ctx
*/
nodeRemoveMarkup: function(ctx) {
var node = ctx.node;
// FT.debug("nodeRemoveMarkup()", node.toString());
// TODO: Unlink attr.ftnode to support GC
if(node.li){
$(node.li).remove();
node.li = null;
}
this.nodeRemoveChildMarkup(ctx);
},
/**
* Create `<li><span>..</span> .. </li>` tags for this node.
*
* This method takes care that all HTML markup is created that is required
* to display this node in it's current state.
*
* Call this method to create new nodes, or after the strucuture
* was changed (e.g. after moving this node or adding/removing children)
* nodeRenderTitle() and nodeRenderStatus() are implied.
*
* Note: if a node was created/removed, nodeRender() must be called for the
* parent.
* <code>
* <li id='KEY' ftnode=NODE>
* <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'>
* <span class="fancytree-expander"></span>
* <span class="fancytree-checkbox"></span> // only present in checkbox mode
* <span class="fancytree-icon"></span>
* <a href="#" class="fancytree-title"> Node 1 </a>
* </span>
* <ul> // only present if node has children
* <li id='KEY' ftnode=NODE> child1 ... </li>
* <li id='KEY' ftnode=NODE> child2 ... </li>
* </ul>
* </li>
* </code>
*
* @param {EventData} ctx
* @param {boolean} [force=false] re-render, even if html markup was already created
* @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
* @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later
*/
nodeRender: function(ctx, force, deep, collapsed, _recursive) {
/* This method must take care of all cases where the current data mode
* (i.e. node hierarchy) does not match the current markup.
*
* - node was not yet rendered:
* create markup
* - node was rendered: exit fast
* - children have been added
* - childern have been removed
*/
var childLI, childNode1, childNode2, i, l, next, subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
firstTime = false,
parent = node.parent,
isRootNode = !parent,
children = node.children;
// FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString());
if( ! isRootNode && ! parent.ul ) {
// Calling node.collapse on a deep, unrendered node
return;
}
_assert(isRootNode || parent.ul, "parent UL must exist");
// if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){
// if(node.li.parentNode !== node.parent.ul){
// // alert("unlink " + node + " (must be child of " + node.parent + ")");
// this.warn("unlink " + node + " (must be child of " + node.parent + ")");
// }
// // this.debug("nodeRemoveMarkup...");
// this.nodeRemoveMarkup(ctx);
// }
// Render the node
if( !isRootNode ){
// Discard markup on force-mode, or if it is not linked to parent <ul>
if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){
if(node.li.parentNode !== node.parent.ul){
// alert("unlink " + node + " (must be child of " + node.parent + ")");
this.warn("unlink " + node + " (must be child of " + node.parent + ")");
}
// this.debug("nodeRemoveMarkup...");
this.nodeRemoveMarkup(ctx);
}
// Create <li><span /> </li>
// node.debug("render...");
if( !node.li ) {
// node.debug("render... really");
firstTime = true;
node.li = document.createElement("li");
node.li.ftnode = node;
if(aria){
// TODO: why doesn't this work:
// node.li.role = "treeitem";
// $(node.li).attr("role", "treeitem")
// .attr("aria-labelledby", "ftal_" + node.key);
}
if( node.key && opts.generateIds ){
node.li.id = opts.idPrefix + node.key;
}
node.span = document.createElement("span");
node.span.className = "fancytree-node";
if(aria){
$(node.span).attr("aria-labelledby", "ftal_" + node.key);
}
node.li.appendChild(node.span);
// Create inner HTML for the <span> (expander, checkbox, icon, and title)
this.nodeRenderTitle(ctx);
// Allow tweaking and binding, after node was created for the first time
if ( opts.createNode ){
opts.createNode.call(tree, {type: "createNode"}, ctx);
}
}else{
// this.nodeRenderTitle(ctx);
this.nodeRenderStatus(ctx);
}
// Allow tweaking after node state was rendered
if ( opts.renderNode ){
opts.renderNode.call(tree, {type: "renderNode"}, ctx);
}
}
// Visit child nodes
if( children ){
if( isRootNode || node.expanded || deep === true ) {
// Create a UL to hold the children
if( !node.ul ){
node.ul = document.createElement("ul");
if((collapsed === true && !_recursive) || !node.expanded){
// hide top UL, so we can use an animation to show it later
node.ul.style.display = "none";
}
if(aria){
$(node.ul).attr("role", "group");
}
if ( node.li ) { // issue #67
node.li.appendChild(node.ul);
} else {
node.tree.$div.append(node.ul);
}
}
// Add child markup
for(i=0, l=children.length; i<l; i++) {
subCtx = $.extend({}, ctx, {node: children[i]});
this.nodeRender(subCtx, force, deep, false, true);
}
// Remove <li> if nodes have moved to another parent
childLI = node.ul.firstChild;
while( childLI ){
childNode2 = childLI.ftnode;
if( childNode2 && childNode2.parent !== node ) {
node.debug("_fixParent: remove missing " + childNode2, childLI);
next = childLI.nextSibling;
childLI.parentNode.removeChild(childLI);
childLI = next;
}else{
childLI = childLI.nextSibling;
}
}
// Make sure, that <li> order matches node.children order.
childLI = node.ul.firstChild;
for(i=0, l=children.length-1; i<l; i++) {
childNode1 = children[i];
childNode2 = childLI.ftnode;
if( childNode1 !== childNode2 ) {
// node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
node.ul.insertBefore(childNode1.li, childNode2.li);
} else {
childLI = childLI.nextSibling;
}
}
}
}else{
// No children: remove markup if any
if( node.ul ){
// alert("remove child markup for " + node);
this.warn("remove child markup for " + node);
this.nodeRemoveChildMarkup(ctx);
}
}
if( !isRootNode ){
// Update element classes according to node state
// this.nodeRenderStatus(ctx);
// Finally add the whole structure to the DOM, so the browser can render
if(firstTime){
parent.ul.appendChild(node.li);
}
}
},
/** Create HTML for the node's outer <span> (expander, checkbox, icon, and title).
*
* nodeRenderStatus() is implied.
* @param {EventData} ctx
* @param {string} [title] optinal new title
*/
nodeRenderTitle: function(ctx, title) {
// set node connector images, links and text
var id, iconSpanClass, nodeTitle, role, tabindex, tooltip,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
aria = opts.aria,
level = node.getLevel(),
ares = [],
iconSrc = node.data.icon;
if(title !== undefined){
node.title = title;
}
if(!node.span){
// Silently bail out if node was not rendered yet, assuming
// node.render() will be called as the node becomes visible
return;
}
// connector (expanded, expandable or simple)
// TODO: optimize this if clause
if( level < opts.minExpandLevel ) {
if( !node.lazy ) {
node.expanded = true;
}
if(level > 1){
if(aria){
ares.push("<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>");
}else{
ares.push("<span class='fancytree-expander fancytree-expander-fixed''></span>");
}
}
// .. else (i.e. for root level) skip expander/connector alltogether
} else {
if(aria){
ares.push("<span role='button' class='fancytree-expander'></span>");
}else{
ares.push("<span class='fancytree-expander'></span>");
}
}
// Checkbox mode
if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) {
if(aria){
ares.push("<span role='checkbox' class='fancytree-checkbox'></span>");
}else{
ares.push("<span class='fancytree-checkbox'></span>");
}
}
// folder or doctype icon
role = aria ? " role='img'" : "";
if( iconSrc === true || (iconSrc !== false && opts.icons !== false) ) {
// opts.icons defines the default behavior, node.icon == true/false can override this
if ( iconSrc && typeof iconSrc === "string" ) {
// node.icon is an image url
iconSrc = (iconSrc.charAt(0) === "/") ? iconSrc : ((opts.imagePath || "") + iconSrc);
ares.push("<img src='" + iconSrc + "' class='fancytree-icon' alt='' />");
} else {
// See if node.iconClass or opts.iconClass() define a class name
iconSpanClass = (opts.iconClass && opts.iconClass.call(tree, node, ctx)) || node.data.iconclass || null;
if( iconSpanClass ) {
ares.push("<span " + role + " class='fancytree-custom-icon " + iconSpanClass + "'></span>");
} else {
ares.push("<span " + role + " class='fancytree-icon'></span>");
}
}
}
// node title
nodeTitle = "";
if ( opts.renderTitle ){
nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || "";
}
if(!nodeTitle){
tooltip = node.tooltip ? " title='" + FT.escapeHtml(node.tooltip) + "'" : "";
id = aria ? " id='ftal_" + node.key + "'" : "";
role = aria ? " role='treeitem'" : "";
tabindex = opts.titlesTabbable ? " tabindex='0'" : "";
nodeTitle = "<span " + role + " class='fancytree-title'" + id + tooltip + tabindex + ">" + node.title + "</span>";
}
ares.push(nodeTitle);
// Note: this will trigger focusout, if node had the focus
//$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly
node.span.innerHTML = ares.join("");
// Update CSS classes
this.nodeRenderStatus(ctx);
},
/** Update element classes according to node state.
* @param {EventData} ctx
*/
nodeRenderStatus: function(ctx) {
// Set classes for current status
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
// nodeContainer = node[tree.nodeContainerAttrName],
hasChildren = node.hasChildren(),
isLastSib = node.isLastSibling(),
aria = opts.aria,
// $ariaElem = aria ? $(node[tree.ariaPropName]) : null,
$ariaElem = $(node.span).find(".fancytree-title"),
cn = opts._classNames,
cnList = [],
statusElem = node[tree.statusClassPropName];
if( !statusElem ){
// if this function is called for an unrendered node, ignore it (will be updated on nect render anyway)
return;
}
// Build a list of class names that we will add to the node <span>
cnList.push(cn.node);
if( tree.activeNode === node ){
cnList.push(cn.active);
// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
// tree.$container.removeAttr("tabindex");
// }else{
// $(">span.fancytree-title", statusElem).removeAttr("tabindex");
// tree.$container.attr("tabindex", "0");
}
if( tree.focusNode === node ){
cnList.push(cn.focused);
if(aria){
// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
// TODO: is this the right element for this attribute?
$ariaElem
.attr("aria-activedescendant", true);
// .attr("tabindex", "-1");
}
}else if(aria){
// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
$ariaElem
.removeAttr("aria-activedescendant");
// .removeAttr("tabindex");
}
if( node.expanded ){
cnList.push(cn.expanded);
if(aria){
$ariaElem.attr("aria-expanded", true);
}
}else if(aria){
$ariaElem.removeAttr("aria-expanded");
}
if( node.folder ){
cnList.push(cn.folder);
}
if( hasChildren !== false ){
cnList.push(cn.hasChildren);
}
// TODO: required?
if( isLastSib ){
cnList.push(cn.lastsib);
}
if( node.lazy && node.children == null ){
cnList.push(cn.lazy);
}
if( node.partsel ){
cnList.push(cn.partsel);
}
if( node.unselectable ){
cnList.push(cn.unselectable);
}
if( node._isLoading ){
cnList.push(cn.loading);
}
if( node._error ){
cnList.push(cn.error);
}
if( node.selected ){
cnList.push(cn.selected);
if(aria){
$ariaElem.attr("aria-selected", true);
}
}else if(aria){
$ariaElem.attr("aria-selected", false);
}
if( node.extraClasses ){
cnList.push(node.extraClasses);
}
// IE6 doesn't correctly evaluate multiple class names,
// so we create combined class names that can be used in the CSS
if( hasChildren === false ){
cnList.push(cn.combinedExpanderPrefix + "n" +
(isLastSib ? "l" : "")
);
}else{
cnList.push(cn.combinedExpanderPrefix +
(node.expanded ? "e" : "c") +
(node.lazy && node.children == null ? "d" : "") +
(isLastSib ? "l" : "")
);
}
cnList.push(cn.combinedIconPrefix +
(node.expanded ? "e" : "c") +
(node.folder ? "f" : "")
);
// node.span.className = cnList.join(" ");
statusElem.className = cnList.join(" ");
// TODO: we should not set this in the <span> tag also, if we set it here:
// Maybe most (all) of the classes should be set in LI instead of SPAN?
if(node.li){
node.li.className = isLastSib ? cn.lastsib : "";
}
},
/** Activate node.
* flag defaults to true.
* If flag is true, the node is activated (must be a synchronous operation)
* If flag is false, the node is deactivated (must be a synchronous operation)
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noEvents: false}
*/
nodeSetActive: function(ctx, flag, callOpts) {
// Handle user click / [space] / [enter], according to clickFolderMode.
callOpts = callOpts || {};
var subCtx,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noEvents = (callOpts.noEvents === true),
isActive = (node === tree.activeNode);
// flag defaults to true
flag = (flag !== false);
// node.debug("nodeSetActive", flag);
if(isActive === flag){
// Nothing to do
return _getResolvedPromise(node);
}else if(flag && !noEvents && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
if(flag){
if(tree.activeNode){
_assert(tree.activeNode !== node, "node was active (inconsistency)");
subCtx = $.extend({}, ctx, {node: tree.activeNode});
tree.nodeSetActive(subCtx, false);
_assert(tree.activeNode === null, "deactivate was out of sync?");
}
if(opts.activeVisible){
// tree.nodeMakeVisible(ctx);
node.makeVisible({scrollIntoView: false}); // nodeSetFocus will scroll
}
tree.activeNode = node;
tree.nodeRenderStatus(ctx);
tree.nodeSetFocus(ctx);
if( !noEvents ) {
tree._triggerNodeEvent("activate", node, ctx.originalEvent);
}
}else{
_assert(tree.activeNode === node, "node was not active (inconsistency)");
tree.activeNode = null;
this.nodeRenderStatus(ctx);
if( !noEvents ) {
ctx.tree._triggerNodeEvent("deactivate", node, ctx.originalEvent);
}
}
},
/** Expand or collapse node, return Deferred.promise.
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
* @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
* @returns {$.Promise} The deferred will be resolved as soon as the (lazy)
* data was retrieved, rendered, and the expand animation finshed.
*/
nodeSetExpanded: function(ctx, flag, callOpts) {
callOpts = callOpts || {};
var _afterLoad, dfd, i, l, parents, prevAC,
node = ctx.node,
tree = ctx.tree,
opts = ctx.options,
noAnimation = (callOpts.noAnimation === true),
noEvents = (callOpts.noEvents === true);
// flag defaults to true
flag = (flag !== false);
// node.debug("nodeSetExpanded(" + flag + ")");
if((node.expanded && flag) || (!node.expanded && !flag)){
// Nothing to do
// node.debug("nodeSetExpanded(" + flag + "): nothing to do");
return _getResolvedPromise(node);
}else if(flag && !node.lazy && !node.hasChildren() ){
// Prevent expanding of empty nodes
// return _getRejectedPromise(node, ["empty"]);
return _getResolvedPromise(node);
}else if( !flag && node.getLevel() < opts.minExpandLevel ) {
// Prevent collapsing locked levels
return _getRejectedPromise(node, ["locked"]);
}else if ( !noEvents && this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){
// Callback returned false
return _getRejectedPromise(node, ["rejected"]);
}
// If this node inside a collpased node, no animation and scrolling is needed
if( !noAnimation && !node.isVisible() ) {
noAnimation = callOpts.noAnimation = true;
}
dfd = new $.Deferred();
// Auto-collapse mode: collapse all siblings
if( flag && !node.expanded && opts.autoCollapse ) {
parents = node.getParentList(false, true);
prevAC = opts.autoCollapse;
try{
opts.autoCollapse = false;
for(i=0, l=parents.length; i<l; i++){
// TODO: should return promise?
this._callHook("nodeCollapseSiblings", parents[i], callOpts);
}
}finally{
opts.autoCollapse = prevAC;
}
}
// Trigger expand/collapse after expanding
dfd.done(function(){
if( flag && opts.autoScroll && !noAnimation ) {
// Scroll down to last child, but keep current node visible
node.getLastChild().scrollIntoView(true, {topNode: node}).always(function(){
if( !noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
});
} else {
if( !noEvents ) {
ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
}
}
});
// vvv Code below is executed after loading finished:
_afterLoad = function(callback){
var duration, easing, isVisible, isExpanded;
node.expanded = flag;
// Create required markup, but make sure the top UL is hidden, so we
// can animate later
tree._callHook("nodeRender", ctx, false, false, true);
// If the currently active node is now hidden, deactivate it
// if( opts.activeVisible && this.activeNode && ! this.activeNode.isVisible() ) {
// this.activeNode.deactivate();
// }
// Expanding a lazy node: set 'loading...' and call callback
// if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) {
// this._loadContent();
// return;
// }
// Hide children, if node is collapsed
if( node.ul ) {
isVisible = (node.ul.style.display !== "none");
isExpanded = !!node.expanded;
if ( isVisible === isExpanded ) {
node.warn("nodeSetExpanded: UL.style.display already set");
} else if ( !opts.fx || noAnimation ) {
node.ul.style.display = ( node.expanded || !parent ) ? "" : "none";
} else {
duration = opts.fx.duration || 200;
easing = opts.fx.easing;
// node.debug("nodeSetExpanded: animate start...");
$(node.ul).animate(opts.fx, duration, easing, function(){
// node.debug("nodeSetExpanded: animate done");
callback();
});
return;
}
}
callback();
};
// ^^^ Code above is executed after loading finshed.
// Load lazy nodes, if any. Then continue with _afterLoad()
if(flag && node.lazy && node.hasChildren() === undefined){
// node.debug("nodeSetExpanded: load start...");
node.load().done(function(){
// node.debug("nodeSetExpanded: load done");
if(dfd.notifyWith){ // requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad(function () { dfd.resolveWith(node); });
}).fail(function(errMsg){
_afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); });
});
/*
var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent);
_assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
node.debug("nodeSetExpanded: load start...");
this._callHook("nodeLoadChildren", ctx, source).done(function(){
node.debug("nodeSetExpanded: load done");
if(dfd.notifyWith){ // requires jQuery 1.6+
dfd.notifyWith(node, ["loaded"]);
}
_afterLoad.call(tree);
}).fail(function(errMsg){
dfd.rejectWith(node, ["load failed (" + errMsg + ")"]);
});
*/
}else{
_afterLoad(function () { dfd.resolveWith(node); });
}
// node.debug("nodeSetExpanded: returns");
return dfd.promise();
},
/** Focus ot blur this node.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetFocus: function(ctx, flag) {
// ctx.node.debug("nodeSetFocus(" + flag + ")");
var ctx2,
tree = ctx.tree,
node = ctx.node;
flag = (flag !== false);
// Blur previous node if any
if(tree.focusNode){
if(tree.focusNode === node && flag){
// node.debug("nodeSetFocus(" + flag + "): nothing to do");
return;
}
ctx2 = $.extend({}, ctx, {node: tree.focusNode});
tree.focusNode = null;
this._triggerNodeEvent("blur", ctx2);
this._callHook("nodeRenderStatus", ctx2);
}
// Set focus to container and node
if(flag){
if( !this.hasFocus() ){
node.debug("nodeSetFocus: forcing container focus");
// Note: we pass _calledByNodeSetFocus=true
this._callHook("treeSetFocus", ctx, true, true);
}
// this.nodeMakeVisible(ctx);
node.makeVisible({scrollIntoView: false});
tree.focusNode = node;
// node.debug("FOCUS...");
// $(node.span).find(".fancytree-title").focus();
this._triggerNodeEvent("focus", ctx);
// if(ctx.options.autoActivate){
// tree.nodeSetActive(ctx, true);
// }
if(ctx.options.autoScroll){
node.scrollIntoView();
}
this._callHook("nodeRenderStatus", ctx);
}
},
/** (De)Select node, return new status (sync).
*
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
nodeSetSelected: function(ctx, flag) {
var node = ctx.node,
tree = ctx.tree,
opts = ctx.options;
// flag defaults to true
flag = (flag !== false);
node.debug("nodeSetSelected(" + flag + ")", ctx);
if( node.unselectable){
return;
}
// TODO: !!node.expanded is nicer, but doesn't pass jshint
// https://github.com/jshint/jshint/issues/455
// if( !!node.expanded === !!flag){
if((node.selected && flag) || (!node.selected && !flag)){
return !!node.selected;
}else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){
return !!node.selected;
}
if(flag && opts.selectMode === 1){
// single selection mode
if(tree.lastSelectedNode){
tree.lastSelectedNode.setSelected(false);
}
}else if(opts.selectMode === 3){
// multi.hier selection mode
node.selected = flag;
// this._fixSelectionState(node);
node.fixSelection3AfterClick();
}
node.selected = flag;
this.nodeRenderStatus(ctx);
tree.lastSelectedNode = flag ? node : null;
tree._triggerNodeEvent("select", ctx);
},
/** Show node status (ok, loading, error) using styles and a dummy child node.
*
* @param {EventData} ctx
* @param status
* @param message
* @param details
*/
nodeSetStatus: function(ctx, status, message, details) {
var node = ctx.node,
tree = ctx.tree;
// cn = ctx.options._classNames;
function _clearStatusNode() {
// Remove dedicated dummy node, if any
var firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
try{
// I've seen exceptions here with loadKeyPath...
if(node.ul){
node.ul.removeChild(firstChild.li);
firstChild.li = null; // avoid leaks (DT issue 215)
}
}catch(e){}
if( node.children.length === 1 ){
node.children = [];
}else{
node.children.shift();
}
}
}
function _setStatusNode(data, type) {
// Create/modify the dedicated dummy node for 'loading...' or
// 'error!' status. (only called for direct child of the invisible
// system root)
var firstChild = ( node.children ? node.children[0] : null );
if ( firstChild && firstChild.isStatusNode() ) {
$.extend(firstChild, data);
// tree._callHook("nodeRender", firstChild);
tree._callHook("nodeRenderTitle", firstChild);
} else {
data.key = "_statusNode";
node._setChildren([data]);
node.children[0].statusNodeType = type;
tree.render();
}
return node.children[0];
}
switch( status ){
case "ok":
_clearStatusNode();
// $(node.span).removeClass(cn.loading).removeClass(cn.error);
node._isLoading = false;
node._error = null;
node.renderStatus();
break;
case "loading":
// $(node.span).removeClass(cn.error).addClass(cn.loading);
if( !node.parent ) {
_setStatusNode({
title: tree.options.strings.loading + (message ? " (" + message + ") " : ""),
tooltip: details,
extraClasses: "fancytree-statusnode-wait"
}, status);
}
node._isLoading = true;
node._error = null;
node.renderStatus();
break;
case "error":
// $(node.span).removeClass(cn.loading).addClass(cn.error);
_setStatusNode({
title: tree.options.strings.loadError + (message ? " (" + message + ") " : ""),
tooltip: details,
extraClasses: "fancytree-statusnode-error"
}, status);
node._isLoading = false;
node._error = { message: message, details: details };
node.renderStatus();
break;
default:
$.error("invalid node status " + status);
}
},
/**
*
* @param {EventData} ctx
*/
nodeToggleExpanded: function(ctx) {
return this.nodeSetExpanded(ctx, !ctx.node.expanded);
},
/**
* @param {EventData} ctx
*/
nodeToggleSelected: function(ctx) {
return this.nodeSetSelected(ctx, !ctx.node.selected);
},
/** Remove all nodes.
* @param {EventData} ctx
*/
treeClear: function(ctx) {
var tree = ctx.tree;
tree.activeNode = null;
tree.focusNode = null;
tree.$div.find(">ul.fancytree-container").empty();
// TODO: call destructors and remove reference loops
tree.rootNode.children = null;
},
/** Widget was created (called only once, even it re-initialized).
* @param {EventData} ctx
*/
treeCreate: function(ctx) {
},
/** Widget was destroyed.
* @param {EventData} ctx
*/
treeDestroy: function(ctx) {
},
/** Widget was (re-)initialized.
* @param {EventData} ctx
*/
treeInit: function(ctx) {
//this.debug("Fancytree.treeInit()");
this.treeLoad(ctx);
},
/** Parse Fancytree from source, as configured in the options.
* @param {EventData} ctx
* @param {object} [source] optional new source (use last data otherwise)
*/
treeLoad: function(ctx, source) {
var type, $ul,
tree = ctx.tree,
$container = ctx.widget.element,
dfd,
// calling context for root node
rootCtx = $.extend({}, ctx, {node: this.rootNode});
if(tree.rootNode.children){
this.treeClear(ctx);
}
source = source || this.options.source;
if(!source){
type = $container.data("type") || "html";
switch(type){
case "html":
$ul = $container.find(">ul:first");
$ul.addClass("ui-fancytree-source ui-helper-hidden");
source = $.ui.fancytree.parseHtml($ul);
// allow to init tree.data.foo from <ul data-foo=''>
this.data = $.extend(this.data, _getElementDataAsDict($ul));
break;
case "json":
// $().addClass("ui-helper-hidden");
source = $.parseJSON($container.text());
if(source.children){
if(source.title){tree.title = source.title;}
source = source.children;
}
break;
default:
$.error("Invalid data-type: " + type);
}
}else if(typeof source === "string"){
// TODO: source is an element ID
$.error("Not implemented");
}
// $container.addClass("ui-widget ui-widget-content ui-corner-all");
// Trigger fancytreeinit after nodes have been loaded
dfd = this.nodeLoadChildren(rootCtx, source).done(function(){
tree.render();
if( ctx.options.selectMode === 3 ){
tree.rootNode.fixSelection3FromEndNodes();
}
tree._triggerTreeEvent("init", null, { status: true });
}).fail(function(){
tree.render();
tree._triggerTreeEvent("init", null, { status: false });
});
return dfd;
},
/** Node was inserted into or removed from the tree.
* @param {EventData} ctx
* @param {boolean} add
* @param {FancytreeNode} node
*/
treeRegisterNode: function(ctx, add, node) {
},
/** Widget got focus.
* @param {EventData} ctx
* @param {boolean} [flag=true]
*/
treeSetFocus: function(ctx, flag, _calledByNodeSetFocus) {
flag = (flag !== false);
// this.debug("treeSetFocus(" + flag + "), _calledByNodeSetFocus: " + _calledByNodeSetFocus);
// this.debug(" focusNode: " + this.focusNode);
// this.debug(" activeNode: " + this.activeNode);
if( flag !== this.hasFocus() ){
this._hasFocus = flag;
this.$container.toggleClass("fancytree-treefocus", flag);
this._triggerTreeEvent(flag ? "focusTree" : "blurTree");
}
}
});
/* ******************************************************************************
* jQuery UI widget boilerplate
*/
/**
* The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br>
* This constructor is not called directly. Use `$(selector).fancytree({})`
* to initialize the plugin instead.<br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members:
* var tree = $("#tree").fancytree("getTree");
* var node = $("#tree").fancytree("getActiveNode", "1234");
* </pre>
*
* @mixin Fancytree_Widget
*/
$.widget("ui.fancytree",
/** @lends Fancytree_Widget# */
{
/**These options will be used as defaults
* @type {FancytreeOptions}
*/
options:
{
activeVisible: true,
ajax: {
type: "GET",
cache: false, // false: Append random '_' argument to the request url to prevent caching.
// timeout: 0, // >0: Make sure we get an ajax error if server is unreachable
dataType: "json" // Expect json format and pass json object to callbacks.
}, //
aria: false, // TODO: default to true
autoActivate: true,
autoCollapse: false,
// autoFocus: false,
autoScroll: false,
checkbox: false,
/**defines click behavior*/
clickFolderMode: 4,
debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo)
disabled: false, // TODO: required anymore?
enableAspx: true, // TODO: document
extensions: [],
fx: { height: "toggle", duration: 200 },
generateIds: false,
icons: true,
idPrefix: "ft_",
focusOnSelect: false,
keyboard: true,
keyPathSeparator: "/",
minExpandLevel: 1,
quicksearch: false,
scrollOfs: {top: 0, bottom: 0},
scrollParent: null,
selectMode: 2,
strings: {
loading: "Loading…",
loadError: "Load error!"
},
tabbable: true,
titlesTabbable: false,
_classNames: {
node: "fancytree-node",
folder: "fancytree-folder",
combinedExpanderPrefix: "fancytree-exp-",
combinedIconPrefix: "fancytree-ico-",
hasChildren: "fancytree-has-children",
active: "fancytree-active",
selected: "fancytree-selected",
expanded: "fancytree-expanded",
lazy: "fancytree-lazy",
focused: "fancytree-focused",
partsel: "fancytree-partsel",
unselectable: "fancytree-unselectable",
lastsib: "fancytree-lastsib",
loading: "fancytree-loading",
error: "fancytree-error"
},
// events
lazyLoad: null,
postProcess: null
},
/* Set up the widget, Called on first $().fancytree() */
_create: function() {
this.tree = new Fancytree(this);
this.$source = this.source || this.element.data("type") === "json" ? this.element
: this.element.find(">ul:first");
// Subclass Fancytree instance with all enabled extensions
var extension, extName, i,
extensions = this.options.extensions,
base = this.tree;
for(i=0; i<extensions.length; i++){
extName = extensions[i];
extension = $.ui.fancytree._extensions[extName];
if(!extension){
$.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)");
}
// Add extension options as tree.options.EXTENSION
// _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName);
this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]);
// Add a namespace tree.ext.EXTENSION, to hold instance data
_assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'");
// this.tree[extName] = extension;
this.tree.ext[extName] = {};
// Subclass Fancytree methods using proxies.
_subclassObject(this.tree, base, extension, extName);
// current extension becomes base for the next extension
base = extension;
}
//
this.tree._callHook("treeCreate", this.tree);
// Note: 'fancytreecreate' event is fired by widget base class
// this.tree._triggerTreeEvent("create");
},
/* Called on every $().fancytree() */
_init: function() {
this.tree._callHook("treeInit", this.tree);
// TODO: currently we call bind after treeInit, because treeInit
// might change tree.$container.
// It would be better, to move ebent binding into hooks altogether
this._bind();
},
/* Use the _setOption method to respond to changes to options */
_setOption: function(key, value) {
var callDefault = true,
rerender = false;
switch( key ) {
case "aria":
case "checkbox":
case "icons":
case "minExpandLevel":
case "tabbable":
// case "nolink":
this.tree._callHook("treeCreate", this.tree);
rerender = true;
break;
case "source":
callDefault = false;
this.tree._callHook("treeLoad", this.tree, value);
break;
}
this.tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">");
if(callDefault){
// In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget
$.Widget.prototype._setOption.apply(this, arguments);
// TODO: In jQuery UI 1.9 and above, you use the _super method instead
// this._super( "_setOption", key, value );
}
if(rerender){
this.tree.render(true, false); // force, not-deep
}
},
/** Use the destroy method to clean up any modifications your widget has made to the DOM */
destroy: function() {
this._unbind();
this.tree._callHook("treeDestroy", this.tree);
// this.element.removeClass("ui-widget ui-widget-content ui-corner-all");
this.tree.$div.find(">ul.fancytree-container").remove();
this.$source && this.$source.removeClass("ui-helper-hidden");
// In jQuery UI 1.8, you must invoke the destroy method from the base widget
$.Widget.prototype.destroy.call(this);
// TODO: delete tree and nodes to make garbage collect easier?
// TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
},
// -------------------------------------------------------------------------
/* Remove all event handlers for our namespace */
_unbind: function() {
var ns = this.tree._ns;
this.element.unbind(ns);
this.tree.$container.unbind(ns);
$(document).unbind(ns);
},
/* Add mouse and kyboard handlers to the container */
_bind: function() {
var that = this,
opts = this.options,
tree = this.tree,
ns = tree._ns
// selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" )
;
// Remove all previuous handlers for this tree
this._unbind();
//alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container);
// tree.debug("bind events; container: ", tree.$container);
tree.$container.on("focusin" + ns + " focusout" + ns, function(event){
var node = FT.getNode(event),
flag = (event.type === "focusin");
// tree.debug("Tree container got event " + event.type, node, event);
// tree.treeOnFocusInOut.call(tree, event);
if(node){
// For example clicking into an <input> that is part of a node
tree._callHook("nodeSetFocus", node, flag);
}else{
tree._callHook("treeSetFocus", tree, flag);
}
}).on("selectstart" + ns, "span.fancytree-title", function(event){
// prevent mouse-drags to select text ranges
// tree.debug("<span title> got event " + event.type);
event.preventDefault();
}).on("keydown" + ns, function(event){
// TODO: also bind keyup and keypress
// tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus());
// if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){
if(opts.disabled || opts.keyboard === false ){
return true;
}
var res,
node = tree.focusNode, // node may be null
ctx = tree._makeHookContext(node || tree, event),
prevPhase = tree.phase;
try {
tree.phase = "userEvent";
// If a 'fancytreekeydown' handler returns false, skip the default
// handling (implemented by tree.nodeKeydown()).
if(node){
res = tree._triggerNodeEvent("keydown", node, event);
}else{
res = tree._triggerTreeEvent("keydown", event);
}
if ( res === "preventNav" ){
res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls
} else if ( res !== false ){
res = tree._callHook("nodeKeydown", ctx);
}
return res;
} finally {
tree.phase = prevPhase;
}
}).on("click" + ns + " dblclick" + ns, function(event){
if(opts.disabled){
return true;
}
var ctx,
et = FT.getEventTarget(event),
node = et.node,
tree = that.tree,
prevPhase = tree.phase;
if( !node ){
return true; // Allow bubbling of other events
}
ctx = tree._makeHookContext(node, event);
// that.tree.debug("event(" + event.type + "): node: ", node);
try {
tree.phase = "userEvent";
switch(event.type) {
case "click":
ctx.targetType = et.type;
return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx);
case "dblclick":
ctx.targetType = et.type;
return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx);
}
// } catch(e) {
// // var _ = null; // DT issue 117 // TODO
// $.error(e);
} finally {
tree.phase = prevPhase;
}
});
},
/** Return the active node or null.
* @returns {FancytreeNode}
*/
getActiveNode: function() {
return this.tree.activeNode;
},
/** Return the matching node or null.
* @param {string} key
* @returns {FancytreeNode}
*/
getNodeByKey: function(key) {
return this.tree.getNodeByKey(key);
},
/** Return the invisible system root node.
* @returns {FancytreeNode}
*/
getRootNode: function() {
return this.tree.rootNode;
},
/** Return the current tree instance.
* @returns {Fancytree}
*/
getTree: function() {
return this.tree;
}
});
// $.ui.fancytree was created by the widget factory. Create a local shortcut:
FT = $.ui.fancytree;
/**
* Static members in the `$.ui.fancytree` namespace.<br>
* <br>
* <pre class="sh_javascript sunlight-highlight-javascript">// Access static members:
* var node = $.ui.fancytree.getNode(element);
* alert($.ui.fancytree.version);
* </pre>
*
* @mixin Fancytree_Static
*/
$.extend($.ui.fancytree,
/** @lends Fancytree_Static# */
{
/** @type {string} */
version: "2.6.0", // Set to semver by 'grunt release'
/** @type {string} */
buildType: "production", // Set to 'production' by 'grunt build'
/** @type {int} */
debugLevel: 1, // Set to 1 by 'grunt build'
// Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel
_nextId: 1,
_nextNodeKey: 1,
_extensions: {},
// focusTree: null,
/** Expose class object as $.ui.fancytree._FancytreeClass */
_FancytreeClass: Fancytree,
/** Expose class object as $.ui.fancytree._FancytreeNodeClass */
_FancytreeNodeClass: FancytreeNode,
/* Feature checks to provide backwards compatibility */
jquerySupports: {
// http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
positionMyOfs: isVersionAtLeast($.ui.version, 1, 9)
},
/** Throw an error if condition fails (debug method).
* @param {boolean} cond
* @param {string} msg
*/
assert: function(cond, msg){
return _assert(cond, msg);
},
/** Return a function that executes *fn* at most every *timeout* ms.
* @param {integer} timeout
* @param {function} fn
* @param {boolean} [invokeAsap=false]
* @param {any} [ctx]
*/
debounce : function(timeout, fn, invokeAsap, ctx) {
var timer;
if(arguments.length === 3 && typeof invokeAsap !== "boolean") {
ctx = invokeAsap;
invokeAsap = false;
}
return function() {
var args = arguments;
ctx = ctx || this;
invokeAsap && !timer && fn.apply(ctx, args);
clearTimeout(timer);
timer = setTimeout(function() {
invokeAsap || fn.apply(ctx, args);
timer = null;
}, timeout);
};
},
/** Write message to console if debugLevel >= 2
* @param {string} msg
*/
debug: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments);
},
/** Write error message to console.
* @param {string} msg
*/
error: function(msg){
consoleApply("error", arguments);
},
/** Convert <, >, &, ", ', / to the equivalent entitites.
*
* @param {string} s
* @returns {string}
*/
escapeHtml: function(s){
return ("" + s).replace(/[&<>"'\/]/g, function (s) {
return ENTITY_MAP[s];
});
},
/** Inverse of escapeHtml().
*
* @param {string} s
* @returns {string}
*/
unescapeHtml: function(s){
var e = document.createElement("div");
e.innerHTML = s;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTargetType: function(event){
return this.getEventTarget(event).type;
},
/** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
*
* @param {Event} event Mouse event, e.g. click, ...
* @returns {object} Return a {node: FancytreeNode, type: TYPE} object
* TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
*/
getEventTarget: function(event){
var tcn = event && event.target ? event.target.className : "",
res = {node: this.getNode(event.target), type: undefined};
// We use a fast version of $(res.node).hasClass()
// See http://jsperf.com/test-for-classname/2
if( /\bfancytree-title\b/.test(tcn) ){
res.type = "title";
}else if( /\bfancytree-expander\b/.test(tcn) ){
res.type = (res.node.hasChildren() === false ? "prefix" : "expander");
}else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){
res.type = "checkbox";
}else if( /\bfancytree-icon\b/.test(tcn) ){
res.type = "icon";
}else if( /\bfancytree-node\b/.test(tcn) ){
// Somewhere near the title
res.type = "title";
}else if( event && event.target && $(event.target).closest(".fancytree-title").length ) {
// #228: clicking an embedded element inside a title
res.type = "title";
}
return res;
},
/** Return a FancytreeNode instance from element.
*
* @param {Element | jQueryObject | Event} el
* @returns {FancytreeNode} matching node or null
*/
getNode: function(el){
if(el instanceof FancytreeNode){
return el; // el already was a FancytreeNode
}else if(el.selector !== undefined){
el = el[0]; // el was a jQuery object: use the DOM element
}else if(el.originalEvent !== undefined){
el = el.target; // el was an Event
}
while( el ) {
if(el.ftnode) {
return el.ftnode;
}
el = el.parentNode;
}
return null;
},
/* Return a Fancytree instance from element.
* TODO: this function could help to get around the data('fancytree') / data('ui-fancytree') problem
* @param {Element | jQueryObject | Event} el
* @returns {Fancytree} matching tree or null
* /
getTree: function(el){
if(el instanceof Fancytree){
return el; // el already was a Fancytree
}else if(el.selector !== undefined){
el = el[0]; // el was a jQuery object: use the DOM element
}else if(el.originalEvent !== undefined){
el = el.target; // el was an Event
}
...
return null;
},
*/
/** Write message to console if debugLevel >= 1
* @param {string} msg
*/
info: function(msg){
/*jshint expr:true */
($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments);
},
/**
* Parse tree data from HTML <ul> markup
*
* @param {jQueryObject} $ul
* @returns {NodeData[]}
*/
parseHtml: function($ul) {
// TODO: understand this:
/*jshint validthis:true */
var extraClasses, i, l, iPos, tmp, tmp2, classes, className,
$children = $ul.find(">li"),
children = [];
$children.each(function() {
var allData,
$li = $(this),
$liSpan = $li.find(">span:first", this),
$liA = $liSpan.length ? null : $li.find(">a:first"),
d = { tooltip: null, data: {} };
if( $liSpan.length ) {
d.title = $liSpan.html();
} else if( $liA && $liA.length ) {
// If a <li><a> tag is specified, use it literally and extract href/target.
d.title = $liA.html();
d.data.href = $liA.attr("href");
d.data.target = $liA.attr("target");
d.tooltip = $liA.attr("title");
} else {
// If only a <li> tag is specified, use the trimmed string up to
// the next child <ul> tag.
d.title = $li.html();
iPos = d.title.search(/<ul/i);
if( iPos >= 0 ){
d.title = d.title.substring(0, iPos);
}
}
d.title = $.trim(d.title);
// Make sure all fields exist
for(i=0, l=CLASS_ATTRS.length; i<l; i++){
d[CLASS_ATTRS[i]] = undefined;
}
// Initialize to `true`, if class is set and collect extraClasses
classes = this.className.split(" ");
extraClasses = [];
for(i=0, l=classes.length; i<l; i++){
className = classes[i];
if(CLASS_ATTR_MAP[className]){
d[className] = true;
}else{
extraClasses.push(className);
}
}
d.extraClasses = extraClasses.join(" ");
// Parse node options from ID, title and class attributes
tmp = $li.attr("title");
if( tmp ){
d.tooltip = tmp; // overrides <a title='...'>
}
tmp = $li.attr("id");
if( tmp ){
d.key = tmp;
}
// Add <li data-NAME='...'> as node.data.NAME
allData = _getElementDataAsDict($li);
if(allData && !$.isEmptyObject(allData)) {
// #56: Allow to set special node.attributes from data-...
for(i=0, l=NODE_ATTRS.length; i<l; i++){
tmp = NODE_ATTRS[i];
tmp2 = allData[tmp];
if( tmp2 != null ) {
delete allData[tmp];
d[tmp] = tmp2;
}
}
// All other data-... goes to node.data...
$.extend(d.data, allData);
}
// Recursive reading of child nodes, if LI tag contains an UL tag
$ul = $li.find(">ul:first");
if( $ul.length ) {
d.children = $.ui.fancytree.parseHtml($ul);
}else{
d.children = d.lazy ? undefined : null;
}
children.push(d);
// FT.debug("parse ", d, children);
});
return children;
},
/** Add Fancytree extension definition to the list of globally available extensions.
*
* @param {object} definition
*/
registerExtension: function(definition){
_assert(definition.name != null, "extensions must have a `name` property.");
_assert(definition.version != null, "extensions must have a `version` property.");
$.ui.fancytree._extensions[definition.name] = definition;
},
/** Write warning message to console.
* @param {string} msg
*/
warn: function(msg){
consoleApply("warn", arguments);
}
});
}(jQuery, window, document));
|
src/Logout/index.js | MLsandbox/MLsandbox | import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import '../Sandbox/Drawer/drawerStyles.css';
class Logout extends Component {
constructor (props) {
super (props);
this.logoutHandler = this.logoutHandler.bind(this);
}
logoutHandler () {
localStorage.removeItem('jwtToken');
this.props.dispatch({type: 'LOGOUT'});
}
render () {
if (this.props.authentication) {
return (
<a className="nav-link" onClick={this.logoutHandler}>
Logout
</a>
);
} else {
return (<Redirect to={{ pathname: '/'}}/>);
}
}
}
export default connect((state) => {
return {
authentication: state.auth.authentication.authorization,
};
})(Logout); |
examples/js/keyboard-nav/nav-with-select-table.js | AllenFang/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
export default class SimpleNavTable extends React.Component {
render() {
const selectRow = {
mode: 'checkbox'
};
return (
<BootstrapTable data={ products } selectRow={ selectRow } keyBoardNav>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
ajax/libs/primereact/6.5.1/carousel/carousel.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { UniqueComponentId, DomHandler, classNames, Ripple } from 'primereact/core';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var CarouselItem = /*#__PURE__*/function (_Component) {
_inherits(CarouselItem, _Component);
var _super = _createSuper(CarouselItem);
function CarouselItem() {
_classCallCheck(this, CarouselItem);
return _super.apply(this, arguments);
}
_createClass(CarouselItem, [{
key: "render",
value: function render() {
var content = this.props.template(this.props.item);
var itemClassName = classNames(this.props.className, 'p-carousel-item', {
'p-carousel-item-active': this.props.active,
'p-carousel-item-start': this.props.start,
'p-carousel-item-end': this.props.end
});
return /*#__PURE__*/React.createElement("div", {
className: itemClassName
}, content);
}
}]);
return CarouselItem;
}(Component);
_defineProperty(CarouselItem, "defaultProps", {
template: null,
item: null,
active: false,
start: false,
end: false,
className: null
});
var Carousel = /*#__PURE__*/function (_Component2) {
_inherits(Carousel, _Component2);
var _super2 = _createSuper(Carousel);
function Carousel(props) {
var _this;
_classCallCheck(this, Carousel);
_this = _super2.call(this, props);
_this.state = {
numVisible: props.numVisible,
numScroll: props.numScroll,
totalShiftedItems: props.page * props.numScroll * -1
};
if (!_this.props.onPageChange) {
_this.state = _objectSpread(_objectSpread({}, _this.state), {}, {
page: props.page
});
}
_this.navBackward = _this.navBackward.bind(_assertThisInitialized(_this));
_this.navForward = _this.navForward.bind(_assertThisInitialized(_this));
_this.onTransitionEnd = _this.onTransitionEnd.bind(_assertThisInitialized(_this));
_this.onTouchStart = _this.onTouchStart.bind(_assertThisInitialized(_this));
_this.onTouchMove = _this.onTouchMove.bind(_assertThisInitialized(_this));
_this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this));
_this.totalIndicators = 0;
_this.remainingItems = 0;
_this.allowAutoplay = !!_this.props.autoplayInterval;
_this.circular = _this.props.circular || _this.allowAutoplay;
_this.attributeSelector = UniqueComponentId();
_this.swipeThreshold = 20;
return _this;
}
_createClass(Carousel, [{
key: "step",
value: function step(dir, page) {
var totalShiftedItems = this.state.totalShiftedItems;
var isCircular = this.isCircular();
if (page != null) {
totalShiftedItems = this.state.numScroll * page * -1;
if (isCircular) {
totalShiftedItems -= this.state.numVisible;
}
this.isRemainingItemsAdded = false;
} else {
totalShiftedItems += this.state.numScroll * dir;
if (this.isRemainingItemsAdded) {
totalShiftedItems += this.remainingItems - this.state.numScroll * dir;
this.isRemainingItemsAdded = false;
}
var originalShiftedItems = isCircular ? totalShiftedItems + this.state.numVisible : totalShiftedItems;
page = Math.abs(Math.floor(originalShiftedItems / this.state.numScroll));
}
if (isCircular && this.state.page === this.totalIndicators - 1 && dir === -1) {
totalShiftedItems = -1 * (this.props.value.length + this.state.numVisible);
page = 0;
} else if (isCircular && this.state.page === 0 && dir === 1) {
totalShiftedItems = 0;
page = this.totalIndicators - 1;
} else if (page === this.totalIndicators - 1 && this.remainingItems > 0) {
totalShiftedItems += this.remainingItems * -1 - this.state.numScroll * dir;
this.isRemainingItemsAdded = true;
}
if (this.itemsContainer) {
DomHandler.removeClass(this.itemsContainer, 'p-items-hidden');
this.changePosition(totalShiftedItems);
this.itemsContainer.style.transition = 'transform 500ms ease 0s';
}
if (this.props.onPageChange) {
this.setState({
totalShiftedItems: totalShiftedItems
});
this.props.onPageChange({
page: page
});
} else {
this.setState({
page: page,
totalShiftedItems: totalShiftedItems
});
}
}
}, {
key: "calculatePosition",
value: function calculatePosition() {
if (this.itemsContainer && this.responsiveOptions) {
var windowWidth = window.innerWidth;
var matchedResponsiveData = {
numVisible: this.props.numVisible,
numScroll: this.props.numScroll
};
for (var i = 0; i < this.responsiveOptions.length; i++) {
var res = this.responsiveOptions[i];
if (parseInt(res.breakpoint, 10) >= windowWidth) {
matchedResponsiveData = res;
}
}
var state = {};
if (this.state.numScroll !== matchedResponsiveData.numScroll) {
var page = this.getPage();
page = Math.floor(page * this.state.numScroll / matchedResponsiveData.numScroll);
var totalShiftedItems = matchedResponsiveData.numScroll * page * -1;
if (this.isCircular()) {
totalShiftedItems -= matchedResponsiveData.numVisible;
}
state = {
totalShiftedItems: totalShiftedItems,
numScroll: matchedResponsiveData.numScroll
};
if (this.props.onPageChange) {
this.props.onPageChange({
page: page
});
} else {
state = _objectSpread(_objectSpread({}, state), {}, {
page: page
});
}
}
if (this.state.numVisible !== matchedResponsiveData.numVisible) {
state = _objectSpread(_objectSpread({}, state), {}, {
numVisible: matchedResponsiveData.numVisible
});
}
if (Object.keys(state).length) {
this.setState(state);
}
}
}
}, {
key: "navBackward",
value: function navBackward(e, page) {
if (this.circular || this.getPage() !== 0) {
this.step(1, page);
}
this.allowAutoplay = false;
if (e.cancelable) {
e.preventDefault();
}
}
}, {
key: "navForward",
value: function navForward(e, page) {
if (this.circular || this.getPage() < this.totalIndicators - 1) {
this.step(-1, page);
}
this.allowAutoplay = false;
if (e.cancelable) {
e.preventDefault();
}
}
}, {
key: "onDotClick",
value: function onDotClick(e, page) {
var currentPage = this.getPage();
if (page > currentPage) {
this.navForward(e, page);
} else if (page < currentPage) {
this.navBackward(e, page);
}
}
}, {
key: "onTransitionEnd",
value: function onTransitionEnd() {
if (this.itemsContainer) {
DomHandler.addClass(this.itemsContainer, 'p-items-hidden');
this.itemsContainer.style.transition = '';
if ((this.state.page === 0 || this.state.page === this.totalIndicators - 1) && this.isCircular()) {
this.changePosition(this.state.totalShiftedItems);
}
}
}
}, {
key: "onTouchStart",
value: function onTouchStart(e) {
var touchobj = e.changedTouches[0];
this.startPos = {
x: touchobj.pageX,
y: touchobj.pageY
};
}
}, {
key: "onTouchMove",
value: function onTouchMove(e) {
if (e.cancelable) {
e.preventDefault();
}
}
}, {
key: "onTouchEnd",
value: function onTouchEnd(e) {
var touchobj = e.changedTouches[0];
if (this.isVertical()) {
this.changePageOnTouch(e, touchobj.pageY - this.startPos.y);
} else {
this.changePageOnTouch(e, touchobj.pageX - this.startPos.x);
}
}
}, {
key: "changePageOnTouch",
value: function changePageOnTouch(e, diff) {
if (Math.abs(diff) > this.swipeThreshold) {
if (diff < 0) {
// left
this.navForward(e);
} else {
// right
this.navBackward(e);
}
}
}
}, {
key: "bindDocumentListeners",
value: function bindDocumentListeners() {
var _this2 = this;
if (!this.documentResizeListener) {
this.documentResizeListener = function () {
_this2.calculatePosition();
};
window.addEventListener('resize', this.documentResizeListener);
}
}
}, {
key: "unbindDocumentListeners",
value: function unbindDocumentListeners() {
if (this.documentResizeListener) {
window.removeEventListener('resize', this.documentResizeListener);
this.documentResizeListener = null;
}
}
}, {
key: "isVertical",
value: function isVertical() {
return this.props.orientation === 'vertical';
}
}, {
key: "isCircular",
value: function isCircular() {
return this.circular && this.props.value.length >= this.state.numVisible;
}
}, {
key: "getPage",
value: function getPage() {
return this.props.onPageChange ? this.props.page : this.state.page;
}
}, {
key: "getTotalIndicators",
value: function getTotalIndicators() {
return this.props.value ? Math.ceil((this.props.value.length - this.state.numVisible) / this.state.numScroll) + 1 : 0;
}
}, {
key: "isAutoplay",
value: function isAutoplay() {
return this.props.autoplayInterval && this.allowAutoplay;
}
}, {
key: "startAutoplay",
value: function startAutoplay() {
var _this3 = this;
this.interval = setInterval(function () {
if (_this3.state.page === _this3.totalIndicators - 1) {
_this3.step(-1, 0);
} else {
_this3.step(-1, _this3.state.page + 1);
}
}, this.props.autoplayInterval);
}
}, {
key: "stopAutoplay",
value: function stopAutoplay() {
if (this.interval) {
clearInterval(this.interval);
}
}
}, {
key: "createStyle",
value: function createStyle() {
if (!this.carouselStyle) {
this.carouselStyle = document.createElement('style');
document.body.appendChild(this.carouselStyle);
}
var innerHTML = "\n .p-carousel[".concat(this.attributeSelector, "] .p-carousel-item {\n flex: 1 0 ").concat(100 / this.state.numVisible, "%\n }\n ");
if (this.props.responsiveOptions) {
this.responsiveOptions = _toConsumableArray(this.props.responsiveOptions);
this.responsiveOptions.sort(function (data1, data2) {
var value1 = data1.breakpoint;
var value2 = data2.breakpoint;
var result = null;
if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, undefined, {
numeric: true
});else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0;
return -1 * result;
});
for (var i = 0; i < this.responsiveOptions.length; i++) {
var res = this.responsiveOptions[i];
innerHTML += "\n @media screen and (max-width: ".concat(res.breakpoint, ") {\n .p-carousel[").concat(this.attributeSelector, "] .p-carousel-item {\n flex: 1 0 ").concat(100 / res.numVisible, "%\n }\n }\n ");
}
}
this.carouselStyle.innerHTML = innerHTML;
}
}, {
key: "changePosition",
value: function changePosition(totalShiftedItems) {
if (this.itemsContainer) {
this.itemsContainer.style.transform = this.isVertical() ? "translate3d(0, ".concat(totalShiftedItems * (100 / this.state.numVisible), "%, 0)") : "translate3d(".concat(totalShiftedItems * (100 / this.state.numVisible), "%, 0, 0)");
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.container) {
this.container.setAttribute(this.attributeSelector, '');
}
this.createStyle();
this.calculatePosition();
this.changePosition(this.state.totalShiftedItems);
if (this.props.responsiveOptions) {
this.bindDocumentListeners();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
var isCircular = this.isCircular();
var stateChanged = false;
var totalShiftedItems = this.state.totalShiftedItems;
if (this.props.autoplayInterval) {
this.stopAutoplay();
}
if (prevState.numScroll !== this.state.numScroll || prevState.numVisible !== this.state.numVisible || this.props.value && prevProps.value && prevProps.value.length !== this.props.value.length) {
this.remainingItems = (this.props.value.length - this.state.numVisible) % this.state.numScroll;
var page = this.getPage();
if (this.totalIndicators !== 0 && page >= this.totalIndicators) {
page = this.totalIndicators - 1;
if (this.props.onPageChange) {
this.props.onPageChange({
page: page
});
} else {
this.setState({
page: page
});
}
stateChanged = true;
}
totalShiftedItems = page * this.state.numScroll * -1;
if (isCircular) {
totalShiftedItems -= this.state.numVisible;
}
if (page === this.totalIndicators - 1 && this.remainingItems > 0) {
totalShiftedItems += -1 * this.remainingItems + this.state.numScroll;
this.isRemainingItemsAdded = true;
} else {
this.isRemainingItemsAdded = false;
}
if (totalShiftedItems !== this.state.totalShiftedItems) {
this.setState({
totalShiftedItems: totalShiftedItems
});
stateChanged = true;
}
this.changePosition(totalShiftedItems);
}
if (isCircular) {
if (this.state.page === 0) {
totalShiftedItems = -1 * this.state.numVisible;
} else if (totalShiftedItems === 0) {
totalShiftedItems = -1 * this.props.value.length;
if (this.remainingItems > 0) {
this.isRemainingItemsAdded = true;
}
}
if (totalShiftedItems !== this.state.totalShiftedItems) {
this.setState({
totalShiftedItems: totalShiftedItems
});
stateChanged = true;
}
}
if (prevProps.page !== this.props.page) {
if (this.props.page > prevProps.page && this.props.page <= this.totalIndicators - 1) {
this.step(-1, this.props.page);
} else if (this.props.page < prevProps.page) {
this.step(1, this.props.page);
}
}
if (!stateChanged && this.isAutoplay()) {
this.startAutoplay();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.props.responsiveOptions) {
this.unbindDocumentListeners();
}
if (this.props.autoplayInterval) {
this.stopAutoplay();
}
}
}, {
key: "renderItems",
value: function renderItems() {
var _this4 = this;
if (this.props.value && this.props.value.length) {
var isCircular = this.isCircular();
var clonedItemsForStarting = null;
var clonedItemsForFinishing = null;
if (isCircular) {
var clonedElements = null;
clonedElements = this.props.value.slice(-1 * this.state.numVisible);
clonedItemsForStarting = clonedElements.map(function (item, index) {
var isActive = _this4.state.totalShiftedItems * -1 === _this4.props.value.length + _this4.state.numVisible,
start = index === 0,
end = index === clonedElements.length - 1;
return /*#__PURE__*/React.createElement(CarouselItem, {
key: index + '_scloned',
className: "p-carousel-item-cloned",
template: _this4.props.itemTemplate,
item: item,
active: isActive,
start: start,
end: end
});
});
clonedElements = this.props.value.slice(0, this.state.numVisible);
clonedItemsForFinishing = clonedElements.map(function (item, index) {
var isActive = _this4.state.totalShiftedItems === 0,
start = index === 0,
end = index === clonedElements.length - 1;
return /*#__PURE__*/React.createElement(CarouselItem, {
key: index + '_fcloned',
className: "p-carousel-item-cloned",
template: _this4.props.itemTemplate,
item: item,
active: isActive,
start: start,
end: end
});
});
}
var items = this.props.value.map(function (item, index) {
var firstIndex = isCircular ? -1 * (_this4.state.totalShiftedItems + _this4.state.numVisible) : _this4.state.totalShiftedItems * -1,
lastIndex = firstIndex + _this4.state.numVisible - 1,
isActive = firstIndex <= index && lastIndex >= index,
start = firstIndex === index,
end = lastIndex === index;
return /*#__PURE__*/React.createElement(CarouselItem, {
key: index,
template: _this4.props.itemTemplate,
item: item,
active: isActive,
start: start,
end: end
});
});
return /*#__PURE__*/React.createElement(React.Fragment, null, clonedItemsForStarting, items, clonedItemsForFinishing);
}
}
}, {
key: "renderHeader",
value: function renderHeader() {
if (this.props.header) {
return /*#__PURE__*/React.createElement("div", {
className: "p-carousel-header"
}, this.props.header);
}
return null;
}
}, {
key: "renderFooter",
value: function renderFooter() {
if (this.props.footer) {
return /*#__PURE__*/React.createElement("div", {
className: "p-carousel-footer"
}, this.props.footer);
}
return null;
}
}, {
key: "renderContent",
value: function renderContent() {
var _this5 = this;
var items = this.renderItems();
var height = this.isVertical() ? this.props.verticalViewPortHeight : 'auto';
var backwardNavigator = this.renderBackwardNavigator();
var forwardNavigator = this.renderForwardNavigator();
var containerClassName = classNames('p-carousel-container', this.props.containerClassName);
return /*#__PURE__*/React.createElement("div", {
className: containerClassName
}, backwardNavigator, /*#__PURE__*/React.createElement("div", {
className: "p-carousel-items-content",
style: {
'height': height
}
}, /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this5.itemsContainer = el;
},
className: "p-carousel-items-container",
onTransitionEnd: this.onTransitionEnd,
onTouchStart: this.onTouchStart,
onTouchMove: this.onTouchMove,
onTouchEnd: this.onTouchEnd
}, items)), forwardNavigator);
}
}, {
key: "renderBackwardNavigator",
value: function renderBackwardNavigator() {
var isDisabled = (!this.circular || this.props.value && this.props.value.length < this.state.numVisible) && this.getPage() === 0;
var buttonClassName = classNames('p-carousel-prev p-link', {
'p-disabled': isDisabled
}),
iconClassName = classNames('p-carousel-prev-icon pi', {
'pi-chevron-left': !this.isVertical(),
'pi-chevron-up': this.isVertical()
});
return /*#__PURE__*/React.createElement("button", {
type: "button",
className: buttonClassName,
onClick: this.navBackward,
disabled: isDisabled
}, /*#__PURE__*/React.createElement("span", {
className: iconClassName
}), /*#__PURE__*/React.createElement(Ripple, null));
}
}, {
key: "renderForwardNavigator",
value: function renderForwardNavigator() {
var isDisabled = (!this.circular || this.props.value && this.props.value.length < this.state.numVisible) && (this.getPage() === this.totalIndicators - 1 || this.totalIndicators === 0);
var buttonClassName = classNames('p-carousel-next p-link', {
'p-disabled': isDisabled
}),
iconClassName = classNames('p-carousel-next-icon pi', {
'pi-chevron-right': !this.isVertical(),
'pi-chevron-down': this.isVertical()
});
return /*#__PURE__*/React.createElement("button", {
type: "button",
className: buttonClassName,
onClick: this.navForward,
disabled: isDisabled
}, /*#__PURE__*/React.createElement("span", {
className: iconClassName
}), /*#__PURE__*/React.createElement(Ripple, null));
}
}, {
key: "renderIndicator",
value: function renderIndicator(index) {
var _this6 = this;
var isActive = this.getPage() === index,
indicatorItemClassName = classNames('p-carousel-indicator', {
'p-highlight': isActive
});
return /*#__PURE__*/React.createElement("li", {
className: indicatorItemClassName,
key: 'p-carousel-indicator-' + index
}, /*#__PURE__*/React.createElement("button", {
type: "button",
className: "p-link",
onClick: function onClick(e) {
return _this6.onDotClick(e, index);
}
}, /*#__PURE__*/React.createElement(Ripple, null)));
}
}, {
key: "renderIndicators",
value: function renderIndicators() {
var indicatorsContentClassName = classNames('p-carousel-indicators p-reset', this.props.indicatorsContentClassName);
var indicators = [];
for (var i = 0; i < this.totalIndicators; i++) {
indicators.push(this.renderIndicator(i));
}
return /*#__PURE__*/React.createElement("ul", {
className: indicatorsContentClassName
}, indicators);
}
}, {
key: "render",
value: function render() {
var _this7 = this;
var className = classNames('p-carousel p-component', {
'p-carousel-vertical': this.isVertical(),
'p-carousel-horizontal': !this.isVertical()
}, this.props.className);
var contentClassName = classNames('p-carousel-content', this.props.contentClassName);
this.totalIndicators = this.getTotalIndicators();
var content = this.renderContent();
var indicators = this.renderIndicators();
var header = this.renderHeader();
var footer = this.renderFooter();
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this7.container = el;
},
id: this.props.id,
className: className,
style: this.props.style
}, header, /*#__PURE__*/React.createElement("div", {
className: contentClassName
}, content, indicators), footer);
}
}]);
return Carousel;
}(Component);
_defineProperty(Carousel, "defaultProps", {
id: null,
value: null,
page: 0,
header: null,
footer: null,
style: null,
className: null,
itemTemplate: null,
circular: false,
autoplayInterval: 0,
numVisible: 1,
numScroll: 1,
responsiveOptions: null,
orientation: "horizontal",
verticalViewPortHeight: "300px",
contentClassName: null,
containerClassName: null,
indicatorsContentClassName: null,
onPageChange: null
});
export { Carousel };
|
js/App/Components/Location/AddLocation/TimeZoneContinent.js | telldus/telldus-live-mobile-v3 | /**
* Copyright 2016-present Telldus Technologies AB.
*
* This file is part of the Telldus Live! app.
*
* Telldus Live! app is free : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Telldus Live! app is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
// @flow
'use strict';
import React from 'react';
import differenceWith from 'lodash/differenceWith';
import { announceForAccessibility } from 'react-native-accessibility';
import timeZone from '../../../Lib/TimeZone';
import { View } from '../../../../BaseComponents';
import ContinentsList from '../Common/ContinentsList';
import i18n from '../../../Translations/common';
import capitalize from '../../../Lib/capitalize';
type Props = {
navigation: Object,
onDidMount: Function,
intl: Object,
appLayout: Object,
screenReaderEnabled: boolean,
currentScreen: string,
route: Object,
};
class TimeZoneContinent extends View {
onContinentChoose: (string) => void;
props: Props;
constructor(props: Props) {
super(props);
let { formatMessage } = props.intl;
this.h1 = capitalize(formatMessage(i18n.headerOneTimeZoneContinent));
this.h2 = formatMessage(i18n.headerTwoTimeZoneContinent);
this.labelMessageToAnnounce = `${formatMessage(i18n.screen)} ${this.h1}. ${this.h2}`;
this.onContinentChoose = this.onContinentChoose.bind(this);
}
componentDidMount() {
const { h1, h2 } = this;
this.props.onDidMount(h1, h2);
let { screenReaderEnabled } = this.props;
if (screenReaderEnabled) {
announceForAccessibility(this.labelMessageToAnnounce);
}
}
componentDidUpdate(prevProps: Object, prevState: Object) {
let { screenReaderEnabled, currentScreen } = this.props;
let shouldAnnounce = currentScreen === 'TimeZoneContinent' && prevProps.currentScreen !== 'TimeZoneContinent';
if (screenReaderEnabled && shouldAnnounce) {
announceForAccessibility(this.labelMessageToAnnounce);
}
}
shouldComponentUpdate(nextProps: Object, nextState: Object): boolean {
return nextProps.currentScreen === 'TimeZoneContinent';
}
onContinentChoose(continent: string) {
const { navigation, route } = this.props;
let { clientInfo } = route.params || {};
if (continent === 'UTC') {
clientInfo.timezone = continent;
navigation.navigate('Position', {clientInfo});
} else {
let data = differenceWith(timeZone, [continent], (v1: string, v2: string): boolean => {
let items = v1.split('/');
return !(items[0] === v2);
});
clientInfo.continent = continent;
navigation.navigate('TimeZoneCity', {
clientInfo,
cities: data,
});
}
}
render(): Object {
return (
<ContinentsList
{...this.props}
onSubmit={this.onContinentChoose}/>
);
}
}
export default (TimeZoneContinent: Object);
|
ajax/libs/react/0.12.0-rc1/JSXTransformer.js | joeylakay/cdnjs | /**
* JSXTransformer v0.12.0-rc1
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)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.JSXTransformer=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);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*/
/* jshint browser: true */
/* jslint evil: true */
'use strict';
var buffer = _dereq_('buffer');
var transform = _dereq_('jstransform').transform;
var visitors = _dereq_('./fbtransform/visitors');
var headEl;
var dummyAnchor;
var inlineScriptCount = 0;
// The source-map library relies on Object.defineProperty, but IE8 doesn't
// support it fully even with es5-sham. Indeed, es5-sham's defineProperty
// throws when Object.prototype.__defineGetter__ is missing, so we skip building
// the source map in that case.
var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
/**
* Run provided code through jstransform.
*
* @param {string} source Original source code
* @param {object?} options Options to pass to jstransform
* @return {object} object as returned from jstransform
*/
function transformReact(source, options) {
// TODO: just use react-tools
options = options || {};
var visitorList;
if (options.harmony) {
visitorList = visitors.getAllVisitors();
} else {
visitorList = visitors.transformVisitors.react;
}
return transform(visitorList, source, {
sourceMap: supportsAccessors && options.sourceMap
});
}
/**
* Eval provided source after transforming it.
*
* @param {string} source Original source code
* @param {object?} options Options to pass to jstransform
*/
function exec(source, options) {
return eval(transformReact(source, options).code);
}
/**
* This method returns a nicely formated line of code pointing to the exact
* location of the error `e`. The line is limited in size so big lines of code
* are also shown in a readable way.
*
* Example:
* ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ...
* ^
*
* @param {string} code The full string of code
* @param {Error} e The error being thrown
* @return {string} formatted message
* @internal
*/
function createSourceCodeErrorMessage(code, e) {
var sourceLines = code.split('\n');
var erroneousLine = sourceLines[e.lineNumber - 1];
// Removes any leading indenting spaces and gets the number of
// chars indenting the `erroneousLine`
var indentation = 0;
erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) {
indentation = leadingSpaces.length;
return '';
});
// Defines the number of characters that are going to show
// before and after the erroneous code
var LIMIT = 30;
var errorColumn = e.column - indentation;
if (errorColumn > LIMIT) {
erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT);
errorColumn = 4 + LIMIT;
}
if (erroneousLine.length - errorColumn > LIMIT) {
erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...';
}
var message = '\n\n' + erroneousLine + '\n';
message += new Array(errorColumn - 1).join(' ') + '^';
return message;
}
/**
* Actually transform the code.
*
* @param {string} code
* @param {string?} url
* @param {object?} options
* @return {string} The transformed code.
* @internal
*/
function transformCode(code, url, options) {
try {
var transformed = transformReact(code, options);
} catch(e) {
e.message += '\n at ';
if (url) {
if ('fileName' in e) {
// We set `fileName` if it's supported by this error object and
// a `url` was provided.
// The error will correctly point to `url` in Firefox.
e.fileName = url;
}
e.message += url + ':' + e.lineNumber + ':' + e.column;
} else {
e.message += location.href;
}
e.message += createSourceCodeErrorMessage(code, e);
throw e;
}
if (!transformed.sourceMap) {
return transformed.code;
}
var map = transformed.sourceMap.toJSON();
var source;
if (url == null) {
source = "Inline JSX script";
inlineScriptCount++;
if (inlineScriptCount > 1) {
source += ' (' + inlineScriptCount + ')';
}
} else if (dummyAnchor) {
// Firefox has problems when the sourcemap source is a proper URL with a
// protocol and hostname, so use the pathname. We could use just the
// filename, but hopefully using the full path will prevent potential
// issues where the same filename exists in multiple directories.
dummyAnchor.href = url;
source = dummyAnchor.pathname.substr(1);
}
map.sources = [source];
map.sourcesContent = [code];
return (
transformed.code +
'\n//# sourceMappingURL=data:application/json;base64,' +
buffer.Buffer(JSON.stringify(map)).toString('base64')
);
}
/**
* Appends a script element at the end of the <head> with the content of code,
* after transforming it.
*
* @param {string} code The original source code
* @param {string?} url Where the code came from. null if inline
* @param {object?} options Options to pass to jstransform
* @internal
*/
function run(code, url, options) {
var scriptEl = document.createElement('script');
scriptEl.text = transformCode(code, url, options);
headEl.appendChild(scriptEl);
}
/**
* Load script from the provided url and pass the content to the callback.
*
* @param {string} url The location of the script src
* @param {function} callback Function to call with the content of url
* @internal
*/
function load(url, successCallback, errorCallback) {
var xhr;
xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP')
: new XMLHttpRequest();
// async, however scripts will be executed in the order they are in the
// DOM to mirror normal script loading.
xhr.open('GET', url, true);
if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0 || xhr.status === 200) {
successCallback(xhr.responseText);
} else {
errorCallback();
throw new Error("Could not load " + url);
}
}
};
return xhr.send(null);
}
/**
* Loop over provided script tags and get the content, via innerHTML if an
* inline script, or by using XHR. Transforms are applied if needed. The scripts
* are executed in the order they are found on the page.
*
* @param {array} scripts The <script> elements to load and run.
* @internal
*/
function loadScripts(scripts) {
var result = [];
var count = scripts.length;
function check() {
var script, i;
for (i = 0; i < count; i++) {
script = result[i];
if (script.loaded && !script.executed) {
script.executed = true;
run(script.content, script.url, script.options);
} else if (!script.loaded && !script.error && !script.async) {
break;
}
}
}
scripts.forEach(function(script, i) {
var options = {
sourceMap: true
};
if (/;harmony=true(;|$)/.test(script.type)) {
options.harmony = true
}
// script.async is always true for non-javascript script tags
var async = script.hasAttribute('async');
if (script.src) {
result[i] = {
async: async,
error: false,
executed: false,
content: null,
loaded: false,
url: script.src,
options: options
};
load(script.src, function(content) {
result[i].loaded = true;
result[i].content = content;
check();
}, function() {
result[i].error = true;
check();
});
} else {
result[i] = {
async: async,
error: false,
executed: false,
content: script.innerHTML,
loaded: true,
url: null,
options: options
};
}
});
check();
}
/**
* Find and run all script tags with type="text/jsx".
*
* @internal
*/
function runScripts() {
var scripts = document.getElementsByTagName('script');
// Array.prototype.slice cannot be used on NodeList on IE8
var jsxScripts = [];
for (var i = 0; i < scripts.length; i++) {
if (/^text\/jsx(;|$)/.test(scripts.item(i).type)) {
jsxScripts.push(scripts.item(i));
}
}
if (jsxScripts.length < 1) {
return;
}
console.warn(
'You are using the in-browser JSX transformer. Be sure to precompile ' +
'your JSX for production - ' +
'http://facebook.github.io/react/docs/tooling-integration.html#jsx'
);
loadScripts(jsxScripts);
}
// Listen for load event if we're in a browser and then kick off finding and
// running of scripts.
if (typeof window !== "undefined" && window !== null) {
headEl = document.getElementsByTagName('head')[0];
dummyAnchor = document.createElement('a');
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', runScripts, false);
} else {
window.attachEvent('onload', runScripts);
}
}
module.exports = {
transform: transformReact,
exec: exec
};
},{"./fbtransform/visitors":37,"buffer":2,"jstransform":21}],2:[function(_dereq_,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
var base64 = _dereq_('base64-js')
var ieee754 = _dereq_('ieee754')
var isArray = _dereq_('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = Buffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var kMaxLength = 0x3fffffff
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
*
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
* get the Object implementation, which is slower but will work correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
return 42 === arr.foo() && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding, noZero) {
if (!(this instanceof Buffer))
return new Buffer(subject, encoding, noZero)
var type = typeof subject
// Find the length
var length
if (type === 'number')
length = subject > 0 ? subject >>> 0 : 0
else if (type === 'string') {
if (encoding === 'base64')
subject = base64clean(subject)
length = Buffer.byteLength(subject, encoding)
} else if (type === 'object' && subject !== null) { // assume object is array-like
if (subject.type === 'Buffer' && isArray(subject.data))
subject = subject.data
length = +subject.length > 0 ? Math.floor(+subject.length) : 0
} else
throw new TypeError('must start with number, buffer, array or string')
if (this.length > kMaxLength)
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength.toString(16) + ' bytes')
var buf
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
buf = Buffer._augment(new Uint8Array(length))
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
buf = this
buf.length = length
buf._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
buf._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
if (Buffer.isBuffer(subject)) {
for (i = 0; i < length; i++)
buf[i] = subject.readUInt8(i)
} else {
for (i = 0; i < length; i++)
buf[i] = ((subject[i] % 256) + 256) % 256
}
} else if (type === 'string') {
buf.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) {
for (i = 0; i < length; i++) {
buf[i] = 0
}
}
return buf
}
Buffer.isBuffer = function (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b))
throw new TypeError('Arguments must be Buffers')
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function (list, totalLength) {
if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (totalLength === undefined) {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
Buffer.byteLength = function (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
case 'hex':
ret = str.length >>> 1
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'base64':
ret = base64ToBytes(str).length
break
default:
ret = str.length
}
return ret
}
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function (encoding, start, end) {
var loweredCase = false
start = start >>> 0
end = end === undefined || end === Infinity ? this.length : end >>> 0
if (!encoding) encoding = 'utf8'
if (start < 0) start = 0
if (end > this.length) end = this.length
if (end <= start) return ''
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase)
throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.equals = function (b) {
if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max)
str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
return Buffer.compare(this, b)
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
Buffer.prototype.set = function (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var byte = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(byte)) throw new Error('Invalid hex string')
buf[offset + i] = byte
}
return i
}
function utf8Write (buf, string, offset, length) {
var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
return charsWritten
}
function asciiWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function utf16leWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = utf8Write(this, string, offset, length)
break
case 'ascii':
ret = asciiWrite(this, string, offset, length)
break
case 'binary':
ret = binaryWrite(this, string, offset, length)
break
case 'base64':
ret = base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = utf16leWrite(this, string, offset, length)
break
default:
throw new TypeError('Unknown encoding: ' + encoding)
}
return ret
}
Buffer.prototype.toJSON = function () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function binarySlice (buf, start, end) {
return asciiSlice(buf, start, end)
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len;
if (start < 0)
start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0)
end = 0
} else if (end > len) {
end = len
}
if (end < start)
end = start
if (Buffer.TYPED_ARRAY_SUPPORT) {
return Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
var newBuf = new Buffer(sliceLen, undefined, true)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
return newBuf
}
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0)
throw new RangeError('offset is not uint')
if (offset + ext > length)
throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUInt8 = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readInt8 = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80))
return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
if (value > max || value < min) throw new TypeError('value is out of bounds')
if (offset + ext > buf.length) throw new TypeError('index out of range')
}
Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else objectWriteUInt16(this, value, offset, true)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else objectWriteUInt16(this, value, offset, false)
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
} else objectWriteUInt32(this, value, offset, true)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else objectWriteUInt32(this, value, offset, false)
return offset + 4
}
Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else objectWriteUInt16(this, value, offset, true)
return offset + 2
}
Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else objectWriteUInt16(this, value, offset, false)
return offset + 2
}
Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else objectWriteUInt32(this, value, offset, true)
return offset + 4
}
Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else objectWriteUInt32(this, value, offset, false)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new TypeError('value is out of bounds')
if (offset + ext > buf.length) throw new TypeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert)
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert)
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function (target, target_start, start, end) {
var source = this
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (!target_start) target_start = 0
// Copy 0 bytes; we're done
if (end === start) return
if (target.length === 0 || source.length === 0) return
// Fatal error conditions
if (end < start) throw new TypeError('sourceEnd < sourceStart')
if (target_start < 0 || target_start >= target.length)
throw new TypeError('targetStart out of bounds')
if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds')
if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length)
end = this.length
if (target.length - target_start < end - start)
end = target.length - target_start + start
var len = end - start
if (len < 100 || !Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < len; i++) {
target[i + target_start] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), target_start)
}
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (end < start) throw new TypeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new TypeError('start out of bounds')
if (end < 0 || end > this.length) throw new TypeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function (arr) {
arr._isBuffer = true
// save reference to original Uint8Array get/set methods before overwriting
arr._get = arr.get
arr._set = arr.set
// deprecated, will be removed in node 0.13+
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
var b = str.charCodeAt(i)
if (b <= 0x7F) {
byteArray.push(b)
} else {
var start = i
if (b >= 0xD800 && b <= 0xDFFF) i++
var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
for (var j = 0; j < h.length; j++) {
byteArray.push(parseInt(h[j], 16))
}
}
}
return byteArray
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(str)
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length))
break
dst[i + offset] = src[i]
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
},{"base64-js":3,"ieee754":4,"is-array":5}],3:[function(_dereq_,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS)
return 62 // '+'
if (code === SLASH)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],4:[function(_dereq_,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity);
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],5:[function(_dereq_,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],6:[function(_dereq_,module,exports){
(function (process){
// 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.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,_dereq_('_process'))
},{"_process":7}],7:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canMutationObserver = typeof window !== 'undefined'
&& window.MutationObserver;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
var queue = [];
if (canMutationObserver) {
var hiddenDiv = document.createElement("div");
var observer = new MutationObserver(function () {
var queueList = queue.slice();
queue.length = 0;
queueList.forEach(function (fn) {
fn();
});
});
observer.observe(hiddenDiv, { attributes: true });
return function nextTick(fn) {
if (!queue.length) {
hiddenDiv.setAttribute('yes', 'no');
}
queue.push(fn);
};
}
if (canPost) {
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');
};
},{}],8:[function(_dereq_,module,exports){
/*
Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint bitwise:true plusplus:true */
/*global esprima:true, define:true, exports:true, window: true,
throwError: true, generateStatement: true, peek: true,
parseAssignmentExpression: true, parseBlock: true,
parseClassExpression: true, parseClassDeclaration: true, parseExpression: true,
parseForStatement: true,
parseFunctionDeclaration: true, parseFunctionExpression: true,
parseFunctionSourceElements: true, parseVariableIdentifier: true,
parseImportSpecifier: true,
parseLeftHandSideExpression: true, parseParams: true, validateParam: true,
parseSpreadOrAssignmentExpression: true,
parseStatement: true, parseSourceElement: true, parseModuleBlock: true, parseConciseBody: true,
advanceXJSChild: true, isXJSIdentifierStart: true, isXJSIdentifierPart: true,
scanXJSStringLiteral: true, scanXJSIdentifier: true,
parseXJSAttributeValue: true, parseXJSChild: true, parseXJSElement: true, parseXJSExpressionContainer: true, parseXJSEmptyExpression: true,
parseTypeAnnotation: true, parseTypeAnnotatableIdentifier: true,
parseYieldExpression: true
*/
(function (root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
// Rhino, and plain browser loading.
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.esprima = {}));
}
}(this, function (exports) {
'use strict';
var Token,
TokenName,
FnExprTokens,
Syntax,
PropertyKind,
Messages,
Regex,
SyntaxTreeDelegate,
XHTMLEntities,
ClassPropertyType,
source,
strict,
index,
lineNumber,
lineStart,
length,
delegate,
lookahead,
state,
extra;
Token = {
BooleanLiteral: 1,
EOF: 2,
Identifier: 3,
Keyword: 4,
NullLiteral: 5,
NumericLiteral: 6,
Punctuator: 7,
StringLiteral: 8,
RegularExpression: 9,
Template: 10,
XJSIdentifier: 11,
XJSText: 12
};
TokenName = {};
TokenName[Token.BooleanLiteral] = 'Boolean';
TokenName[Token.EOF] = '<end>';
TokenName[Token.Identifier] = 'Identifier';
TokenName[Token.Keyword] = 'Keyword';
TokenName[Token.NullLiteral] = 'Null';
TokenName[Token.NumericLiteral] = 'Numeric';
TokenName[Token.Punctuator] = 'Punctuator';
TokenName[Token.StringLiteral] = 'String';
TokenName[Token.XJSIdentifier] = 'XJSIdentifier';
TokenName[Token.XJSText] = 'XJSText';
TokenName[Token.RegularExpression] = 'RegularExpression';
// A function following one of those tokens is an expression.
FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
'return', 'case', 'delete', 'throw', 'void',
// assignment operators
'=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
'&=', '|=', '^=', ',',
// binary/unary operators
'+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
'|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
'<=', '<', '>', '!=', '!=='];
Syntax = {
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrowFunctionExpression: 'ArrowFunctionExpression',
AssignmentExpression: 'AssignmentExpression',
BinaryExpression: 'BinaryExpression',
BlockStatement: 'BlockStatement',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ClassProperty: 'ClassProperty',
ComprehensionBlock: 'ComprehensionBlock',
ComprehensionExpression: 'ComprehensionExpression',
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DebuggerStatement: 'DebuggerStatement',
DoWhileStatement: 'DoWhileStatement',
EmptyStatement: 'EmptyStatement',
ExportDeclaration: 'ExportDeclaration',
ExportBatchSpecifier: 'ExportBatchSpecifier',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForInStatement: 'ForInStatement',
ForOfStatement: 'ForOfStatement',
ForStatement: 'ForStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportDeclaration: 'ImportDeclaration',
ImportSpecifier: 'ImportSpecifier',
LabeledStatement: 'LabeledStatement',
Literal: 'Literal',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MethodDefinition: 'MethodDefinition',
ModuleDeclaration: 'ModuleDeclaration',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
ObjectTypeAnnotation: 'ObjectTypeAnnotation',
OptionalParameter: 'OptionalParameter',
ParametricTypeAnnotation: 'ParametricTypeAnnotation',
ParametricallyTypedIdentifier: 'ParametricallyTypedIdentifier',
Program: 'Program',
Property: 'Property',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
SpreadProperty: 'SpreadProperty',
SwitchCase: 'SwitchCase',
SwitchStatement: 'SwitchStatement',
TaggedTemplateExpression: 'TaggedTemplateExpression',
TemplateElement: 'TemplateElement',
TemplateLiteral: 'TemplateLiteral',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TryStatement: 'TryStatement',
TypeAnnotatedIdentifier: 'TypeAnnotatedIdentifier',
TypeAnnotation: 'TypeAnnotation',
UnaryExpression: 'UnaryExpression',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
VoidTypeAnnotation: 'VoidTypeAnnotation',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
XJSIdentifier: 'XJSIdentifier',
XJSNamespacedName: 'XJSNamespacedName',
XJSMemberExpression: 'XJSMemberExpression',
XJSEmptyExpression: 'XJSEmptyExpression',
XJSExpressionContainer: 'XJSExpressionContainer',
XJSElement: 'XJSElement',
XJSClosingElement: 'XJSClosingElement',
XJSOpeningElement: 'XJSOpeningElement',
XJSAttribute: 'XJSAttribute',
XJSSpreadAttribute: 'XJSSpreadAttribute',
XJSText: 'XJSText',
YieldExpression: 'YieldExpression'
};
PropertyKind = {
Data: 1,
Get: 2,
Set: 4
};
ClassPropertyType = {
'static': 'static',
prototype: 'prototype'
};
// Error messages should be identical to V8.
Messages = {
UnexpectedToken: 'Unexpected token %0',
UnexpectedNumber: 'Unexpected number',
UnexpectedString: 'Unexpected string',
UnexpectedIdentifier: 'Unexpected identifier',
UnexpectedReserved: 'Unexpected reserved word',
UnexpectedTemplate: 'Unexpected quasi %0',
UnexpectedEOS: 'Unexpected end of input',
NewlineAfterThrow: 'Illegal newline after throw',
InvalidRegExp: 'Invalid regular expression',
UnterminatedRegExp: 'Invalid regular expression: missing /',
InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
InvalidLHSInFormalsList: 'Invalid left-hand side in formals list',
InvalidLHSInForIn: 'Invalid left-hand side in for-in',
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
NoCatchOrFinally: 'Missing catch or finally after try',
UnknownLabel: 'Undefined label \'%0\'',
Redeclaration: '%0 \'%1\' has already been declared',
IllegalContinue: 'Illegal continue statement',
IllegalBreak: 'Illegal break statement',
IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition',
IllegalReturn: 'Illegal return statement',
IllegalYield: 'Illegal yield expression',
IllegalSpread: 'Illegal spread element',
StrictModeWith: 'Strict mode code may not include a with statement',
StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
StrictVarName: 'Variable name may not be eval or arguments in strict mode',
StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list',
DefaultRestParameter: 'Rest parameter can not have a default value',
ElementAfterSpreadElement: 'Spread must be the final element of an element list',
PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal',
ObjectPatternAsRestParameter: 'Invalid rest parameter',
ObjectPatternAsSpread: 'Invalid spread argument',
StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
StrictDelete: 'Delete of an unqualified identifier in strict mode.',
StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
StrictReservedWord: 'Use of future reserved word in strict mode',
NewlineAfterModule: 'Illegal newline after module',
NoFromAfterImport: 'Missing from after import',
InvalidModuleSpecifier: 'Invalid module specifier',
NestedModule: 'Module declaration can not be nested',
NoUnintializedConst: 'Const must be initialized',
ComprehensionRequiresBlock: 'Comprehension must have at least one block',
ComprehensionError: 'Comprehension Error',
EachNotAllowed: 'Each is not supported',
InvalidXJSAttributeValue: 'XJS value should be either an expression or a quoted XJS text',
ExpectedXJSClosingTag: 'Expected corresponding XJS closing tag for %0',
AdjacentXJSElements: 'Adjacent XJS elements must be wrapped in an enclosing tag'
};
// See also tools/generate-unicode-regex.py.
Regex = {
NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')
};
// Ensure the condition is true, otherwise throw an error.
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.
function assert(condition, message) {
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
function isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0..9
}
function isHexDigit(ch) {
return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
}
function isOctalDigit(ch) {
return '01234567'.indexOf(ch) >= 0;
}
// 7.2 White Space
function isWhiteSpace(ch) {
return (ch === 32) || // space
(ch === 9) || // tab
(ch === 0xB) ||
(ch === 0xC) ||
(ch === 0xA0) ||
(ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0);
}
// 7.3 Line Terminators
function isLineTerminator(ch) {
return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029);
}
// 7.6 Identifier Names and Identifiers
function isIdentifierStart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
}
function isIdentifierPart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch >= 48 && ch <= 57) || // 0..9
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
}
// 7.6.1.2 Future Reserved Words
function isFutureReservedWord(id) {
switch (id) {
case 'class':
case 'enum':
case 'export':
case 'extends':
case 'import':
case 'super':
return true;
default:
return false;
}
}
function isStrictModeReservedWord(id) {
switch (id) {
case 'implements':
case 'interface':
case 'package':
case 'private':
case 'protected':
case 'public':
case 'static':
case 'yield':
case 'let':
return true;
default:
return false;
}
}
function isRestrictedWord(id) {
return id === 'eval' || id === 'arguments';
}
// 7.6.1.1 Keywords
function isKeyword(id) {
if (strict && isStrictModeReservedWord(id)) {
return true;
}
// 'const' is specialized as Keyword in V8.
// 'yield' is only treated as a keyword in strict mode.
// 'let' is for compatiblity with SpiderMonkey and ES.next.
// Some others are from future reserved words.
switch (id.length) {
case 2:
return (id === 'if') || (id === 'in') || (id === 'do');
case 3:
return (id === 'var') || (id === 'for') || (id === 'new') ||
(id === 'try') || (id === 'let');
case 4:
return (id === 'this') || (id === 'else') || (id === 'case') ||
(id === 'void') || (id === 'with') || (id === 'enum');
case 5:
return (id === 'while') || (id === 'break') || (id === 'catch') ||
(id === 'throw') || (id === 'const') ||
(id === 'class') || (id === 'super');
case 6:
return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
(id === 'switch') || (id === 'export') || (id === 'import');
case 7:
return (id === 'default') || (id === 'finally') || (id === 'extends');
case 8:
return (id === 'function') || (id === 'continue') || (id === 'debugger');
case 10:
return (id === 'instanceof');
default:
return false;
}
}
// 7.4 Comments
function skipComment() {
var ch, blockComment, lineComment;
blockComment = false;
lineComment = false;
while (index < length) {
ch = source.charCodeAt(index);
if (lineComment) {
++index;
if (isLineTerminator(ch)) {
lineComment = false;
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
}
} else if (blockComment) {
if (isLineTerminator(ch)) {
if (ch === 13) {
++index;
}
if (ch !== 13 || source.charCodeAt(index) === 10) {
++lineNumber;
++index;
lineStart = index;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
} else {
ch = source.charCodeAt(index++);
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// Block comment ends with '*/' (char #42, char #47).
if (ch === 42) {
ch = source.charCodeAt(index);
if (ch === 47) {
++index;
blockComment = false;
}
}
}
} else if (ch === 47) {
ch = source.charCodeAt(index + 1);
// Line comment starts with '//' (char #47, char #47).
if (ch === 47) {
index += 2;
lineComment = true;
} else if (ch === 42) {
// Block comment starts with '/*' (char #47, char #42).
index += 2;
blockComment = true;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
break;
}
} else if (isWhiteSpace(ch)) {
++index;
} else if (isLineTerminator(ch)) {
++index;
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
} else {
break;
}
}
}
function scanHexEscape(prefix) {
var i, len, ch, code = 0;
len = (prefix === 'u') ? 4 : 2;
for (i = 0; i < len; ++i) {
if (index < length && isHexDigit(source[index])) {
ch = source[index++];
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
} else {
return '';
}
}
return String.fromCharCode(code);
}
function scanUnicodeCodePointEscape() {
var ch, code, cu1, cu2;
ch = source[index];
code = 0;
// At least, one hex digit is required.
if (ch === '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
while (index < length) {
ch = source[index++];
if (!isHexDigit(ch)) {
break;
}
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
}
if (code > 0x10FFFF || ch !== '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// UTF-16 Encoding
if (code <= 0xFFFF) {
return String.fromCharCode(code);
}
cu1 = ((code - 0x10000) >> 10) + 0xD800;
cu2 = ((code - 0x10000) & 1023) + 0xDC00;
return String.fromCharCode(cu1, cu2);
}
function getEscapedIdentifier() {
var ch, id;
ch = source.charCodeAt(index++);
id = String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id = ch;
}
while (index < length) {
ch = source.charCodeAt(index);
if (!isIdentifierPart(ch)) {
break;
}
++index;
id += String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
id = id.substr(0, id.length - 1);
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id += ch;
}
}
return id;
}
function getIdentifier() {
var start, ch;
start = index++;
while (index < length) {
ch = source.charCodeAt(index);
if (ch === 92) {
// Blackslash (char #92) marks Unicode escape sequence.
index = start;
return getEscapedIdentifier();
}
if (isIdentifierPart(ch)) {
++index;
} else {
break;
}
}
return source.slice(start, index);
}
function scanIdentifier() {
var start, id, type;
start = index;
// Backslash (char #92) starts an escaped character.
id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier();
// There is no keyword or literal with only one character.
// Thus, it must be an identifier.
if (id.length === 1) {
type = Token.Identifier;
} else if (isKeyword(id)) {
type = Token.Keyword;
} else if (id === 'null') {
type = Token.NullLiteral;
} else if (id === 'true' || id === 'false') {
type = Token.BooleanLiteral;
} else {
type = Token.Identifier;
}
return {
type: type,
value: id,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.7 Punctuators
function scanPunctuator() {
var start = index,
code = source.charCodeAt(index),
code2,
ch1 = source[index],
ch2,
ch3,
ch4;
switch (code) {
// Check for most common single-character punctuators.
case 40: // ( open bracket
case 41: // ) close bracket
case 59: // ; semicolon
case 44: // , comma
case 123: // { open curly brace
case 125: // } close curly brace
case 91: // [
case 93: // ]
case 58: // :
case 63: // ?
case 126: // ~
++index;
if (extra.tokenize) {
if (code === 40) {
extra.openParenToken = extra.tokens.length;
} else if (code === 123) {
extra.openCurlyToken = extra.tokens.length;
}
}
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
code2 = source.charCodeAt(index + 1);
// '=' (char #61) marks an assignment or comparison operator.
if (code2 === 61) {
switch (code) {
case 37: // %
case 38: // &
case 42: // *:
case 43: // +
case 45: // -
case 47: // /
case 60: // <
case 62: // >
case 94: // ^
case 124: // |
index += 2;
return {
type: Token.Punctuator,
value: String.fromCharCode(code) + String.fromCharCode(code2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
case 33: // !
case 61: // =
index += 2;
// !== and ===
if (source.charCodeAt(index) === 61) {
++index;
}
return {
type: Token.Punctuator,
value: source.slice(start, index),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
break;
}
}
break;
}
// Peek more characters.
ch2 = source[index + 1];
ch3 = source[index + 2];
ch4 = source[index + 3];
// 4-character punctuator: >>>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
if (ch4 === '=') {
index += 4;
return {
type: Token.Punctuator,
value: '>>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
}
// 3-character punctuators: === !== >>> <<= >>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
index += 3;
return {
type: Token.Punctuator,
value: '>>>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '<<=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.' && ch2 === '.' && ch3 === '.') {
index += 3;
return {
type: Token.Punctuator,
value: '...',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// Other 2-character punctuators: ++ -- << >> && ||
if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) {
index += 2;
return {
type: Token.Punctuator,
value: ch1 + ch2,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '=' && ch2 === '>') {
index += 2;
return {
type: Token.Punctuator,
value: '=>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.') {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// 7.8.3 Numeric Literals
function scanHexLiteral(start) {
var number = '';
while (index < length) {
if (!isHexDigit(source[index])) {
break;
}
number += source[index++];
}
if (number.length === 0) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt('0x' + number, 16),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanOctalLiteral(prefix, start) {
var number, octal;
if (isOctalDigit(prefix)) {
octal = true;
number = '0' + source[index++];
} else {
octal = false;
++index;
number = '';
}
while (index < length) {
if (!isOctalDigit(source[index])) {
break;
}
number += source[index++];
}
if (!octal && number.length === 0) {
// only 0o or 0O
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 8),
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanNumericLiteral() {
var number, start, ch, octal;
ch = source[index];
assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
'Numeric literal must start with a decimal digit or a decimal point');
start = index;
number = '';
if (ch !== '.') {
number = source[index++];
ch = source[index];
// Hex number starts with '0x'.
// Octal number starts with '0'.
// Octal number in ES6 starts with '0o'.
// Binary number in ES6 starts with '0b'.
if (number === '0') {
if (ch === 'x' || ch === 'X') {
++index;
return scanHexLiteral(start);
}
if (ch === 'b' || ch === 'B') {
++index;
number = '';
while (index < length) {
ch = source[index];
if (ch !== '0' && ch !== '1') {
break;
}
number += source[index++];
}
if (number.length === 0) {
// only 0b or 0B
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (index < length) {
ch = source.charCodeAt(index);
if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) {
return scanOctalLiteral(ch, start);
}
// decimal number starts with '0' such as '09' is illegal.
if (ch && isDecimalDigit(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === '.') {
number += source[index++];
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === 'e' || ch === 'E') {
number += source[index++];
ch = source[index];
if (ch === '+' || ch === '-') {
number += source[index++];
}
if (isDecimalDigit(source.charCodeAt(index))) {
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
} else {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseFloat(number),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.8.4 String Literals
function scanStringLiteral() {
var str = '', quote, start, ch, code, unescaped, restore, octal = false;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === quote) {
quote = '';
break;
} else if (ch === '\\') {
ch = source[index++];
if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
str += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
str += unescaped;
} else {
index = restore;
str += ch;
}
}
break;
case 'b':
str += '\b';
break;
case 'f':
str += '\f';
break;
case 'v':
str += '\x0B';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
str += String.fromCharCode(code);
} else {
str += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
break;
} else {
str += ch;
}
}
if (quote !== '') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.StringLiteral,
value: str,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplate() {
var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal;
terminated = false;
tail = false;
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === '`') {
tail = true;
terminated = true;
break;
} else if (ch === '$') {
if (source[index] === '{') {
++index;
terminated = true;
break;
}
cooked += ch;
} else if (ch === '\\') {
ch = source[index++];
if (!isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
cooked += '\n';
break;
case 'r':
cooked += '\r';
break;
case 't':
cooked += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
cooked += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
cooked += unescaped;
} else {
index = restore;
cooked += ch;
}
}
break;
case 'b':
cooked += '\b';
break;
case 'f':
cooked += '\f';
break;
case 'v':
cooked += '\v';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
cooked += String.fromCharCode(code);
} else {
cooked += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
cooked += '\n';
} else {
cooked += ch;
}
}
if (!terminated) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.Template,
value: {
cooked: cooked,
raw: source.slice(start + 1, index - ((tail) ? 1 : 2))
},
tail: tail,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplateElement(option) {
var startsWith, template;
lookahead = null;
skipComment();
startsWith = (option.head) ? '`' : '}';
if (source[index] !== startsWith) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
template = scanTemplate();
peek();
return template;
}
function scanRegExp() {
var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false;
lookahead = null;
skipComment();
start = index;
ch = source[index];
assert(ch === '/', 'Regular expression literal must start with a slash');
str = source[index++];
while (index < length) {
ch = source[index++];
str += ch;
if (classMarker) {
if (ch === ']') {
classMarker = false;
}
} else {
if (ch === '\\') {
ch = source[index++];
// ECMA-262 7.8.5
if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
}
str += ch;
} else if (ch === '/') {
terminated = true;
break;
} else if (ch === '[') {
classMarker = true;
} else if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
}
}
}
if (!terminated) {
throwError({}, Messages.UnterminatedRegExp);
}
// Exclude leading and trailing slash.
pattern = str.substr(1, str.length - 2);
flags = '';
while (index < length) {
ch = source[index];
if (!isIdentifierPart(ch.charCodeAt(0))) {
break;
}
++index;
if (ch === '\\' && index < length) {
ch = source[index];
if (ch === 'u') {
++index;
restore = index;
ch = scanHexEscape('u');
if (ch) {
flags += ch;
for (str += '\\u'; restore < index; ++restore) {
str += source[restore];
}
} else {
index = restore;
flags += 'u';
str += '\\u';
}
} else {
str += '\\';
}
} else {
flags += ch;
str += ch;
}
}
try {
value = new RegExp(pattern, flags);
} catch (e) {
throwError({}, Messages.InvalidRegExp);
}
peek();
if (extra.tokenize) {
return {
type: Token.RegularExpression,
value: value,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
return {
literal: str,
value: value,
range: [start, index]
};
}
function isIdentifierName(token) {
return token.type === Token.Identifier ||
token.type === Token.Keyword ||
token.type === Token.BooleanLiteral ||
token.type === Token.NullLiteral;
}
function advanceSlash() {
var prevToken,
checkToken;
// Using the following algorithm:
// https://github.com/mozilla/sweet.js/wiki/design
prevToken = extra.tokens[extra.tokens.length - 1];
if (!prevToken) {
// Nothing before that: it cannot be a division.
return scanRegExp();
}
if (prevToken.type === 'Punctuator') {
if (prevToken.value === ')') {
checkToken = extra.tokens[extra.openParenToken - 1];
if (checkToken &&
checkToken.type === 'Keyword' &&
(checkToken.value === 'if' ||
checkToken.value === 'while' ||
checkToken.value === 'for' ||
checkToken.value === 'with')) {
return scanRegExp();
}
return scanPunctuator();
}
if (prevToken.value === '}') {
// Dividing a function by anything makes little sense,
// but we have to check for that.
if (extra.tokens[extra.openCurlyToken - 3] &&
extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
// Anonymous function.
checkToken = extra.tokens[extra.openCurlyToken - 4];
if (!checkToken) {
return scanPunctuator();
}
} else if (extra.tokens[extra.openCurlyToken - 4] &&
extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
// Named function.
checkToken = extra.tokens[extra.openCurlyToken - 5];
if (!checkToken) {
return scanRegExp();
}
} else {
return scanPunctuator();
}
// checkToken determines whether the function is
// a declaration or an expression.
if (FnExprTokens.indexOf(checkToken.value) >= 0) {
// It is an expression.
return scanPunctuator();
}
// It is a declaration.
return scanRegExp();
}
return scanRegExp();
}
if (prevToken.type === 'Keyword') {
return scanRegExp();
}
return scanPunctuator();
}
function advance() {
var ch;
if (!state.inXJSChild) {
skipComment();
}
if (index >= length) {
return {
type: Token.EOF,
lineNumber: lineNumber,
lineStart: lineStart,
range: [index, index]
};
}
if (state.inXJSChild) {
return advanceXJSChild();
}
ch = source.charCodeAt(index);
// Very common: ( and ) and ;
if (ch === 40 || ch === 41 || ch === 58) {
return scanPunctuator();
}
// String literal starts with single quote (#39) or double quote (#34).
if (ch === 39 || ch === 34) {
if (state.inXJSTag) {
return scanXJSStringLiteral();
}
return scanStringLiteral();
}
if (state.inXJSTag && isXJSIdentifierStart(ch)) {
return scanXJSIdentifier();
}
if (ch === 96) {
return scanTemplate();
}
if (isIdentifierStart(ch)) {
return scanIdentifier();
}
// Dot (.) char #46 can also start a floating-point number, hence the need
// to check the next character.
if (ch === 46) {
if (isDecimalDigit(source.charCodeAt(index + 1))) {
return scanNumericLiteral();
}
return scanPunctuator();
}
if (isDecimalDigit(ch)) {
return scanNumericLiteral();
}
// Slash (/) char #47 can also start a regex.
if (extra.tokenize && ch === 47) {
return advanceSlash();
}
return scanPunctuator();
}
function lex() {
var token;
token = lookahead;
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
lookahead = advance();
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
return token;
}
function peek() {
var pos, line, start;
pos = index;
line = lineNumber;
start = lineStart;
lookahead = advance();
index = pos;
lineNumber = line;
lineStart = start;
}
function lookahead2() {
var adv, pos, line, start, result;
// If we are collecting the tokens, don't grab the next one yet.
adv = (typeof extra.advance === 'function') ? extra.advance : advance;
pos = index;
line = lineNumber;
start = lineStart;
// Scan for the next immediate token.
if (lookahead === null) {
lookahead = adv();
}
index = lookahead.range[1];
lineNumber = lookahead.lineNumber;
lineStart = lookahead.lineStart;
// Grab the token right after.
result = adv();
index = pos;
lineNumber = line;
lineStart = start;
return result;
}
function markerCreate() {
if (!extra.loc && !extra.range) {
return undefined;
}
skipComment();
return {offset: index, line: lineNumber, col: index - lineStart};
}
function markerCreatePreserveWhitespace() {
if (!extra.loc && !extra.range) {
return undefined;
}
return {offset: index, line: lineNumber, col: index - lineStart};
}
function processComment(node) {
var lastChild,
trailingComments,
bottomRight = extra.bottomRightStack,
last = bottomRight[bottomRight.length - 1];
if (node.type === Syntax.Program) {
if (node.body.length > 0) {
return;
}
}
if (extra.trailingComments.length > 0) {
if (extra.trailingComments[0].range[0] >= node.range[1]) {
trailingComments = extra.trailingComments;
extra.trailingComments = [];
} else {
extra.trailingComments.length = 0;
}
} else {
if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) {
trailingComments = last.trailingComments;
delete last.trailingComments;
}
}
// Eating the stack.
if (last) {
while (last && last.range[0] >= node.range[0]) {
lastChild = last;
last = bottomRight.pop();
}
}
if (lastChild) {
if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
node.leadingComments = lastChild.leadingComments;
delete lastChild.leadingComments;
}
} else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
node.leadingComments = extra.leadingComments;
extra.leadingComments = [];
}
if (trailingComments) {
node.trailingComments = trailingComments;
}
bottomRight.push(node);
}
function markerApply(marker, node) {
if (extra.range) {
node.range = [marker.offset, index];
}
if (extra.loc) {
node.loc = {
start: {
line: marker.line,
column: marker.col
},
end: {
line: lineNumber,
column: index - lineStart
}
};
node = delegate.postProcess(node);
}
if (extra.attachComment) {
processComment(node);
}
return node;
}
SyntaxTreeDelegate = {
name: 'SyntaxTree',
postProcess: function (node) {
return node;
},
createArrayExpression: function (elements) {
return {
type: Syntax.ArrayExpression,
elements: elements
};
},
createAssignmentExpression: function (operator, left, right) {
return {
type: Syntax.AssignmentExpression,
operator: operator,
left: left,
right: right
};
},
createBinaryExpression: function (operator, left, right) {
var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :
Syntax.BinaryExpression;
return {
type: type,
operator: operator,
left: left,
right: right
};
},
createBlockStatement: function (body) {
return {
type: Syntax.BlockStatement,
body: body
};
},
createBreakStatement: function (label) {
return {
type: Syntax.BreakStatement,
label: label
};
},
createCallExpression: function (callee, args) {
return {
type: Syntax.CallExpression,
callee: callee,
'arguments': args
};
},
createCatchClause: function (param, body) {
return {
type: Syntax.CatchClause,
param: param,
body: body
};
},
createConditionalExpression: function (test, consequent, alternate) {
return {
type: Syntax.ConditionalExpression,
test: test,
consequent: consequent,
alternate: alternate
};
},
createContinueStatement: function (label) {
return {
type: Syntax.ContinueStatement,
label: label
};
},
createDebuggerStatement: function () {
return {
type: Syntax.DebuggerStatement
};
},
createDoWhileStatement: function (body, test) {
return {
type: Syntax.DoWhileStatement,
body: body,
test: test
};
},
createEmptyStatement: function () {
return {
type: Syntax.EmptyStatement
};
},
createExpressionStatement: function (expression) {
return {
type: Syntax.ExpressionStatement,
expression: expression
};
},
createForStatement: function (init, test, update, body) {
return {
type: Syntax.ForStatement,
init: init,
test: test,
update: update,
body: body
};
},
createForInStatement: function (left, right, body) {
return {
type: Syntax.ForInStatement,
left: left,
right: right,
body: body,
each: false
};
},
createForOfStatement: function (left, right, body) {
return {
type: Syntax.ForOfStatement,
left: left,
right: right,
body: body
};
},
createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression,
returnType, parametricType) {
return {
type: Syntax.FunctionDeclaration,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType,
parametricType: parametricType
};
},
createFunctionExpression: function (id, params, defaults, body, rest, generator, expression,
returnType, parametricType) {
return {
type: Syntax.FunctionExpression,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType,
parametricType: parametricType
};
},
createIdentifier: function (name) {
return {
type: Syntax.Identifier,
name: name,
// Only here to initialize the shape of the object to ensure
// that the 'typeAnnotation' key is ordered before others that
// are added later (like 'loc' and 'range'). This just helps
// keep the shape of Identifier nodes consistent with everything
// else.
typeAnnotation: undefined
};
},
createTypeAnnotation: function (typeIdentifier, parametricType, params, returnType, nullable) {
return {
type: Syntax.TypeAnnotation,
id: typeIdentifier,
parametricType: parametricType,
params: params,
returnType: returnType,
nullable: nullable
};
},
createParametricTypeAnnotation: function (parametricTypes) {
return {
type: Syntax.ParametricTypeAnnotation,
params: parametricTypes
};
},
createVoidTypeAnnotation: function () {
return {
type: Syntax.VoidTypeAnnotation
};
},
createObjectTypeAnnotation: function (properties, nullable) {
return {
type: Syntax.ObjectTypeAnnotation,
properties: properties,
nullable: nullable
};
},
createTypeAnnotatedIdentifier: function (identifier, annotation, isOptionalParam) {
return {
type: Syntax.TypeAnnotatedIdentifier,
id: identifier,
annotation: annotation
};
},
createOptionalParameter: function (identifier) {
return {
type: Syntax.OptionalParameter,
id: identifier
};
},
createXJSAttribute: function (name, value) {
return {
type: Syntax.XJSAttribute,
name: name,
value: value || null
};
},
createXJSSpreadAttribute: function (argument) {
return {
type: Syntax.XJSSpreadAttribute,
argument: argument
};
},
createXJSIdentifier: function (name) {
return {
type: Syntax.XJSIdentifier,
name: name
};
},
createXJSNamespacedName: function (namespace, name) {
return {
type: Syntax.XJSNamespacedName,
namespace: namespace,
name: name
};
},
createXJSMemberExpression: function (object, property) {
return {
type: Syntax.XJSMemberExpression,
object: object,
property: property
};
},
createXJSElement: function (openingElement, closingElement, children) {
return {
type: Syntax.XJSElement,
openingElement: openingElement,
closingElement: closingElement,
children: children
};
},
createXJSEmptyExpression: function () {
return {
type: Syntax.XJSEmptyExpression
};
},
createXJSExpressionContainer: function (expression) {
return {
type: Syntax.XJSExpressionContainer,
expression: expression
};
},
createXJSOpeningElement: function (name, attributes, selfClosing) {
return {
type: Syntax.XJSOpeningElement,
name: name,
selfClosing: selfClosing,
attributes: attributes
};
},
createXJSClosingElement: function (name) {
return {
type: Syntax.XJSClosingElement,
name: name
};
},
createIfStatement: function (test, consequent, alternate) {
return {
type: Syntax.IfStatement,
test: test,
consequent: consequent,
alternate: alternate
};
},
createLabeledStatement: function (label, body) {
return {
type: Syntax.LabeledStatement,
label: label,
body: body
};
},
createLiteral: function (token) {
return {
type: Syntax.Literal,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
},
createMemberExpression: function (accessor, object, property) {
return {
type: Syntax.MemberExpression,
computed: accessor === '[',
object: object,
property: property
};
},
createNewExpression: function (callee, args) {
return {
type: Syntax.NewExpression,
callee: callee,
'arguments': args
};
},
createObjectExpression: function (properties) {
return {
type: Syntax.ObjectExpression,
properties: properties
};
},
createPostfixExpression: function (operator, argument) {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: false
};
},
createProgram: function (body) {
return {
type: Syntax.Program,
body: body
};
},
createProperty: function (kind, key, value, method, shorthand, computed) {
return {
type: Syntax.Property,
key: key,
value: value,
kind: kind,
method: method,
shorthand: shorthand,
computed: computed
};
},
createReturnStatement: function (argument) {
return {
type: Syntax.ReturnStatement,
argument: argument
};
},
createSequenceExpression: function (expressions) {
return {
type: Syntax.SequenceExpression,
expressions: expressions
};
},
createSwitchCase: function (test, consequent) {
return {
type: Syntax.SwitchCase,
test: test,
consequent: consequent
};
},
createSwitchStatement: function (discriminant, cases) {
return {
type: Syntax.SwitchStatement,
discriminant: discriminant,
cases: cases
};
},
createThisExpression: function () {
return {
type: Syntax.ThisExpression
};
},
createThrowStatement: function (argument) {
return {
type: Syntax.ThrowStatement,
argument: argument
};
},
createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
return {
type: Syntax.TryStatement,
block: block,
guardedHandlers: guardedHandlers,
handlers: handlers,
finalizer: finalizer
};
},
createUnaryExpression: function (operator, argument) {
if (operator === '++' || operator === '--') {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: true
};
}
return {
type: Syntax.UnaryExpression,
operator: operator,
argument: argument,
prefix: true
};
},
createVariableDeclaration: function (declarations, kind) {
return {
type: Syntax.VariableDeclaration,
declarations: declarations,
kind: kind
};
},
createVariableDeclarator: function (id, init) {
return {
type: Syntax.VariableDeclarator,
id: id,
init: init
};
},
createWhileStatement: function (test, body) {
return {
type: Syntax.WhileStatement,
test: test,
body: body
};
},
createWithStatement: function (object, body) {
return {
type: Syntax.WithStatement,
object: object,
body: body
};
},
createTemplateElement: function (value, tail) {
return {
type: Syntax.TemplateElement,
value: value,
tail: tail
};
},
createTemplateLiteral: function (quasis, expressions) {
return {
type: Syntax.TemplateLiteral,
quasis: quasis,
expressions: expressions
};
},
createSpreadElement: function (argument) {
return {
type: Syntax.SpreadElement,
argument: argument
};
},
createSpreadProperty: function (argument) {
return {
type: Syntax.SpreadProperty,
argument: argument
};
},
createTaggedTemplateExpression: function (tag, quasi) {
return {
type: Syntax.TaggedTemplateExpression,
tag: tag,
quasi: quasi
};
},
createArrowFunctionExpression: function (params, defaults, body, rest, expression) {
return {
type: Syntax.ArrowFunctionExpression,
id: null,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: false,
expression: expression
};
},
createMethodDefinition: function (propertyType, kind, key, value) {
return {
type: Syntax.MethodDefinition,
key: key,
value: value,
kind: kind,
'static': propertyType === ClassPropertyType["static"]
};
},
createClassProperty: function (propertyIdentifier) {
return {
type: Syntax.ClassProperty,
id: propertyIdentifier
};
},
createClassBody: function (body) {
return {
type: Syntax.ClassBody,
body: body
};
},
createClassExpression: function (id, superClass, body, parametricType) {
return {
type: Syntax.ClassExpression,
id: id,
superClass: superClass,
body: body,
parametricType: parametricType
};
},
createClassDeclaration: function (id, superClass, body, parametricType, superParametricType) {
return {
type: Syntax.ClassDeclaration,
id: id,
superClass: superClass,
body: body,
parametricType: parametricType,
superParametricType: superParametricType
};
},
createExportSpecifier: function (id, name) {
return {
type: Syntax.ExportSpecifier,
id: id,
name: name
};
},
createExportBatchSpecifier: function () {
return {
type: Syntax.ExportBatchSpecifier
};
},
createExportDeclaration: function (declaration, specifiers, source) {
return {
type: Syntax.ExportDeclaration,
declaration: declaration,
specifiers: specifiers,
source: source
};
},
createImportSpecifier: function (id, name) {
return {
type: Syntax.ImportSpecifier,
id: id,
name: name
};
},
createImportDeclaration: function (specifiers, kind, source) {
return {
type: Syntax.ImportDeclaration,
specifiers: specifiers,
kind: kind,
source: source
};
},
createYieldExpression: function (argument, delegate) {
return {
type: Syntax.YieldExpression,
argument: argument,
delegate: delegate
};
},
createModuleDeclaration: function (id, source, body) {
return {
type: Syntax.ModuleDeclaration,
id: id,
source: source,
body: body
};
},
createComprehensionExpression: function (filter, blocks, body) {
return {
type: Syntax.ComprehensionExpression,
filter: filter,
blocks: blocks,
body: body
};
}
};
// Return true if there is a line terminator before the next token.
function peekLineTerminator() {
var pos, line, start, found;
pos = index;
line = lineNumber;
start = lineStart;
skipComment();
found = lineNumber !== line;
index = pos;
lineNumber = line;
lineStart = start;
return found;
}
// Throw an exception
function throwError(token, messageFormat) {
var error,
args = Array.prototype.slice.call(arguments, 2),
msg = messageFormat.replace(
/%(\d)/g,
function (whole, index) {
assert(index < args.length, 'Message reference must be in range');
return args[index];
}
);
if (typeof token.lineNumber === 'number') {
error = new Error('Line ' + token.lineNumber + ': ' + msg);
error.index = token.range[0];
error.lineNumber = token.lineNumber;
error.column = token.range[0] - lineStart + 1;
} else {
error = new Error('Line ' + lineNumber + ': ' + msg);
error.index = index;
error.lineNumber = lineNumber;
error.column = index - lineStart + 1;
}
error.description = msg;
throw error;
}
function throwErrorTolerant() {
try {
throwError.apply(null, arguments);
} catch (e) {
if (extra.errors) {
extra.errors.push(e);
} else {
throw e;
}
}
}
// Throw an exception because of the token.
function throwUnexpected(token) {
if (token.type === Token.EOF) {
throwError(token, Messages.UnexpectedEOS);
}
if (token.type === Token.NumericLiteral) {
throwError(token, Messages.UnexpectedNumber);
}
if (token.type === Token.StringLiteral || token.type === Token.XJSText) {
throwError(token, Messages.UnexpectedString);
}
if (token.type === Token.Identifier) {
throwError(token, Messages.UnexpectedIdentifier);
}
if (token.type === Token.Keyword) {
if (isFutureReservedWord(token.value)) {
throwError(token, Messages.UnexpectedReserved);
} else if (strict && isStrictModeReservedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictReservedWord);
return;
}
throwError(token, Messages.UnexpectedToken, token.value);
}
if (token.type === Token.Template) {
throwError(token, Messages.UnexpectedTemplate, token.value.raw);
}
// BooleanLiteral, NullLiteral, or Punctuator.
throwError(token, Messages.UnexpectedToken, token.value);
}
// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.
function expect(value) {
var token = lex();
if (token.type !== Token.Punctuator || token.value !== value) {
throwUnexpected(token);
}
}
// Expect the next token to match the specified keyword.
// If not, an exception will be thrown.
function expectKeyword(keyword) {
var token = lex();
if (token.type !== Token.Keyword || token.value !== keyword) {
throwUnexpected(token);
}
}
// Return true if the next token matches the specified punctuator.
function match(value) {
return lookahead.type === Token.Punctuator && lookahead.value === value;
}
// Return true if the next token matches the specified keyword
function matchKeyword(keyword) {
return lookahead.type === Token.Keyword && lookahead.value === keyword;
}
// Return true if the next token matches the specified contextual keyword
function matchContextualKeyword(keyword) {
return lookahead.type === Token.Identifier && lookahead.value === keyword;
}
// Return true if the next token is an assignment operator
function matchAssign() {
var op;
if (lookahead.type !== Token.Punctuator) {
return false;
}
op = lookahead.value;
return op === '=' ||
op === '*=' ||
op === '/=' ||
op === '%=' ||
op === '+=' ||
op === '-=' ||
op === '<<=' ||
op === '>>=' ||
op === '>>>=' ||
op === '&=' ||
op === '^=' ||
op === '|=';
}
function consumeSemicolon() {
var line, oldIndex = index, oldLineNumber = lineNumber,
oldLineStart = lineStart, oldLookahead = lookahead;
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
return;
}
line = lineNumber;
skipComment();
if (lineNumber !== line) {
index = oldIndex;
lineNumber = oldLineNumber;
lineStart = oldLineStart;
lookahead = oldLookahead;
return;
}
if (match(';')) {
lex();
return;
}
if (lookahead.type !== Token.EOF && !match('}')) {
throwUnexpected(lookahead);
}
}
// Return true if provided expression is LeftHandSideExpression
function isLeftHandSide(expr) {
return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
}
function isAssignableLeftHandSide(expr) {
return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern;
}
// 11.1.4 Array Initialiser
function parseArrayInitialiser() {
var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, body,
marker = markerCreate();
expect('[');
while (!match(']')) {
if (lookahead.value === 'for' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
matchKeyword('for');
tmp = parseForStatement({ignoreBody: true});
tmp.of = tmp.type === Syntax.ForOfStatement;
tmp.type = Syntax.ComprehensionBlock;
if (tmp.left.kind) { // can't be let or const
throwError({}, Messages.ComprehensionError);
}
blocks.push(tmp);
} else if (lookahead.value === 'if' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
expectKeyword('if');
expect('(');
filter = parseExpression();
expect(')');
} else if (lookahead.value === ',' &&
lookahead.type === Token.Punctuator) {
possiblecomprehension = false; // no longer allowed.
lex();
elements.push(null);
} else {
tmp = parseSpreadOrAssignmentExpression();
elements.push(tmp);
if (tmp && tmp.type === Syntax.SpreadElement) {
if (!match(']')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
} else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) {
expect(','); // this lexes.
possiblecomprehension = false;
}
}
}
expect(']');
if (filter && !blocks.length) {
throwError({}, Messages.ComprehensionRequiresBlock);
}
if (blocks.length) {
if (elements.length !== 1) {
throwError({}, Messages.ComprehensionError);
}
return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0]));
}
return markerApply(marker, delegate.createArrayExpression(elements));
}
// 11.1.5 Object Initialiser
function parsePropertyFunction(options) {
var previousStrict, previousYieldAllowed, params, defaults, body,
marker = markerCreate();
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = options.generator;
params = options.params || [];
defaults = options.defaults || [];
body = parseConciseBody();
if (options.name && strict && isRestrictedWord(params[0].name)) {
throwErrorTolerant(options.name, Messages.StrictParamName);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
return markerApply(marker, delegate.createFunctionExpression(
null,
params,
defaults,
body,
options.rest || null,
options.generator,
body.type !== Syntax.BlockStatement,
options.returnType,
options.parametricType
));
}
function parsePropertyMethodFunction(options) {
var previousStrict, tmp, method;
previousStrict = strict;
strict = true;
tmp = parseParams();
if (tmp.stricted) {
throwErrorTolerant(tmp.stricted, tmp.message);
}
method = parsePropertyFunction({
params: tmp.params,
defaults: tmp.defaults,
rest: tmp.rest,
generator: options.generator,
returnType: tmp.returnType,
parametricType: options.parametricType
});
strict = previousStrict;
return method;
}
function parseObjectPropertyKey() {
var marker = markerCreate(),
token = lex(),
propertyKey,
result;
// Note: This function is called only from parseObjectProperty(), where
// EOF and Punctuator tokens are already filtered out.
if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
if (strict && token.octal) {
throwErrorTolerant(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createLiteral(token));
}
if (token.type === Token.Punctuator && token.value === '[') {
// For computed properties we should skip the [ and ], and
// capture in marker only the assignment expression itself.
marker = markerCreate();
propertyKey = parseAssignmentExpression();
result = markerApply(marker, propertyKey);
expect(']');
return result;
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseObjectProperty() {
var token, key, id, value, param, expr, computed,
marker = markerCreate();
token = lookahead;
computed = (token.value === '[');
if (token.type === Token.Identifier || computed) {
id = parseObjectPropertyKey();
// Property Assignment: Getter and Setter.
if (token.value === 'get' && !(match(':') || match('('))) {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
expect('(');
expect(')');
return markerApply(marker, delegate.createProperty('get', key, parsePropertyFunction({ generator: false }), false, false, computed));
}
if (token.value === 'set' && !(match(':') || match('('))) {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
return markerApply(marker, delegate.createProperty('set', key, parsePropertyFunction({ params: param, generator: false, name: token }), false, false, computed));
}
if (match(':')) {
lex();
return markerApply(marker, delegate.createProperty('init', id, parseAssignmentExpression(), false, false, computed));
}
if (match('(')) {
return markerApply(marker, delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: false }), true, false, computed));
}
if (computed) {
// Computed properties can only be used with full notation.
throwUnexpected(lookahead);
}
return markerApply(marker, delegate.createProperty('init', id, id, false, true, false));
}
if (token.type === Token.EOF || token.type === Token.Punctuator) {
if (!match('*')) {
throwUnexpected(token);
}
lex();
computed = (lookahead.type === Token.Punctuator && lookahead.value === '[');
id = parseObjectPropertyKey();
if (!match('(')) {
throwUnexpected(lex());
}
return markerApply(marker, delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: true }), true, false, computed));
}
key = parseObjectPropertyKey();
if (match(':')) {
lex();
return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false));
}
if (match('(')) {
return markerApply(marker, delegate.createProperty('init', key, parsePropertyMethodFunction({ generator: false }), true, false, false));
}
throwUnexpected(lex());
}
function parseObjectSpreadProperty() {
var marker = markerCreate();
expect('...');
return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression()));
}
function parseObjectInitialiser() {
var properties = [], property, name, key, kind, map = {}, toString = String,
marker = markerCreate();
expect('{');
while (!match('}')) {
if (match('...')) {
property = parseObjectSpreadProperty();
} else {
property = parseObjectProperty();
if (property.key.type === Syntax.Identifier) {
name = property.key.name;
} else {
name = toString(property.key.value);
}
kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
key = '$' + name;
if (Object.prototype.hasOwnProperty.call(map, key)) {
if (map[key] === PropertyKind.Data) {
if (strict && kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.StrictDuplicateProperty);
} else if (kind !== PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
}
} else {
if (kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
} else if (map[key] & kind) {
throwErrorTolerant({}, Messages.AccessorGetSet);
}
}
map[key] |= kind;
} else {
map[key] = kind;
}
}
properties.push(property);
if (!match('}')) {
expect(',');
}
}
expect('}');
return markerApply(marker, delegate.createObjectExpression(properties));
}
function parseTemplateElement(option) {
var marker = markerCreate(),
token = scanTemplateElement(option);
if (strict && token.octal) {
throwError(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail));
}
function parseTemplateLiteral() {
var quasi, quasis, expressions, marker = markerCreate();
quasi = parseTemplateElement({ head: true });
quasis = [ quasi ];
expressions = [];
while (!quasi.tail) {
expressions.push(parseExpression());
quasi = parseTemplateElement({ head: false });
quasis.push(quasi);
}
return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions));
}
// 11.1.6 The Grouping Operator
function parseGroupExpression() {
var expr;
expect('(');
++state.parenthesizedCount;
expr = parseExpression();
expect(')');
return expr;
}
// 11.1 Primary Expressions
function parsePrimaryExpression() {
var marker, type, token, expr;
type = lookahead.type;
if (type === Token.Identifier) {
marker = markerCreate();
return markerApply(marker, delegate.createIdentifier(lex().value));
}
if (type === Token.StringLiteral || type === Token.NumericLiteral) {
if (strict && lookahead.octal) {
throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
}
marker = markerCreate();
return markerApply(marker, delegate.createLiteral(lex()));
}
if (type === Token.Keyword) {
if (matchKeyword('this')) {
marker = markerCreate();
lex();
return markerApply(marker, delegate.createThisExpression());
}
if (matchKeyword('function')) {
return parseFunctionExpression();
}
if (matchKeyword('class')) {
return parseClassExpression();
}
if (matchKeyword('super')) {
marker = markerCreate();
lex();
return markerApply(marker, delegate.createIdentifier('super'));
}
}
if (type === Token.BooleanLiteral) {
marker = markerCreate();
token = lex();
token.value = (token.value === 'true');
return markerApply(marker, delegate.createLiteral(token));
}
if (type === Token.NullLiteral) {
marker = markerCreate();
token = lex();
token.value = null;
return markerApply(marker, delegate.createLiteral(token));
}
if (match('[')) {
return parseArrayInitialiser();
}
if (match('{')) {
return parseObjectInitialiser();
}
if (match('(')) {
return parseGroupExpression();
}
if (match('/') || match('/=')) {
marker = markerCreate();
return markerApply(marker, delegate.createLiteral(scanRegExp()));
}
if (type === Token.Template) {
return parseTemplateLiteral();
}
if (match('<')) {
return parseXJSElement();
}
throwUnexpected(lex());
}
// 11.2 Left-Hand-Side Expressions
function parseArguments() {
var args = [], arg;
expect('(');
if (!match(')')) {
while (index < length) {
arg = parseSpreadOrAssignmentExpression();
args.push(arg);
if (match(')')) {
break;
} else if (arg.type === Syntax.SpreadElement) {
throwError({}, Messages.ElementAfterSpreadElement);
}
expect(',');
}
}
expect(')');
return args;
}
function parseSpreadOrAssignmentExpression() {
if (match('...')) {
var marker = markerCreate();
lex();
return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression()));
}
return parseAssignmentExpression();
}
function parseNonComputedProperty() {
var marker = markerCreate(),
token = lex();
if (!isIdentifierName(token)) {
throwUnexpected(token);
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseNonComputedMember() {
expect('.');
return parseNonComputedProperty();
}
function parseComputedMember() {
var expr;
expect('[');
expr = parseExpression();
expect(']');
return expr;
}
function parseNewExpression() {
var callee, args, marker = markerCreate();
expectKeyword('new');
callee = parseLeftHandSideExpression();
args = match('(') ? parseArguments() : [];
return markerApply(marker, delegate.createNewExpression(callee, args));
}
function parseLeftHandSideExpressionAllowCall() {
var expr, args, marker = markerCreate();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) {
if (match('(')) {
args = parseArguments();
expr = markerApply(marker, delegate.createCallExpression(expr, args));
} else if (match('[')) {
expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
} else if (match('.')) {
expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
} else {
expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
}
}
return expr;
}
function parseLeftHandSideExpression() {
var expr, marker = markerCreate();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || lookahead.type === Token.Template) {
if (match('[')) {
expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
} else if (match('.')) {
expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
} else {
expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
}
}
return expr;
}
// 11.3 Postfix Expressions
function parsePostfixExpression() {
var marker = markerCreate(),
expr = parseLeftHandSideExpressionAllowCall(),
token;
if (lookahead.type !== Token.Punctuator) {
return expr;
}
if ((match('++') || match('--')) && !peekLineTerminator()) {
// 11.3.1, 11.3.2
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPostfix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
token = lex();
expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr));
}
return expr;
}
// 11.4 Unary Operators
function parseUnaryExpression() {
var marker, token, expr;
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
return parsePostfixExpression();
}
if (match('++') || match('--')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
// 11.4.4, 11.4.5
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPrefix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (match('+') || match('-') || match('~') || match('!')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr));
if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
throwErrorTolerant({}, Messages.StrictDelete);
}
return expr;
}
return parsePostfixExpression();
}
function binaryPrecedence(token, allowIn) {
var prec = 0;
if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
return 0;
}
switch (token.value) {
case '||':
prec = 1;
break;
case '&&':
prec = 2;
break;
case '|':
prec = 3;
break;
case '^':
prec = 4;
break;
case '&':
prec = 5;
break;
case '==':
case '!=':
case '===':
case '!==':
prec = 6;
break;
case '<':
case '>':
case '<=':
case '>=':
case 'instanceof':
prec = 7;
break;
case 'in':
prec = allowIn ? 7 : 0;
break;
case '<<':
case '>>':
case '>>>':
prec = 8;
break;
case '+':
case '-':
prec = 9;
break;
case '*':
case '/':
case '%':
prec = 11;
break;
default:
break;
}
return prec;
}
// 11.5 Multiplicative Operators
// 11.6 Additive Operators
// 11.7 Bitwise Shift Operators
// 11.8 Relational Operators
// 11.9 Equality Operators
// 11.10 Binary Bitwise Operators
// 11.11 Binary Logical Operators
function parseBinaryExpression() {
var expr, token, prec, previousAllowIn, stack, right, operator, left, i,
marker, markers;
previousAllowIn = state.allowIn;
state.allowIn = true;
marker = markerCreate();
left = parseUnaryExpression();
token = lookahead;
prec = binaryPrecedence(token, previousAllowIn);
if (prec === 0) {
return left;
}
token.prec = prec;
lex();
markers = [marker, markerCreate()];
right = parseUnaryExpression();
stack = [left, token, right];
while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) {
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
operator = stack.pop().value;
left = stack.pop();
expr = delegate.createBinaryExpression(operator, left, right);
markers.pop();
marker = markers.pop();
markerApply(marker, expr);
stack.push(expr);
markers.push(marker);
}
// Shift.
token = lex();
token.prec = prec;
stack.push(token);
markers.push(markerCreate());
expr = parseUnaryExpression();
stack.push(expr);
}
state.allowIn = previousAllowIn;
// Final reduce to clean-up the stack.
i = stack.length - 1;
expr = stack[i];
markers.pop();
while (i > 1) {
expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
i -= 2;
marker = markers.pop();
markerApply(marker, expr);
}
return expr;
}
// 11.12 Conditional Operator
function parseConditionalExpression() {
var expr, previousAllowIn, consequent, alternate, marker = markerCreate();
expr = parseBinaryExpression();
if (match('?')) {
lex();
previousAllowIn = state.allowIn;
state.allowIn = true;
consequent = parseAssignmentExpression();
state.allowIn = previousAllowIn;
expect(':');
alternate = parseAssignmentExpression();
expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate));
}
return expr;
}
// 11.13 Assignment Operators
function reinterpretAsAssignmentBindingPattern(expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.type === Syntax.SpreadProperty) {
if (i < len - 1) {
throwError({}, Messages.PropertyAfterSpreadProperty);
}
reinterpretAsAssignmentBindingPattern(property.argument);
} else {
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInAssignment);
}
reinterpretAsAssignmentBindingPattern(property.value);
}
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
if (element) {
reinterpretAsAssignmentBindingPattern(element);
}
}
} else if (expr.type === Syntax.Identifier) {
if (isRestrictedWord(expr.name)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
} else if (expr.type === Syntax.SpreadElement) {
reinterpretAsAssignmentBindingPattern(expr.argument);
if (expr.argument.type === Syntax.ObjectPattern) {
throwError({}, Messages.ObjectPatternAsSpread);
}
} else {
if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
throwError({}, Messages.InvalidLHSInAssignment);
}
}
}
function reinterpretAsDestructuredParameter(options, expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.type === Syntax.SpreadProperty) {
if (i < len - 1) {
throwError({}, Messages.PropertyAfterSpreadProperty);
}
reinterpretAsDestructuredParameter(options, property.argument);
} else {
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInFormalsList);
}
reinterpretAsDestructuredParameter(options, property.value);
}
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
if (element) {
reinterpretAsDestructuredParameter(options, element);
}
}
} else if (expr.type === Syntax.Identifier) {
validateParam(options, expr, expr.name);
} else {
if (expr.type !== Syntax.MemberExpression) {
throwError({}, Messages.InvalidLHSInFormalsList);
}
}
}
function reinterpretAsCoverFormalsList(expressions) {
var i, len, param, params, defaults, defaultCount, options, rest;
params = [];
defaults = [];
defaultCount = 0;
rest = null;
options = {
paramSet: {}
};
for (i = 0, len = expressions.length; i < len; i += 1) {
param = expressions[i];
if (param.type === Syntax.Identifier) {
params.push(param);
defaults.push(null);
validateParam(options, param, param.name);
} else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) {
reinterpretAsDestructuredParameter(options, param);
params.push(param);
defaults.push(null);
} else if (param.type === Syntax.SpreadElement) {
assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression');
reinterpretAsDestructuredParameter(options, param.argument);
rest = param.argument;
} else if (param.type === Syntax.AssignmentExpression) {
params.push(param.left);
defaults.push(param.right);
++defaultCount;
validateParam(options, param.left, param.left.name);
} else {
return null;
}
}
if (options.message === Messages.StrictParamDupe) {
throwError(
strict ? options.stricted : options.firstRestricted,
options.message
);
}
if (defaultCount === 0) {
defaults = [];
}
return {
params: params,
defaults: defaults,
rest: rest,
stricted: options.stricted,
firstRestricted: options.firstRestricted,
message: options.message
};
}
function parseArrowFunctionExpression(options, marker) {
var previousStrict, previousYieldAllowed, body;
expect('=>');
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
body = parseConciseBody();
if (strict && options.firstRestricted) {
throwError(options.firstRestricted, options.message);
}
if (strict && options.stricted) {
throwErrorTolerant(options.stricted, options.message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
return markerApply(marker, delegate.createArrowFunctionExpression(
options.params,
options.defaults,
body,
options.rest,
body.type !== Syntax.BlockStatement
));
}
function parseAssignmentExpression() {
var marker, expr, token, params, oldParenthesizedCount;
// Note that 'yield' is treated as a keyword in strict mode, but a
// contextual keyword (identifier) in non-strict mode, so we need
// to use matchKeyword and matchContextualKeyword appropriately.
if ((state.yieldAllowed && matchContextualKeyword('yield')) || (strict && matchKeyword('yield'))) {
return parseYieldExpression();
}
oldParenthesizedCount = state.parenthesizedCount;
marker = markerCreate();
if (match('(')) {
token = lookahead2();
if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') {
params = parseParams();
if (!match('=>')) {
throwUnexpected(lex());
}
return parseArrowFunctionExpression(params, marker);
}
}
token = lookahead;
expr = parseConditionalExpression();
if (match('=>') &&
(state.parenthesizedCount === oldParenthesizedCount ||
state.parenthesizedCount === (oldParenthesizedCount + 1))) {
if (expr.type === Syntax.Identifier) {
params = reinterpretAsCoverFormalsList([ expr ]);
} else if (expr.type === Syntax.SequenceExpression) {
params = reinterpretAsCoverFormalsList(expr.expressions);
}
if (params) {
return parseArrowFunctionExpression(params, marker);
}
}
if (matchAssign()) {
// 11.13.1
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant(token, Messages.StrictLHSAssignment);
}
// ES.next draf 11.13 Runtime Semantics step 1
if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) {
reinterpretAsAssignmentBindingPattern(expr);
} else if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression()));
}
return expr;
}
// 11.14 Comma Operator
function parseExpression() {
var marker, expr, expressions, sequence, coverFormalsList, spreadFound, oldParenthesizedCount;
oldParenthesizedCount = state.parenthesizedCount;
marker = markerCreate();
expr = parseAssignmentExpression();
expressions = [ expr ];
if (match(',')) {
while (index < length) {
if (!match(',')) {
break;
}
lex();
expr = parseSpreadOrAssignmentExpression();
expressions.push(expr);
if (expr.type === Syntax.SpreadElement) {
spreadFound = true;
if (!match(')')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
break;
}
}
sequence = markerApply(marker, delegate.createSequenceExpression(expressions));
}
if (match('=>')) {
// Do not allow nested parentheses on the LHS of the =>.
if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) {
expr = expr.type === Syntax.SequenceExpression ? expr.expressions : expressions;
coverFormalsList = reinterpretAsCoverFormalsList(expr);
if (coverFormalsList) {
return parseArrowFunctionExpression(coverFormalsList, marker);
}
}
throwUnexpected(lex());
}
if (spreadFound && lookahead2().value !== '=>') {
throwError({}, Messages.IllegalSpread);
}
return sequence || expr;
}
// 12.1 Block
function parseStatementList() {
var list = [],
statement;
while (index < length) {
if (match('}')) {
break;
}
statement = parseSourceElement();
if (typeof statement === 'undefined') {
break;
}
list.push(statement);
}
return list;
}
function parseBlock() {
var block, marker = markerCreate();
expect('{');
block = parseStatementList();
expect('}');
return markerApply(marker, delegate.createBlockStatement(block));
}
// 12.2 Variable Statement
function parseObjectTypeAnnotation(nullable) {
var isMethod, marker, properties = [], property, propertyKey,
propertyTypeAnnotation;
expect('{');
while (!match('}')) {
marker = markerCreate();
propertyKey = parseObjectPropertyKey();
isMethod = match('(');
propertyTypeAnnotation = parseTypeAnnotation();
properties.push(markerApply(marker, delegate.createProperty(
'init',
propertyKey,
propertyTypeAnnotation,
isMethod,
false
)));
if (!match('}')) {
if (match(',') || match(';')) {
lex();
} else {
throwUnexpected(lookahead);
}
}
}
expect('}');
return delegate.createObjectTypeAnnotation(properties, nullable);
}
function parseVoidTypeAnnotation() {
var marker = markerCreate();
expectKeyword('void');
return markerApply(marker, delegate.createVoidTypeAnnotation());
}
function parseParametricTypeAnnotation() {
var marker = markerCreate(), typeIdentifier, paramTypes = [];
expect('<');
while (!match('>')) {
paramTypes.push(parseVariableIdentifier());
if (!match('>')) {
expect(',');
}
}
expect('>');
return markerApply(marker, delegate.createParametricTypeAnnotation(
paramTypes
));
}
function parseTypeAnnotation(dontExpectColon) {
var typeIdentifier = null, params = null, returnType = null,
nullable = false, marker = markerCreate(), returnTypeMarker = null,
parametricType, annotation;
if (!dontExpectColon) {
expect(':');
}
if (match('?')) {
lex();
nullable = true;
}
if (match('{')) {
return markerApply(marker, parseObjectTypeAnnotation(nullable));
}
if (lookahead.type === Token.Identifier) {
typeIdentifier = parseVariableIdentifier();
if (match('<')) {
parametricType = parseParametricTypeAnnotation();
}
} else if (match('(')) {
lex();
params = [];
while (lookahead.type === Token.Identifier || match('?')) {
params.push(parseTypeAnnotatableIdentifier(
true, /* requireTypeAnnotation */
true /* canBeOptionalParam */
));
if (!match(')')) {
expect(',');
}
}
expect(')');
returnTypeMarker = markerCreate();
expect('=>');
returnType = parseTypeAnnotation(true);
} else {
if (!matchKeyword('void')) {
throwUnexpected(lookahead);
} else {
return markerApply(marker, parseVoidTypeAnnotation());
}
}
return markerApply(marker, delegate.createTypeAnnotation(
typeIdentifier,
parametricType,
params,
returnType,
nullable
));
}
function parseVariableIdentifier() {
var marker = markerCreate(),
token = lex();
if (token.type !== Token.Identifier) {
throwUnexpected(token);
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) {
var marker = markerCreate(),
ident = parseVariableIdentifier(),
isOptionalParam = false;
if (canBeOptionalParam && match('?')) {
expect('?');
isOptionalParam = true;
}
if (requireTypeAnnotation || match(':')) {
ident = markerApply(marker, delegate.createTypeAnnotatedIdentifier(
ident,
parseTypeAnnotation()
));
}
if (isOptionalParam) {
ident = markerApply(marker, delegate.createOptionalParameter(ident));
}
return ident;
}
function parseVariableDeclaration(kind) {
var id,
marker = markerCreate(),
init = null;
if (match('{')) {
id = parseObjectInitialiser();
reinterpretAsAssignmentBindingPattern(id);
} else if (match('[')) {
id = parseArrayInitialiser();
reinterpretAsAssignmentBindingPattern(id);
} else {
id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier();
// 12.2.1
if (strict && isRestrictedWord(id.name)) {
throwErrorTolerant({}, Messages.StrictVarName);
}
}
if (kind === 'const') {
if (!match('=')) {
throwError({}, Messages.NoUnintializedConst);
}
expect('=');
init = parseAssignmentExpression();
} else if (match('=')) {
lex();
init = parseAssignmentExpression();
}
return markerApply(marker, delegate.createVariableDeclarator(id, init));
}
function parseVariableDeclarationList(kind) {
var list = [];
do {
list.push(parseVariableDeclaration(kind));
if (!match(',')) {
break;
}
lex();
} while (index < length);
return list;
}
function parseVariableStatement() {
var declarations, marker = markerCreate();
expectKeyword('var');
declarations = parseVariableDeclarationList();
consumeSemicolon();
return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var'));
}
// kind may be `const` or `let`
// Both are experimental and not in the specification yet.
// see http://wiki.ecmascript.org/doku.php?id=harmony:const
// and http://wiki.ecmascript.org/doku.php?id=harmony:let
function parseConstLetDeclaration(kind) {
var declarations, marker = markerCreate();
expectKeyword(kind);
declarations = parseVariableDeclarationList(kind);
consumeSemicolon();
return markerApply(marker, delegate.createVariableDeclaration(declarations, kind));
}
// http://wiki.ecmascript.org/doku.php?id=harmony:modules
function parseModuleDeclaration() {
var id, src, body, marker = markerCreate();
lex(); // 'module'
if (peekLineTerminator()) {
throwError({}, Messages.NewlineAfterModule);
}
switch (lookahead.type) {
case Token.StringLiteral:
id = parsePrimaryExpression();
body = parseModuleBlock();
src = null;
break;
case Token.Identifier:
id = parseVariableIdentifier();
body = null;
if (!matchContextualKeyword('from')) {
throwUnexpected(lex());
}
lex();
src = parsePrimaryExpression();
if (src.type !== Syntax.Literal) {
throwError({}, Messages.InvalidModuleSpecifier);
}
break;
}
consumeSemicolon();
return markerApply(marker, delegate.createModuleDeclaration(id, src, body));
}
function parseExportBatchSpecifier() {
var marker = markerCreate();
expect('*');
return markerApply(marker, delegate.createExportBatchSpecifier());
}
function parseExportSpecifier() {
var id, name = null, marker = markerCreate();
id = parseVariableIdentifier();
if (matchContextualKeyword('as')) {
lex();
name = parseNonComputedProperty();
}
return markerApply(marker, delegate.createExportSpecifier(id, name));
}
function parseExportDeclaration() {
var previousAllowKeyword, decl, def, src, specifiers,
marker = markerCreate();
expectKeyword('export');
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'let':
case 'const':
case 'var':
case 'class':
case 'function':
return markerApply(marker, delegate.createExportDeclaration(parseSourceElement(), null, null));
}
}
if (isIdentifierName(lookahead)) {
previousAllowKeyword = state.allowKeyword;
state.allowKeyword = true;
decl = parseVariableDeclarationList('let');
state.allowKeyword = previousAllowKeyword;
return markerApply(marker, delegate.createExportDeclaration(decl, null, null));
}
specifiers = [];
src = null;
if (match('*')) {
specifiers.push(parseExportBatchSpecifier());
} else {
expect('{');
do {
specifiers.push(parseExportSpecifier());
} while (match(',') && lex());
expect('}');
}
if (matchContextualKeyword('from')) {
lex();
src = parsePrimaryExpression();
if (src.type !== Syntax.Literal) {
throwError({}, Messages.InvalidModuleSpecifier);
}
}
consumeSemicolon();
return markerApply(marker, delegate.createExportDeclaration(null, specifiers, src));
}
function parseImportDeclaration() {
var specifiers, kind, src, marker = markerCreate();
expectKeyword('import');
specifiers = [];
if (isIdentifierName(lookahead)) {
kind = 'default';
specifiers.push(parseImportSpecifier());
if (!matchContextualKeyword('from')) {
throwError({}, Messages.NoFromAfterImport);
}
lex();
} else if (match('{')) {
kind = 'named';
lex();
do {
specifiers.push(parseImportSpecifier());
} while (match(',') && lex());
expect('}');
if (!matchContextualKeyword('from')) {
throwError({}, Messages.NoFromAfterImport);
}
lex();
}
src = parsePrimaryExpression();
if (src.type !== Syntax.Literal) {
throwError({}, Messages.InvalidModuleSpecifier);
}
consumeSemicolon();
return markerApply(marker, delegate.createImportDeclaration(specifiers, kind, src));
}
function parseImportSpecifier() {
var id, name = null, marker = markerCreate();
id = parseNonComputedProperty();
if (matchContextualKeyword('as')) {
lex();
name = parseVariableIdentifier();
}
return markerApply(marker, delegate.createImportSpecifier(id, name));
}
// 12.3 Empty Statement
function parseEmptyStatement() {
var marker = markerCreate();
expect(';');
return markerApply(marker, delegate.createEmptyStatement());
}
// 12.4 Expression Statement
function parseExpressionStatement() {
var marker = markerCreate(), expr = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createExpressionStatement(expr));
}
// 12.5 If statement
function parseIfStatement() {
var test, consequent, alternate, marker = markerCreate();
expectKeyword('if');
expect('(');
test = parseExpression();
expect(')');
consequent = parseStatement();
if (matchKeyword('else')) {
lex();
alternate = parseStatement();
} else {
alternate = null;
}
return markerApply(marker, delegate.createIfStatement(test, consequent, alternate));
}
// 12.6 Iteration Statements
function parseDoWhileStatement() {
var body, test, oldInIteration, marker = markerCreate();
expectKeyword('do');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
if (match(';')) {
lex();
}
return markerApply(marker, delegate.createDoWhileStatement(body, test));
}
function parseWhileStatement() {
var test, body, oldInIteration, marker = markerCreate();
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
return markerApply(marker, delegate.createWhileStatement(test, body));
}
function parseForVariableDeclaration() {
var marker = markerCreate(),
token = lex(),
declarations = parseVariableDeclarationList();
return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value));
}
function parseForStatement(opts) {
var init, test, update, left, right, body, operator, oldInIteration,
marker = markerCreate();
init = test = update = null;
expectKeyword('for');
// http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each
if (matchContextualKeyword('each')) {
throwError({}, Messages.EachNotAllowed);
}
expect('(');
if (match(';')) {
lex();
} else {
if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) {
state.allowIn = false;
init = parseForVariableDeclaration();
state.allowIn = true;
if (init.declarations.length === 1) {
if (matchKeyword('in') || matchContextualKeyword('of')) {
operator = lookahead;
if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) {
lex();
left = init;
right = parseExpression();
init = null;
}
}
}
} else {
state.allowIn = false;
init = parseExpression();
state.allowIn = true;
if (matchContextualKeyword('of')) {
operator = lex();
left = init;
right = parseExpression();
init = null;
} else if (matchKeyword('in')) {
// LeftHandSideExpression
if (!isAssignableLeftHandSide(init)) {
throwError({}, Messages.InvalidLHSInForIn);
}
operator = lex();
left = init;
right = parseExpression();
init = null;
}
}
if (typeof left === 'undefined') {
expect(';');
}
}
if (typeof left === 'undefined') {
if (!match(';')) {
test = parseExpression();
}
expect(';');
if (!match(')')) {
update = parseExpression();
}
}
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
if (!(opts !== undefined && opts.ignoreBody)) {
body = parseStatement();
}
state.inIteration = oldInIteration;
if (typeof left === 'undefined') {
return markerApply(marker, delegate.createForStatement(init, test, update, body));
}
if (operator.value === 'in') {
return markerApply(marker, delegate.createForInStatement(left, right, body));
}
return markerApply(marker, delegate.createForOfStatement(left, right, body));
}
// 12.7 The continue statement
function parseContinueStatement() {
var label = null, key, marker = markerCreate();
expectKeyword('continue');
// Optimize the most common form: 'continue;'.
if (source.charCodeAt(index) === 59) {
lex();
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(null));
}
if (peekLineTerminator()) {
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(null));
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
key = '$' + label.name;
if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(label));
}
// 12.8 The break statement
function parseBreakStatement() {
var label = null, key, marker = markerCreate();
expectKeyword('break');
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(null));
}
if (peekLineTerminator()) {
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(null));
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
key = '$' + label.name;
if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(label));
}
// 12.9 The return statement
function parseReturnStatement() {
var argument = null, marker = markerCreate();
expectKeyword('return');
if (!state.inFunctionBody) {
throwErrorTolerant({}, Messages.IllegalReturn);
}
// 'return' followed by a space and an identifier is very common.
if (source.charCodeAt(index) === 32) {
if (isIdentifierStart(source.charCodeAt(index + 1))) {
argument = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
}
}
if (peekLineTerminator()) {
return markerApply(marker, delegate.createReturnStatement(null));
}
if (!match(';')) {
if (!match('}') && lookahead.type !== Token.EOF) {
argument = parseExpression();
}
}
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
}
// 12.10 The with statement
function parseWithStatement() {
var object, body, marker = markerCreate();
if (strict) {
throwErrorTolerant({}, Messages.StrictModeWith);
}
expectKeyword('with');
expect('(');
object = parseExpression();
expect(')');
body = parseStatement();
return markerApply(marker, delegate.createWithStatement(object, body));
}
// 12.10 The swith statement
function parseSwitchCase() {
var test,
consequent = [],
sourceElement,
marker = markerCreate();
if (matchKeyword('default')) {
lex();
test = null;
} else {
expectKeyword('case');
test = parseExpression();
}
expect(':');
while (index < length) {
if (match('}') || matchKeyword('default') || matchKeyword('case')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
consequent.push(sourceElement);
}
return markerApply(marker, delegate.createSwitchCase(test, consequent));
}
function parseSwitchStatement() {
var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate();
expectKeyword('switch');
expect('(');
discriminant = parseExpression();
expect(')');
expect('{');
cases = [];
if (match('}')) {
lex();
return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
}
oldInSwitch = state.inSwitch;
state.inSwitch = true;
defaultFound = false;
while (index < length) {
if (match('}')) {
break;
}
clause = parseSwitchCase();
if (clause.test === null) {
if (defaultFound) {
throwError({}, Messages.MultipleDefaultsInSwitch);
}
defaultFound = true;
}
cases.push(clause);
}
state.inSwitch = oldInSwitch;
expect('}');
return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
}
// 12.13 The throw statement
function parseThrowStatement() {
var argument, marker = markerCreate();
expectKeyword('throw');
if (peekLineTerminator()) {
throwError({}, Messages.NewlineAfterThrow);
}
argument = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createThrowStatement(argument));
}
// 12.14 The try statement
function parseCatchClause() {
var param, body, marker = markerCreate();
expectKeyword('catch');
expect('(');
if (match(')')) {
throwUnexpected(lookahead);
}
param = parseExpression();
// 12.14.1
if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
throwErrorTolerant({}, Messages.StrictCatchVariable);
}
expect(')');
body = parseBlock();
return markerApply(marker, delegate.createCatchClause(param, body));
}
function parseTryStatement() {
var block, handlers = [], finalizer = null, marker = markerCreate();
expectKeyword('try');
block = parseBlock();
if (matchKeyword('catch')) {
handlers.push(parseCatchClause());
}
if (matchKeyword('finally')) {
lex();
finalizer = parseBlock();
}
if (handlers.length === 0 && !finalizer) {
throwError({}, Messages.NoCatchOrFinally);
}
return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer));
}
// 12.15 The debugger statement
function parseDebuggerStatement() {
var marker = markerCreate();
expectKeyword('debugger');
consumeSemicolon();
return markerApply(marker, delegate.createDebuggerStatement());
}
// 12 Statements
function parseStatement() {
var type = lookahead.type,
marker,
expr,
labeledBody,
key;
if (type === Token.EOF) {
throwUnexpected(lookahead);
}
if (type === Token.Punctuator) {
switch (lookahead.value) {
case ';':
return parseEmptyStatement();
case '{':
return parseBlock();
case '(':
return parseExpressionStatement();
default:
break;
}
}
if (type === Token.Keyword) {
switch (lookahead.value) {
case 'break':
return parseBreakStatement();
case 'continue':
return parseContinueStatement();
case 'debugger':
return parseDebuggerStatement();
case 'do':
return parseDoWhileStatement();
case 'for':
return parseForStatement();
case 'function':
return parseFunctionDeclaration();
case 'class':
return parseClassDeclaration();
case 'if':
return parseIfStatement();
case 'return':
return parseReturnStatement();
case 'switch':
return parseSwitchStatement();
case 'throw':
return parseThrowStatement();
case 'try':
return parseTryStatement();
case 'var':
return parseVariableStatement();
case 'while':
return parseWhileStatement();
case 'with':
return parseWithStatement();
default:
break;
}
}
marker = markerCreate();
expr = parseExpression();
// 12.12 Labelled Statements
if ((expr.type === Syntax.Identifier) && match(':')) {
lex();
key = '$' + expr.name;
if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
throwError({}, Messages.Redeclaration, 'Label', expr.name);
}
state.labelSet[key] = true;
labeledBody = parseStatement();
delete state.labelSet[key];
return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody));
}
consumeSemicolon();
return markerApply(marker, delegate.createExpressionStatement(expr));
}
// 13 Function Definition
function parseConciseBody() {
if (match('{')) {
return parseFunctionSourceElements();
}
return parseAssignmentExpression();
}
function parseFunctionSourceElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted,
oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount,
marker = markerCreate();
expect('{');
while (index < length) {
if (lookahead.type !== Token.StringLiteral) {
break;
}
token = lookahead;
sourceElement = parseSourceElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
oldLabelSet = state.labelSet;
oldInIteration = state.inIteration;
oldInSwitch = state.inSwitch;
oldInFunctionBody = state.inFunctionBody;
oldParenthesizedCount = state.parenthesizedCount;
state.labelSet = {};
state.inIteration = false;
state.inSwitch = false;
state.inFunctionBody = true;
state.parenthesizedCount = 0;
while (index < length) {
if (match('}')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
expect('}');
state.labelSet = oldLabelSet;
state.inIteration = oldInIteration;
state.inSwitch = oldInSwitch;
state.inFunctionBody = oldInFunctionBody;
state.parenthesizedCount = oldParenthesizedCount;
return markerApply(marker, delegate.createBlockStatement(sourceElements));
}
function validateParam(options, param, name) {
var key = '$' + name;
if (strict) {
if (isRestrictedWord(name)) {
options.stricted = param;
options.message = Messages.StrictParamName;
}
if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
options.stricted = param;
options.message = Messages.StrictParamDupe;
}
} else if (!options.firstRestricted) {
if (isRestrictedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamName;
} else if (isStrictModeReservedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictReservedWord;
} else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
options.firstRestricted = param;
options.message = Messages.StrictParamDupe;
}
}
options.paramSet[key] = true;
}
function parseParam(options) {
var token, rest, param, def;
token = lookahead;
if (token.value === '...') {
token = lex();
rest = true;
}
if (match('[')) {
param = parseArrayInitialiser();
reinterpretAsDestructuredParameter(options, param);
} else if (match('{')) {
if (rest) {
throwError({}, Messages.ObjectPatternAsRestParameter);
}
param = parseObjectInitialiser();
reinterpretAsDestructuredParameter(options, param);
} else {
// Typing rest params is awkward, so punting on that for now
param =
rest
? parseVariableIdentifier()
: parseTypeAnnotatableIdentifier(
false, /* requireTypeAnnotation */
true /* canBeOptionalParam */
);
validateParam(options, token, token.value);
}
if (match('=')) {
if (rest) {
throwErrorTolerant(lookahead, Messages.DefaultRestParameter);
}
lex();
def = parseAssignmentExpression();
++options.defaultCount;
}
if (rest) {
if (!match(')')) {
throwError({}, Messages.ParameterAfterRestParameter);
}
options.rest = param;
return false;
}
options.params.push(param);
options.defaults.push(def);
return !match(')');
}
function parseParams(firstRestricted) {
var options, marker = markerCreate();
options = {
params: [],
defaultCount: 0,
defaults: [],
rest: null,
firstRestricted: firstRestricted
};
expect('(');
if (!match(')')) {
options.paramSet = {};
while (index < length) {
if (!parseParam(options)) {
break;
}
expect(',');
}
}
expect(')');
if (options.defaultCount === 0) {
options.defaults = [];
}
if (match(':')) {
options.returnType = parseTypeAnnotation();
}
return markerApply(marker, options);
}
function parseFunctionDeclaration() {
var id, body, token, tmp, firstRestricted, message, previousStrict, previousYieldAllowed, generator,
marker = markerCreate(), parametricType;
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
token = lookahead;
id = parseVariableIdentifier();
if (match('<')) {
parametricType = parseParametricTypeAnnotation();
}
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
return markerApply(marker, delegate.createFunctionDeclaration(id, tmp.params, tmp.defaults, body, tmp.rest, generator, false,
tmp.returnType, parametricType));
}
function parseFunctionExpression() {
var token, id = null, firstRestricted, message, tmp, body, previousStrict, previousYieldAllowed, generator,
marker = markerCreate(), parametricType;
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
if (!match('(')) {
if (!match('<')) {
token = lookahead;
id = parseVariableIdentifier();
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
}
if (match('<')) {
parametricType = parseParametricTypeAnnotation();
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
return markerApply(marker, delegate.createFunctionExpression(id, tmp.params, tmp.defaults, body, tmp.rest, generator, false,
tmp.returnType, parametricType));
}
function parseYieldExpression() {
var yieldToken, delegateFlag, expr, marker = markerCreate();
yieldToken = lex();
assert(yieldToken.value === 'yield', 'Called parseYieldExpression with non-yield lookahead.');
if (!state.yieldAllowed) {
throwErrorTolerant({}, Messages.IllegalYield);
}
delegateFlag = false;
if (match('*')) {
lex();
delegateFlag = true;
}
expr = parseAssignmentExpression();
return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag));
}
// 14 Classes
function parseMethodDefinition(existingPropNames) {
var token, key, param, propType, isValidDuplicateProp = false,
marker = markerCreate(), token2, parametricType,
parametricTypeMarker, annotationMarker;
if (lookahead.value === 'static') {
propType = ClassPropertyType["static"];
lex();
} else {
propType = ClassPropertyType.prototype;
}
if (match('*')) {
lex();
return markerApply(marker, delegate.createMethodDefinition(
propType,
'',
parseObjectPropertyKey(),
parsePropertyMethodFunction({ generator: true })
));
}
token = lookahead;
//parametricTypeMarker = markerCreate();
key = parseObjectPropertyKey();
if (token.value === 'get' && !match('(')) {
key = parseObjectPropertyKey();
// It is a syntax error if any other properties have a name
// duplicating this one unless they are a setter
if (existingPropNames[propType].hasOwnProperty(key.name)) {
isValidDuplicateProp =
// There isn't already a getter for this prop
existingPropNames[propType][key.name].get === undefined
// There isn't already a data prop by this name
&& existingPropNames[propType][key.name].data === undefined
// The only existing prop by this name is a setter
&& existingPropNames[propType][key.name].set !== undefined;
if (!isValidDuplicateProp) {
throwError(key, Messages.IllegalDuplicateClassProperty);
}
} else {
existingPropNames[propType][key.name] = {};
}
existingPropNames[propType][key.name].get = true;
expect('(');
expect(')');
return markerApply(marker, delegate.createMethodDefinition(
propType,
'get',
key,
parsePropertyFunction({ generator: false })
));
}
if (token.value === 'set' && !match('(')) {
key = parseObjectPropertyKey();
// It is a syntax error if any other properties have a name
// duplicating this one unless they are a getter
if (existingPropNames[propType].hasOwnProperty(key.name)) {
isValidDuplicateProp =
// There isn't already a setter for this prop
existingPropNames[propType][key.name].set === undefined
// There isn't already a data prop by this name
&& existingPropNames[propType][key.name].data === undefined
// The only existing prop by this name is a getter
&& existingPropNames[propType][key.name].get !== undefined;
if (!isValidDuplicateProp) {
throwError(key, Messages.IllegalDuplicateClassProperty);
}
} else {
existingPropNames[propType][key.name] = {};
}
existingPropNames[propType][key.name].set = true;
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
return markerApply(marker, delegate.createMethodDefinition(
propType,
'set',
key,
parsePropertyFunction({ params: param, generator: false, name: token })
));
}
if (match('<')) {
parametricType = parseParametricTypeAnnotation();
}
// It is a syntax error if any other properties have the same name as a
// non-getter, non-setter method
if (existingPropNames[propType].hasOwnProperty(key.name)) {
throwError(key, Messages.IllegalDuplicateClassProperty);
} else {
existingPropNames[propType][key.name] = {};
}
existingPropNames[propType][key.name].data = true;
return markerApply(marker, delegate.createMethodDefinition(
propType,
'',
key,
parsePropertyMethodFunction({
generator: false,
parametricType: parametricType
})
));
}
function parseClassProperty(existingPropNames) {
var marker = markerCreate(), propertyIdentifier;
propertyIdentifier = parseTypeAnnotatableIdentifier();
expect(';');
return markerApply(marker, delegate.createClassProperty(
propertyIdentifier
));
}
function parseClassElement(existingProps) {
if (match(';')) {
lex();
return;
}
var doubleLookahead = lookahead2();
if (doubleLookahead.type === Token.Punctuator) {
if (doubleLookahead.value === ':') {
return parseClassProperty(existingProps);
}
}
return parseMethodDefinition(existingProps);
}
function parseClassBody() {
var classElement, classElements = [], existingProps = {}, marker = markerCreate();
existingProps[ClassPropertyType["static"]] = {};
existingProps[ClassPropertyType.prototype] = {};
expect('{');
while (index < length) {
if (match('}')) {
break;
}
classElement = parseClassElement(existingProps);
if (typeof classElement !== 'undefined') {
classElements.push(classElement);
}
}
expect('}');
return markerApply(marker, delegate.createClassBody(classElements));
}
function parseClassExpression() {
var id, previousYieldAllowed, superClass = null, marker = markerCreate(),
parametricType;
expectKeyword('class');
if (!matchKeyword('extends') && !match('{')) {
id = parseVariableIdentifier();
}
if (match('<')) {
parametricType = parseParametricTypeAnnotation();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseAssignmentExpression();
state.yieldAllowed = previousYieldAllowed;
}
return markerApply(marker, delegate.createClassExpression(id, superClass, parseClassBody(), parametricType));
}
function parseClassDeclaration() {
var id, previousYieldAllowed, superClass = null, marker = markerCreate(),
parametricType, superParametricType;
expectKeyword('class');
id = parseVariableIdentifier();
if (match('<')) {
parametricType = parseParametricTypeAnnotation();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseAssignmentExpression();
state.yieldAllowed = previousYieldAllowed;
}
return markerApply(marker, delegate.createClassDeclaration(id, superClass, parseClassBody(), parametricType, superParametricType));
}
// 15 Program
function matchModuleDeclaration() {
var id;
if (matchContextualKeyword('module')) {
id = lookahead2();
return id.type === Token.StringLiteral || id.type === Token.Identifier;
}
return false;
}
function parseSourceElement() {
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'const':
case 'let':
return parseConstLetDeclaration(lookahead.value);
case 'function':
return parseFunctionDeclaration();
case 'export':
return parseExportDeclaration();
case 'import':
return parseImportDeclaration();
default:
return parseStatement();
}
}
if (matchModuleDeclaration()) {
throwError({}, Messages.NestedModule);
}
if (lookahead.type !== Token.EOF) {
return parseStatement();
}
}
function parseProgramElement() {
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'export':
return parseExportDeclaration();
case 'import':
return parseImportDeclaration();
}
}
if (matchModuleDeclaration()) {
return parseModuleDeclaration();
}
return parseSourceElement();
}
function parseProgramElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted;
while (index < length) {
token = lookahead;
if (token.type !== Token.StringLiteral) {
break;
}
sourceElement = parseProgramElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
while (index < length) {
sourceElement = parseProgramElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
return sourceElements;
}
function parseModuleElement() {
return parseSourceElement();
}
function parseModuleElements() {
var list = [],
statement;
while (index < length) {
if (match('}')) {
break;
}
statement = parseModuleElement();
if (typeof statement === 'undefined') {
break;
}
list.push(statement);
}
return list;
}
function parseModuleBlock() {
var block, marker = markerCreate();
expect('{');
block = parseModuleElements();
expect('}');
return markerApply(marker, delegate.createBlockStatement(block));
}
function parseProgram() {
var body, marker = markerCreate();
strict = false;
peek();
body = parseProgramElements();
return markerApply(marker, delegate.createProgram(body));
}
// The following functions are needed only when the option to preserve
// the comments is active.
function addComment(type, value, start, end, loc) {
var comment;
assert(typeof start === 'number', 'Comment must have valid position');
// Because the way the actual token is scanned, often the comments
// (if any) are skipped twice during the lexical analysis.
// Thus, we need to skip adding a comment if the comment array already
// handled it.
if (state.lastCommentStart >= start) {
return;
}
state.lastCommentStart = start;
comment = {
type: type,
value: value
};
if (extra.range) {
comment.range = [start, end];
}
if (extra.loc) {
comment.loc = loc;
}
extra.comments.push(comment);
if (extra.attachComment) {
extra.leadingComments.push(comment);
extra.trailingComments.push(comment);
}
}
function scanComment() {
var comment, ch, loc, start, blockComment, lineComment;
comment = '';
blockComment = false;
lineComment = false;
while (index < length) {
ch = source[index];
if (lineComment) {
ch = source[index++];
if (isLineTerminator(ch.charCodeAt(0))) {
loc.end = {
line: lineNumber,
column: index - lineStart - 1
};
lineComment = false;
addComment('Line', comment, start, index - 1, loc);
if (ch === '\r' && source[index] === '\n') {
++index;
}
++lineNumber;
lineStart = index;
comment = '';
} else if (index >= length) {
lineComment = false;
comment += ch;
loc.end = {
line: lineNumber,
column: length - lineStart
};
addComment('Line', comment, start, length, loc);
} else {
comment += ch;
}
} else if (blockComment) {
if (isLineTerminator(ch.charCodeAt(0))) {
if (ch === '\r') {
++index;
comment += '\r';
}
if (ch !== '\r' || source[index] === '\n') {
comment += source[index];
++lineNumber;
++index;
lineStart = index;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
} else {
ch = source[index++];
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
comment += ch;
if (ch === '*') {
ch = source[index];
if (ch === '/') {
comment = comment.substr(0, comment.length - 1);
blockComment = false;
++index;
loc.end = {
line: lineNumber,
column: index - lineStart
};
addComment('Block', comment, start, index, loc);
comment = '';
}
}
}
} else if (ch === '/') {
ch = source[index + 1];
if (ch === '/') {
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
start = index;
index += 2;
lineComment = true;
if (index >= length) {
loc.end = {
line: lineNumber,
column: index - lineStart
};
lineComment = false;
addComment('Line', comment, start, index, loc);
}
} else if (ch === '*') {
start = index;
index += 2;
blockComment = true;
loc = {
start: {
line: lineNumber,
column: index - lineStart - 2
}
};
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
break;
}
} else if (isWhiteSpace(ch.charCodeAt(0))) {
++index;
} else if (isLineTerminator(ch.charCodeAt(0))) {
++index;
if (ch === '\r' && source[index] === '\n') {
++index;
}
++lineNumber;
lineStart = index;
} else {
break;
}
}
}
// 16 XJS
XHTMLEntities = {
quot: '\u0022',
amp: '&',
apos: '\u0027',
lt: '<',
gt: '>',
nbsp: '\u00A0',
iexcl: '\u00A1',
cent: '\u00A2',
pound: '\u00A3',
curren: '\u00A4',
yen: '\u00A5',
brvbar: '\u00A6',
sect: '\u00A7',
uml: '\u00A8',
copy: '\u00A9',
ordf: '\u00AA',
laquo: '\u00AB',
not: '\u00AC',
shy: '\u00AD',
reg: '\u00AE',
macr: '\u00AF',
deg: '\u00B0',
plusmn: '\u00B1',
sup2: '\u00B2',
sup3: '\u00B3',
acute: '\u00B4',
micro: '\u00B5',
para: '\u00B6',
middot: '\u00B7',
cedil: '\u00B8',
sup1: '\u00B9',
ordm: '\u00BA',
raquo: '\u00BB',
frac14: '\u00BC',
frac12: '\u00BD',
frac34: '\u00BE',
iquest: '\u00BF',
Agrave: '\u00C0',
Aacute: '\u00C1',
Acirc: '\u00C2',
Atilde: '\u00C3',
Auml: '\u00C4',
Aring: '\u00C5',
AElig: '\u00C6',
Ccedil: '\u00C7',
Egrave: '\u00C8',
Eacute: '\u00C9',
Ecirc: '\u00CA',
Euml: '\u00CB',
Igrave: '\u00CC',
Iacute: '\u00CD',
Icirc: '\u00CE',
Iuml: '\u00CF',
ETH: '\u00D0',
Ntilde: '\u00D1',
Ograve: '\u00D2',
Oacute: '\u00D3',
Ocirc: '\u00D4',
Otilde: '\u00D5',
Ouml: '\u00D6',
times: '\u00D7',
Oslash: '\u00D8',
Ugrave: '\u00D9',
Uacute: '\u00DA',
Ucirc: '\u00DB',
Uuml: '\u00DC',
Yacute: '\u00DD',
THORN: '\u00DE',
szlig: '\u00DF',
agrave: '\u00E0',
aacute: '\u00E1',
acirc: '\u00E2',
atilde: '\u00E3',
auml: '\u00E4',
aring: '\u00E5',
aelig: '\u00E6',
ccedil: '\u00E7',
egrave: '\u00E8',
eacute: '\u00E9',
ecirc: '\u00EA',
euml: '\u00EB',
igrave: '\u00EC',
iacute: '\u00ED',
icirc: '\u00EE',
iuml: '\u00EF',
eth: '\u00F0',
ntilde: '\u00F1',
ograve: '\u00F2',
oacute: '\u00F3',
ocirc: '\u00F4',
otilde: '\u00F5',
ouml: '\u00F6',
divide: '\u00F7',
oslash: '\u00F8',
ugrave: '\u00F9',
uacute: '\u00FA',
ucirc: '\u00FB',
uuml: '\u00FC',
yacute: '\u00FD',
thorn: '\u00FE',
yuml: '\u00FF',
OElig: '\u0152',
oelig: '\u0153',
Scaron: '\u0160',
scaron: '\u0161',
Yuml: '\u0178',
fnof: '\u0192',
circ: '\u02C6',
tilde: '\u02DC',
Alpha: '\u0391',
Beta: '\u0392',
Gamma: '\u0393',
Delta: '\u0394',
Epsilon: '\u0395',
Zeta: '\u0396',
Eta: '\u0397',
Theta: '\u0398',
Iota: '\u0399',
Kappa: '\u039A',
Lambda: '\u039B',
Mu: '\u039C',
Nu: '\u039D',
Xi: '\u039E',
Omicron: '\u039F',
Pi: '\u03A0',
Rho: '\u03A1',
Sigma: '\u03A3',
Tau: '\u03A4',
Upsilon: '\u03A5',
Phi: '\u03A6',
Chi: '\u03A7',
Psi: '\u03A8',
Omega: '\u03A9',
alpha: '\u03B1',
beta: '\u03B2',
gamma: '\u03B3',
delta: '\u03B4',
epsilon: '\u03B5',
zeta: '\u03B6',
eta: '\u03B7',
theta: '\u03B8',
iota: '\u03B9',
kappa: '\u03BA',
lambda: '\u03BB',
mu: '\u03BC',
nu: '\u03BD',
xi: '\u03BE',
omicron: '\u03BF',
pi: '\u03C0',
rho: '\u03C1',
sigmaf: '\u03C2',
sigma: '\u03C3',
tau: '\u03C4',
upsilon: '\u03C5',
phi: '\u03C6',
chi: '\u03C7',
psi: '\u03C8',
omega: '\u03C9',
thetasym: '\u03D1',
upsih: '\u03D2',
piv: '\u03D6',
ensp: '\u2002',
emsp: '\u2003',
thinsp: '\u2009',
zwnj: '\u200C',
zwj: '\u200D',
lrm: '\u200E',
rlm: '\u200F',
ndash: '\u2013',
mdash: '\u2014',
lsquo: '\u2018',
rsquo: '\u2019',
sbquo: '\u201A',
ldquo: '\u201C',
rdquo: '\u201D',
bdquo: '\u201E',
dagger: '\u2020',
Dagger: '\u2021',
bull: '\u2022',
hellip: '\u2026',
permil: '\u2030',
prime: '\u2032',
Prime: '\u2033',
lsaquo: '\u2039',
rsaquo: '\u203A',
oline: '\u203E',
frasl: '\u2044',
euro: '\u20AC',
image: '\u2111',
weierp: '\u2118',
real: '\u211C',
trade: '\u2122',
alefsym: '\u2135',
larr: '\u2190',
uarr: '\u2191',
rarr: '\u2192',
darr: '\u2193',
harr: '\u2194',
crarr: '\u21B5',
lArr: '\u21D0',
uArr: '\u21D1',
rArr: '\u21D2',
dArr: '\u21D3',
hArr: '\u21D4',
forall: '\u2200',
part: '\u2202',
exist: '\u2203',
empty: '\u2205',
nabla: '\u2207',
isin: '\u2208',
notin: '\u2209',
ni: '\u220B',
prod: '\u220F',
sum: '\u2211',
minus: '\u2212',
lowast: '\u2217',
radic: '\u221A',
prop: '\u221D',
infin: '\u221E',
ang: '\u2220',
and: '\u2227',
or: '\u2228',
cap: '\u2229',
cup: '\u222A',
'int': '\u222B',
there4: '\u2234',
sim: '\u223C',
cong: '\u2245',
asymp: '\u2248',
ne: '\u2260',
equiv: '\u2261',
le: '\u2264',
ge: '\u2265',
sub: '\u2282',
sup: '\u2283',
nsub: '\u2284',
sube: '\u2286',
supe: '\u2287',
oplus: '\u2295',
otimes: '\u2297',
perp: '\u22A5',
sdot: '\u22C5',
lceil: '\u2308',
rceil: '\u2309',
lfloor: '\u230A',
rfloor: '\u230B',
lang: '\u2329',
rang: '\u232A',
loz: '\u25CA',
spades: '\u2660',
clubs: '\u2663',
hearts: '\u2665',
diams: '\u2666'
};
function getQualifiedXJSName(object) {
if (object.type === Syntax.XJSIdentifier) {
return object.name;
}
if (object.type === Syntax.XJSNamespacedName) {
return object.namespace.name + ':' + object.name.name;
}
if (object.type === Syntax.XJSMemberExpression) {
return (
getQualifiedXJSName(object.object) + '.' +
getQualifiedXJSName(object.property)
);
}
}
function isXJSIdentifierStart(ch) {
// exclude backslash (\)
return (ch !== 92) && isIdentifierStart(ch);
}
function isXJSIdentifierPart(ch) {
// exclude backslash (\) and add hyphen (-)
return (ch !== 92) && (ch === 45 || isIdentifierPart(ch));
}
function scanXJSIdentifier() {
var ch, start, value = '';
start = index;
while (index < length) {
ch = source.charCodeAt(index);
if (!isXJSIdentifierPart(ch)) {
break;
}
value += source[index++];
}
return {
type: Token.XJSIdentifier,
value: value,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanXJSEntity() {
var ch, str = '', count = 0, entity;
ch = source[index];
assert(ch === '&', 'Entity must start with an ampersand');
index++;
while (index < length && count++ < 10) {
ch = source[index++];
if (ch === ';') {
break;
}
str += ch;
}
if (str[0] === '#' && str[1] === 'x') {
entity = String.fromCharCode(parseInt(str.substr(2), 16));
} else if (str[0] === '#') {
entity = String.fromCharCode(parseInt(str.substr(1), 10));
} else {
entity = XHTMLEntities[str];
}
return entity;
}
function scanXJSText(stopChars) {
var ch, str = '', start;
start = index;
while (index < length) {
ch = source[index];
if (stopChars.indexOf(ch) !== -1) {
break;
}
if (ch === '&') {
str += scanXJSEntity();
} else {
index++;
if (ch === '\r' && source[index] === '\n') {
str += ch;
ch = source[index];
index++;
}
if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
lineStart = index;
}
str += ch;
}
}
return {
type: Token.XJSText,
value: str,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanXJSStringLiteral() {
var innerToken, quote, start;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
innerToken = scanXJSText([quote]);
if (quote !== source[index]) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
innerToken.range = [start, index];
return innerToken;
}
/**
* Between XJS opening and closing tags (e.g. <foo>HERE</foo>), anything that
* is not another XJS tag and is not an expression wrapped by {} is text.
*/
function advanceXJSChild() {
var ch = source.charCodeAt(index);
// { (123) and < (60)
if (ch !== 123 && ch !== 60) {
return scanXJSText(['<', '{']);
}
return scanPunctuator();
}
function parseXJSIdentifier() {
var token, marker = markerCreate();
if (lookahead.type !== Token.XJSIdentifier) {
throwUnexpected(lookahead);
}
token = lex();
return markerApply(marker, delegate.createXJSIdentifier(token.value));
}
function parseXJSNamespacedName() {
var namespace, name, marker = markerCreate();
namespace = parseXJSIdentifier();
expect(':');
name = parseXJSIdentifier();
return markerApply(marker, delegate.createXJSNamespacedName(namespace, name));
}
function parseXJSMemberExpression() {
var marker = markerCreate(),
expr = parseXJSIdentifier();
while (match('.')) {
lex();
expr = markerApply(marker, delegate.createXJSMemberExpression(expr, parseXJSIdentifier()));
}
return expr;
}
function parseXJSElementName() {
if (lookahead2().value === ':') {
return parseXJSNamespacedName();
}
if (lookahead2().value === '.') {
return parseXJSMemberExpression();
}
return parseXJSIdentifier();
}
function parseXJSAttributeName() {
if (lookahead2().value === ':') {
return parseXJSNamespacedName();
}
return parseXJSIdentifier();
}
function parseXJSAttributeValue() {
var value, marker;
if (match('{')) {
value = parseXJSExpressionContainer();
if (value.expression.type === Syntax.XJSEmptyExpression) {
throwError(
value,
'XJS attributes must only be assigned a non-empty ' +
'expression'
);
}
} else if (match('<')) {
value = parseXJSElement();
} else if (lookahead.type === Token.XJSText) {
marker = markerCreate();
value = markerApply(marker, delegate.createLiteral(lex()));
} else {
throwError({}, Messages.InvalidXJSAttributeValue);
}
return value;
}
function parseXJSEmptyExpression() {
var marker = markerCreatePreserveWhitespace();
while (source.charAt(index) !== '}') {
index++;
}
return markerApply(marker, delegate.createXJSEmptyExpression());
}
function parseXJSExpressionContainer() {
var expression, origInXJSChild, origInXJSTag, marker = markerCreate();
origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
state.inXJSChild = false;
state.inXJSTag = false;
expect('{');
if (match('}')) {
expression = parseXJSEmptyExpression();
} else {
expression = parseExpression();
}
state.inXJSChild = origInXJSChild;
state.inXJSTag = origInXJSTag;
expect('}');
return markerApply(marker, delegate.createXJSExpressionContainer(expression));
}
function parseXJSSpreadAttribute() {
var expression, origInXJSChild, origInXJSTag, marker = markerCreate();
origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
state.inXJSChild = false;
state.inXJSTag = false;
expect('{');
expect('...');
expression = parseAssignmentExpression();
state.inXJSChild = origInXJSChild;
state.inXJSTag = origInXJSTag;
expect('}');
return markerApply(marker, delegate.createXJSSpreadAttribute(expression));
}
function parseXJSAttribute() {
var name, marker;
if (match('{')) {
return parseXJSSpreadAttribute();
}
marker = markerCreate();
name = parseXJSAttributeName();
// HTML empty attribute
if (match('=')) {
lex();
return markerApply(marker, delegate.createXJSAttribute(name, parseXJSAttributeValue()));
}
return markerApply(marker, delegate.createXJSAttribute(name));
}
function parseXJSChild() {
var token, marker;
if (match('{')) {
token = parseXJSExpressionContainer();
} else if (lookahead.type === Token.XJSText) {
marker = markerCreatePreserveWhitespace();
token = markerApply(marker, delegate.createLiteral(lex()));
} else {
token = parseXJSElement();
}
return token;
}
function parseXJSClosingElement() {
var name, origInXJSChild, origInXJSTag, marker = markerCreate();
origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
state.inXJSChild = false;
state.inXJSTag = true;
expect('<');
expect('/');
name = parseXJSElementName();
// Because advance() (called by lex() called by expect()) expects there
// to be a valid token after >, it needs to know whether to look for a
// standard JS token or an XJS text node
state.inXJSChild = origInXJSChild;
state.inXJSTag = origInXJSTag;
expect('>');
return markerApply(marker, delegate.createXJSClosingElement(name));
}
function parseXJSOpeningElement() {
var name, attribute, attributes = [], selfClosing = false, origInXJSChild, origInXJSTag, marker = markerCreate();
origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
state.inXJSChild = false;
state.inXJSTag = true;
expect('<');
name = parseXJSElementName();
while (index < length &&
lookahead.value !== '/' &&
lookahead.value !== '>') {
attributes.push(parseXJSAttribute());
}
state.inXJSTag = origInXJSTag;
if (lookahead.value === '/') {
expect('/');
// Because advance() (called by lex() called by expect()) expects
// there to be a valid token after >, it needs to know whether to
// look for a standard JS token or an XJS text node
state.inXJSChild = origInXJSChild;
expect('>');
selfClosing = true;
} else {
state.inXJSChild = true;
expect('>');
}
return markerApply(marker, delegate.createXJSOpeningElement(name, attributes, selfClosing));
}
function parseXJSElement() {
var openingElement, closingElement = null, children = [], origInXJSChild, origInXJSTag, marker = markerCreate();
origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
openingElement = parseXJSOpeningElement();
if (!openingElement.selfClosing) {
while (index < length) {
state.inXJSChild = false; // Call lookahead2() with inXJSChild = false because </ should not be considered in the child
if (lookahead.value === '<' && lookahead2().value === '/') {
break;
}
state.inXJSChild = true;
children.push(parseXJSChild());
}
state.inXJSChild = origInXJSChild;
state.inXJSTag = origInXJSTag;
closingElement = parseXJSClosingElement();
if (getQualifiedXJSName(closingElement.name) !== getQualifiedXJSName(openingElement.name)) {
throwError({}, Messages.ExpectedXJSClosingTag, getQualifiedXJSName(openingElement.name));
}
}
// When (erroneously) writing two adjacent tags like
//
// var x = <div>one</div><div>two</div>;
//
// the default error message is a bit incomprehensible. Since it's
// rarely (never?) useful to write a less-than sign after an XJS
// element, we disallow it here in the parser in order to provide a
// better error message. (In the rare case that the less-than operator
// was intended, the left tag can be wrapped in parentheses.)
if (!origInXJSChild && match('<')) {
throwError(lookahead, Messages.AdjacentXJSElements);
}
return markerApply(marker, delegate.createXJSElement(openingElement, closingElement, children));
}
function collectToken() {
var start, loc, token, range, value;
if (!state.inXJSChild) {
skipComment();
}
start = index;
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
token = extra.advance();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (token.type !== Token.EOF) {
range = [token.range[0], token.range[1]];
value = source.slice(token.range[0], token.range[1]);
extra.tokens.push({
type: TokenName[token.type],
value: value,
range: range,
loc: loc
});
}
return token;
}
function collectRegex() {
var pos, loc, regex, token;
skipComment();
pos = index;
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
regex = extra.scanRegExp();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (!extra.tokenize) {
// Pop the previous token, which is likely '/' or '/='
if (extra.tokens.length > 0) {
token = extra.tokens[extra.tokens.length - 1];
if (token.range[0] === pos && token.type === 'Punctuator') {
if (token.value === '/' || token.value === '/=') {
extra.tokens.pop();
}
}
}
extra.tokens.push({
type: 'RegularExpression',
value: regex.literal,
range: [pos, index],
loc: loc
});
}
return regex;
}
function filterTokenLocation() {
var i, entry, token, tokens = [];
for (i = 0; i < extra.tokens.length; ++i) {
entry = extra.tokens[i];
token = {
type: entry.type,
value: entry.value
};
if (extra.range) {
token.range = entry.range;
}
if (extra.loc) {
token.loc = entry.loc;
}
tokens.push(token);
}
extra.tokens = tokens;
}
function patch() {
if (extra.comments) {
extra.skipComment = skipComment;
skipComment = scanComment;
}
if (typeof extra.tokens !== 'undefined') {
extra.advance = advance;
extra.scanRegExp = scanRegExp;
advance = collectToken;
scanRegExp = collectRegex;
}
}
function unpatch() {
if (typeof extra.skipComment === 'function') {
skipComment = extra.skipComment;
}
if (typeof extra.scanRegExp === 'function') {
advance = extra.advance;
scanRegExp = extra.scanRegExp;
}
}
// This is used to modify the delegate.
function extend(object, properties) {
var entry, result = {};
for (entry in object) {
if (object.hasOwnProperty(entry)) {
result[entry] = object[entry];
}
}
for (entry in properties) {
if (properties.hasOwnProperty(entry)) {
result[entry] = properties[entry];
}
}
return result;
}
function tokenize(code, options) {
var toString,
token,
tokens;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: true,
allowIn: true,
labelSet: {},
inFunctionBody: false,
inIteration: false,
inSwitch: false,
lastCommentStart: -1
};
extra = {};
// Options matching.
options = options || {};
// Of course we collect tokens here.
options.tokens = true;
extra.tokens = [];
extra.tokenize = true;
// The following two fields are necessary to compute the Regex tokens.
extra.openParenToken = -1;
extra.openCurlyToken = -1;
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
if (length > 0) {
if (typeof source[0] === 'undefined') {
// Try first to convert to a string. This is good as fast path
// for old IE which understands string indexing for string
// literals only and not for string object.
if (code instanceof String) {
source = code.valueOf();
}
}
}
patch();
try {
peek();
if (lookahead.type === Token.EOF) {
return extra.tokens;
}
token = lex();
while (lookahead.type !== Token.EOF) {
try {
token = lex();
} catch (lexError) {
token = lookahead;
if (extra.errors) {
extra.errors.push(lexError);
// We have to break on the first error
// to avoid infinite loops.
break;
} else {
throw lexError;
}
}
}
filterTokenLocation();
tokens = extra.tokens;
if (typeof extra.comments !== 'undefined') {
tokens.comments = extra.comments;
}
if (typeof extra.errors !== 'undefined') {
tokens.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return tokens;
}
function parse(code, options) {
var program, toString;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: false,
allowIn: true,
labelSet: {},
parenthesizedCount: 0,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
inXJSChild: false,
inXJSTag: false,
lastCommentStart: -1,
yieldAllowed: false
};
extra = {};
if (typeof options !== 'undefined') {
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
if (extra.loc && options.source !== null && options.source !== undefined) {
delegate = extend(delegate, {
'postProcess': function (node) {
node.loc.source = toString(options.source);
return node;
}
});
}
if (typeof options.tokens === 'boolean' && options.tokens) {
extra.tokens = [];
}
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
if (extra.attachComment) {
extra.range = true;
extra.comments = [];
extra.bottomRightStack = [];
extra.trailingComments = [];
extra.leadingComments = [];
}
}
if (length > 0) {
if (typeof source[0] === 'undefined') {
// Try first to convert to a string. This is good as fast path
// for old IE which understands string indexing for string
// literals only and not for string object.
if (code instanceof String) {
source = code.valueOf();
}
}
}
patch();
try {
program = parseProgram();
if (typeof extra.comments !== 'undefined') {
program.comments = extra.comments;
}
if (typeof extra.tokens !== 'undefined') {
filterTokenLocation();
program.tokens = extra.tokens;
}
if (typeof extra.errors !== 'undefined') {
program.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return program;
}
// Sync with *.json manifests.
exports.version = '6001.0001.0000-dev-harmony-fb';
exports.tokenize = tokenize;
exports.parse = parse;
// Deep copy.
exports.Syntax = (function () {
var name, types = {};
if (typeof Object.create === 'function') {
types = Object.create(null);
}
for (name in Syntax) {
if (Syntax.hasOwnProperty(name)) {
types[name] = Syntax[name];
}
}
if (typeof Object.freeze === 'function') {
Object.freeze(types);
}
return types;
}());
}));
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],9:[function(_dereq_,module,exports){
var Base62 = (function (my) {
my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "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"]
my.encode = function(i){
if (i === 0) {return '0'}
var s = ''
while (i > 0) {
s = this.chars[i % 62] + s
i = Math.floor(i/62)
}
return s
};
my.decode = function(a,b,c,d){
for (
b = c = (
a === (/\W|_|^$/.test(a += "") || a)
) - 1;
d = a.charCodeAt(c++);
)
b = b * 62 + d - [, 48, 29, 87][d >> 5];
return b
};
return my;
}({}));
module.exports = Base62
},{}],10:[function(_dereq_,module,exports){
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer;
exports.SourceNode = _dereq_('./source-map/source-node').SourceNode;
},{"./source-map/source-map-consumer":15,"./source-map/source-map-generator":16,"./source-map/source-node":17}],11:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = {};
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var isDuplicate = this.has(aStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[util.toSetString(aStr)] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set,
util.toSetString(aStr));
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
return this._set[util.toSetString(aStr)];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
});
},{"./util":18,"amdefine":19}],12:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64 = _dereq_('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string.
*/
exports.decode = function base64VLQ_decode(aStr) {
var i = 0;
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (i >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charAt(i++));
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return {
value: fromVLQSigned(result),
rest: aStr.slice(i)
};
};
});
},{"./base64":13,"amdefine":19}],13:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
.split('')
.forEach(function (ch, index) {
charToIntMap[ch] = index;
intToCharMap[index] = ch;
});
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function base64_encode(aNumber) {
if (aNumber in intToCharMap) {
return intToCharMap[aNumber];
}
throw new TypeError("Must be between 0 and 63: " + aNumber);
};
/**
* Decode a single base 64 digit to an integer.
*/
exports.decode = function base64_decode(aChar) {
if (aChar in charToIntMap) {
return charToIntMap[aChar];
}
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
},{"amdefine":19}],14:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the next
// closest element that is less than that element.
//
// 3. We did not find the exact element, and there is no next-closest
// element which is less than the one we are searching for, so we
// return null.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return aHaystack[mid];
}
else if (cmp > 0) {
// aHaystack[mid] is greater than our needle.
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
// We did not find an exact match, return the next closest one
// (termination case 2).
return aHaystack[mid];
}
else {
// aHaystack[mid] is less than our needle.
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (2) or (3) and return the appropriate thing.
return aLow < 0
? null
: aHaystack[aLow];
}
}
/**
* This is an implementation of binary search which will always try and return
* the next lowest value checked if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
*/
exports.search = function search(aNeedle, aHaystack, aCompare) {
return aHaystack.length > 0
? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
: null;
};
});
},{"amdefine":19}],15:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
var binarySearch = _dereq_('./binary-search');
var ArraySet = _dereq_('./array-set').ArraySet;
var base64VLQ = _dereq_('./base64-vlq');
/**
* A SourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
*/
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names, true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
/**
* Create a SourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns SourceMapConsumer
*/
SourceMapConsumer.fromSourceMap =
function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(SourceMapConsumer.prototype);
smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
smc.sourceRoot);
smc.file = aSourceMap._file;
smc.__generatedMappings = aSourceMap._mappings.slice()
.sort(util.compareByGeneratedPositions);
smc.__originalMappings = aSourceMap._mappings.slice()
.sort(util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
get: function () {
return this._sources.toArray().map(function (s) {
return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function () {
if (!this.__generatedMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function () {
if (!this.__originalMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var mappingSeparator = /^[,;]/;
var str = aStr;
var mapping;
var temp;
while (str.length > 0) {
if (str.charAt(0) === ';') {
generatedLine++;
str = str.slice(1);
previousGeneratedColumn = 0;
}
else if (str.charAt(0) === ',') {
str = str.slice(1);
}
else {
mapping = {};
mapping.generatedLine = generatedLine;
// Generated column.
temp = base64VLQ.decode(str);
mapping.generatedColumn = previousGeneratedColumn + temp.value;
previousGeneratedColumn = mapping.generatedColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original source.
temp = base64VLQ.decode(str);
mapping.source = this._sources.at(previousSource + temp.value);
previousSource += temp.value;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source, but no line and column');
}
// Original line.
temp = base64VLQ.decode(str);
mapping.originalLine = previousOriginalLine + temp.value;
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source and line, but no column');
}
// Original column.
temp = base64VLQ.decode(str);
mapping.originalColumn = previousOriginalColumn + temp.value;
previousOriginalColumn = mapping.originalColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original name.
temp = base64VLQ.decode(str);
mapping.name = this._names.at(previousName + temp.value);
previousName += temp.value;
str = temp.rest;
}
}
this.__generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
this.__originalMappings.push(mapping);
}
}
}
this.__originalMappings.sort(util.compareByOriginalPositions);
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
SourceMapConsumer.prototype._findMapping =
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
aColumnName, aComparator) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got '
+ aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator);
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
SourceMapConsumer.prototype.originalPositionFor =
function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var mapping = this._findMapping(needle,
this._generatedMappings,
"generatedLine",
"generatedColumn",
util.compareByGeneratedPositions);
if (mapping) {
var source = util.getArg(mapping, 'source', null);
if (source && this.sourceRoot) {
source = util.join(this.sourceRoot, source);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: util.getArg(mapping, 'name', null)
};
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* availible.
*/
SourceMapConsumer.prototype.sourceContentFor =
function SourceMapConsumer_sourceContentFor(aSource) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot
&& (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file"
&& this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
}
if ((!url.path || url.path == "/")
&& this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
throw new Error('"' + aSource + '" is not in the SourceMap.');
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.generatedPositionFor =
function SourceMapConsumer_generatedPositionFor(aArgs) {
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
if (this.sourceRoot) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
var mapping = this._findMapping(needle,
this._originalMappings,
"originalLine",
"originalColumn",
util.compareByOriginalPositions);
if (mapping) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null)
};
}
return {
line: null,
column: null
};
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping =
function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source;
if (source && sourceRoot) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name
};
}).forEach(aCallback, context);
};
exports.SourceMapConsumer = SourceMapConsumer;
});
},{"./array-set":11,"./base64-vlq":12,"./binary-search":14,"./util":18,"amdefine":19}],16:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64VLQ = _dereq_('./base64-vlq');
var util = _dereq_('./util');
var ArraySet = _dereq_('./array-set').ArraySet;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. To create a new one, you must pass an object
* with the following properties:
*
* - file: The filename of the generated source.
* - sourceRoot: An optional root for all URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
this._file = util.getArg(aArgs, 'file');
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = [];
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source) {
newMapping.source = mapping.source;
if (sourceRoot) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
this._validateMapping(generated, original, source, name);
if (source && !this._sources.has(source)) {
this._sources.add(source);
}
if (name && !this._names.has(name)) {
this._names.add(name);
}
this._mappings.push({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent !== null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = {};
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (!aSourceFile) {
aSourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "aSourceFile" relative if an absolute Url is passed.
if (sourceRoot) {
aSourceFile = util.relative(sourceRoot, aSourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "aSourceFile"
this._mappings.forEach(function (mapping) {
if (mapping.source === aSourceFile && mapping.originalLine) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source !== null) {
// Copy mapping
if (sourceRoot) {
mapping.source = util.relative(sourceRoot, original.source);
} else {
mapping.source = original.source;
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name !== null && mapping.name !== null) {
// Only use the identifier name if it's an identifier
// in both SourceMaps
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
if (sourceRoot) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
orginal: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var mapping;
// The mappings must be guaranteed to be in sorted order before we start
// serializing them or else the generated line numbers (which are defined
// via the ';' separators) will be all messed up. Note: it might be more
// performant to maintain the sorting as we insert them, rather than as we
// serialize them, but the big O is the same either way.
this._mappings.sort(util.compareByGeneratedPositions);
for (var i = 0, len = this._mappings.length; i < len; i++) {
mapping = this._mappings[i];
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
result += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
continue;
}
result += ',';
}
}
result += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source) {
result += base64VLQ.encode(this._sources.indexOf(mapping.source)
- previousSource);
previousSource = this._sources.indexOf(mapping.source);
// lines are stored 0-based in SourceMap spec version 3
result += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
result += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name) {
result += base64VLQ.encode(this._names.indexOf(mapping.name)
- previousName);
previousName = this._names.indexOf(mapping.name);
}
}
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents,
key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
file: this._file,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._sourceRoot) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this);
};
exports.SourceMapGenerator = SourceMapGenerator;
});
},{"./array-set":11,"./base64-vlq":12,"./util":18,"amdefine":19}],17:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator;
var util = _dereq_('./util');
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine === undefined ? null : aLine;
this.column = aColumn === undefined ? null : aColumn;
this.source = aSource === undefined ? null : aSource;
this.name = aName === undefined ? null : aName;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// The generated code
// Processed fragments are removed from this array.
var remainingLines = aGeneratedCode.split('\n');
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping === null) {
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(remainingLines.shift() + "\n");
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
} else {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
var code = "";
// Associate full lines with "lastMapping"
do {
code += remainingLines.shift() + "\n";
lastGeneratedLine++;
lastGeneratedColumn = 0;
} while (lastGeneratedLine < mapping.generatedLine);
// When we reached the correct line, we add code until we
// reach the correct column too.
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
code += nextLine.substr(0, mapping.generatedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
// Create the SourceNode.
addMappingWithCode(lastMapping, code);
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
}
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
// Associate the remaining code in the current line with "lastMapping"
// and add the remaining lines without any mapping
addMappingWithCode(lastMapping, remainingLines.join("\n"));
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
mapping.source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk instanceof SourceNode) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild instanceof SourceNode) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i] instanceof SourceNode) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
chunk.split('').forEach(function (ch) {
if (ch === '\n') {
generated.line++;
generated.column = 0;
} else {
generated.column++;
}
});
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
});
},{"./source-map-generator":16,"./util":18,"amdefine":19}],18:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
var dataUrlRegexp = /^data:.+\,.+/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[3],
host: match[4],
port: match[6],
path: match[7]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = aParsedUrl.scheme + "://";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@"
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function join(aRoot, aPath) {
var url;
if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
url.path = aPath;
return urlGenerate(url);
}
return aRoot.replace(/\/$/, '') + '/' + aPath;
}
exports.join = join;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
};
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings where the generated positions are
* compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
},{"amdefine":19}],19:[function(_dereq_,module,exports){
(function (process,__filename){
/** vim: et:ts=4:sw=4:sts=4
* @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/amdefine for details
*/
/*jslint node: true */
/*global module, process */
'use strict';
/**
* Creates a define for node.
* @param {Object} module the "module" object that is defined by Node for the
* current module.
* @param {Function} [requireFn]. Node's require function for the current module.
* It only needs to be passed in Node versions before 0.5, when module.require
* did not exist.
* @returns {Function} a define function that is usable for the current node
* module.
*/
function amdefine(module, requireFn) {
'use strict';
var defineCache = {},
loaderCache = {},
alreadyCalled = false,
path = _dereq_('path'),
makeRequire, stringRequire;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i+= 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
function normalize(name, baseName) {
var baseParts;
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
baseParts = baseName.split('/');
baseParts = baseParts.slice(0, baseParts.length - 1);
baseParts = baseParts.concat(name.split('/'));
trimDots(baseParts);
name = baseParts.join('/');
}
}
return name;
}
/**
* Create the normalize() function passed to a loader plugin's
* normalize method.
*/
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(id) {
function load(value) {
loaderCache[id] = value;
}
load.fromText = function (id, text) {
//This one is difficult because the text can/probably uses
//define, and any relative paths and requires should be relative
//to that id was it would be found on disk. But this would require
//bootstrapping a module/require fairly deeply from node core.
//Not sure how best to go about that yet.
throw new Error('amdefine does not implement load.fromText');
};
return load;
}
makeRequire = function (systemRequire, exports, module, relId) {
function amdRequire(deps, callback) {
if (typeof deps === 'string') {
//Synchronous, single module require('')
return stringRequire(systemRequire, exports, module, deps, relId);
} else {
//Array of dependencies with a callback.
//Convert the dependencies to modules.
deps = deps.map(function (depName) {
return stringRequire(systemRequire, exports, module, depName, relId);
});
//Wait for next tick to call back the require call.
process.nextTick(function () {
callback.apply(null, deps);
});
}
}
amdRequire.toUrl = function (filePath) {
if (filePath.indexOf('.') === 0) {
return normalize(filePath, path.dirname(module.filename));
} else {
return filePath;
}
};
return amdRequire;
};
//Favor explicit value, passed in if the module wants to support Node 0.4.
requireFn = requireFn || function req() {
return module.require.apply(module, arguments);
};
function runFactory(id, deps, factory) {
var r, e, m, result;
if (id) {
e = loaderCache[id] = {};
m = {
id: id,
uri: __filename,
exports: e
};
r = makeRequire(requireFn, e, m, id);
} else {
//Only support one define call per file
if (alreadyCalled) {
throw new Error('amdefine with no module ID cannot be called more than once per file.');
}
alreadyCalled = true;
//Use the real variables from node
//Use module.exports for exports, since
//the exports in here is amdefine exports.
e = module.exports;
m = module;
r = makeRequire(requireFn, e, m, module.id);
}
//If there are dependencies, they are strings, so need
//to convert them to dependency values.
if (deps) {
deps = deps.map(function (depName) {
return r(depName);
});
}
//Call the factory with the right dependencies.
if (typeof factory === 'function') {
result = factory.apply(m.exports, deps);
} else {
result = factory;
}
if (result !== undefined) {
m.exports = result;
if (id) {
loaderCache[id] = m.exports;
}
}
}
stringRequire = function (systemRequire, exports, module, id, relId) {
//Split the ID by a ! so that
var index = id.indexOf('!'),
originalId = id,
prefix, plugin;
if (index === -1) {
id = normalize(id, relId);
//Straight module lookup. If it is one of the special dependencies,
//deal with it, otherwise, delegate to node.
if (id === 'require') {
return makeRequire(systemRequire, exports, module, relId);
} else if (id === 'exports') {
return exports;
} else if (id === 'module') {
return module;
} else if (loaderCache.hasOwnProperty(id)) {
return loaderCache[id];
} else if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
} else {
if(systemRequire) {
return systemRequire(originalId);
} else {
throw new Error('No module with ID: ' + id);
}
}
} else {
//There is a plugin in play.
prefix = id.substring(0, index);
id = id.substring(index + 1, id.length);
plugin = stringRequire(systemRequire, exports, module, prefix, relId);
if (plugin.normalize) {
id = plugin.normalize(id, makeNormalize(relId));
} else {
//Normalize the ID normally.
id = normalize(id, relId);
}
if (loaderCache[id]) {
return loaderCache[id];
} else {
plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
return loaderCache[id];
}
}
};
//Create a define function specific to the module asking for amdefine.
function define(id, deps, factory) {
if (Array.isArray(id)) {
factory = deps;
deps = id;
id = undefined;
} else if (typeof id !== 'string') {
factory = id;
id = deps = undefined;
}
if (deps && !Array.isArray(deps)) {
factory = deps;
deps = undefined;
}
if (!deps) {
deps = ['require', 'exports', 'module'];
}
//Set up properties for this module. If an ID, then use
//internal cache. If no ID, then use the external variables
//for this node module.
if (id) {
//Put the module in deep freeze until there is a
//require call for it.
defineCache[id] = [id, deps, factory];
} else {
runFactory(id, deps, factory);
}
}
//define.require, which has access to all the values in the
//cache. Useful for AMD modules that all have IDs in the file,
//but need to finally export a value to node based on one of those
//IDs.
define.require = function (id) {
if (loaderCache[id]) {
return loaderCache[id];
}
if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
}
};
define.amd = {};
return define;
}
module.exports = amdefine;
}).call(this,_dereq_('_process'),"/node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js")
},{"_process":7,"path":6}],20:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/;
var ltrimRe = /^\s*/;
/**
* @param {String} contents
* @return {String}
*/
function extract(contents) {
var match = contents.match(docblockRe);
if (match) {
return match[0].replace(ltrimRe, '') || '';
}
return '';
}
var commentStartRe = /^\/\*\*?/;
var commentEndRe = /\*+\/$/;
var wsRe = /[\t ]+/g;
var stringStartRe = /(\r?\n|^) *\*/g;
var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
/**
* @param {String} contents
* @return {Array}
*/
function parse(docblock) {
docblock = docblock
.replace(commentStartRe, '')
.replace(commentEndRe, '')
.replace(wsRe, ' ')
.replace(stringStartRe, '$1');
// Normalize multi-line directives
var prev = '';
while (prev != docblock) {
prev = docblock;
docblock = docblock.replace(multilineRe, "\n$1 $2\n");
}
docblock = docblock.trim();
var result = [];
var match;
while (match = propertyRe.exec(docblock)) {
result.push([match[1], match[2]]);
}
return result;
}
/**
* Same as parse but returns an object of prop: value instead of array of paris
* If a property appers more than once the last one will be returned
*
* @param {String} contents
* @return {Object}
*/
function parseAsObject(docblock) {
var pairs = parse(docblock);
var result = {};
for (var i = 0; i < pairs.length; i++) {
result[pairs[i][0]] = pairs[i][1];
}
return result;
}
exports.extract = extract;
exports.parse = parse;
exports.parseAsObject = parseAsObject;
},{}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node: true*/
"use strict";
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('./utils');
var getBoundaryNode = utils.getBoundaryNode;
var declareIdentInScope = utils.declareIdentInLocalScope;
var initScopeMetadata = utils.initScopeMetadata;
var Syntax = esprima.Syntax;
/**
* @param {object} node
* @param {object} parentNode
* @return {boolean}
*/
function _nodeIsClosureScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return true;
}
var parentIsFunction =
parentNode.type === Syntax.FunctionDeclaration
|| parentNode.type === Syntax.FunctionExpression
|| parentNode.type === Syntax.ArrowFunctionExpression;
return node.type === Syntax.BlockStatement && parentIsFunction;
}
function _nodeIsBlockScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return false;
}
return node.type === Syntax.BlockStatement
&& parentNode.type === Syntax.CatchClause;
}
/**
* @param {object} node
* @param {function} visitor
* @param {array} path
* @param {object} state
*/
function traverse(node, path, state) {
// Create a scope stack entry if this is the first node we've encountered in
// its local scope
var parentNode = path[0];
if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) {
if (_nodeIsClosureScopeBoundary(node, parentNode)) {
var scopeIsStrict =
state.scopeIsStrict
|| node.body.length > 0
&& node.body[0].type === Syntax.ExpressionStatement
&& node.body[0].expression.type === Syntax.Literal
&& node.body[0].expression.value === 'use strict';
if (node.type === Syntax.Program) {
state = utils.updateState(state, {
scopeIsStrict: scopeIsStrict
});
} else {
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {},
tempVarIndex: 0
},
scopeIsStrict: scopeIsStrict
});
// All functions have an implicit 'arguments' object in scope
declareIdentInScope('arguments', initScopeMetadata(node), state);
// Include function arg identifiers in the scope boundaries of the
// function
if (parentNode.params.length > 0) {
var param;
for (var i = 0; i < parentNode.params.length; i++) {
param = parentNode.params[i];
if (param.type === Syntax.Identifier) {
declareIdentInScope(
param.name, initScopeMetadata(parentNode), state
);
}
}
}
// Named FunctionExpressions scope their name within the body block of
// themselves only
if (parentNode.type === Syntax.FunctionExpression && parentNode.id) {
var metaData =
initScopeMetadata(parentNode, path.parentNodeslice, parentNode);
declareIdentInScope(parentNode.id.name, metaData, state);
}
}
// Traverse and find all local identifiers in this closure first to
// account for function/variable declaration hoisting
collectClosureIdentsAndTraverse(node, path, state);
}
if (_nodeIsBlockScopeBoundary(node, parentNode)) {
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {}
}
});
if (parentNode.type === Syntax.CatchClause) {
declareIdentInScope(
parentNode.param.name, initScopeMetadata(parentNode), state
);
}
collectBlockIdentsAndTraverse(node, path, state);
}
}
// Only catchup() before and after traversing a child node
function traverser(node, path, state) {
node.range && utils.catchup(node.range[0], state);
traverse(node, path, state);
node.range && utils.catchup(node.range[1], state);
}
utils.analyzeAndTraverse(walker, traverser, node, path, state);
}
function collectClosureIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalClosureIdentifiers,
collectClosureIdentsAndTraverse,
node,
path,
state
);
}
function collectBlockIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalBlockIdentifiers,
collectBlockIdentsAndTraverse,
node,
path,
state
);
}
function visitLocalClosureIdentifiers(node, path, state) {
var metaData;
switch (node.type) {
case Syntax.FunctionExpression:
// Function expressions don't get their names (if there is one) added to
// the closure scope they're defined in
return false;
case Syntax.ClassDeclaration:
case Syntax.ClassExpression:
case Syntax.FunctionDeclaration:
if (node.id) {
metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
declareIdentInScope(node.id.name, metaData, state);
}
return false;
case Syntax.VariableDeclarator:
// Variables have function-local scope
if (path[0].kind === 'var') {
metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
declareIdentInScope(node.id.name, metaData, state);
}
break;
}
}
function visitLocalBlockIdentifiers(node, path, state) {
// TODO: Support 'let' here...maybe...one day...or something...
if (node.type === Syntax.CatchClause) {
return false;
}
}
function walker(node, path, state) {
var visitors = state.g.visitors;
for (var i = 0; i < visitors.length; i++) {
if (visitors[i].test(node, path, state)) {
return visitors[i](traverse, node, path, state);
}
}
}
var _astCache = {};
/**
* Applies all available transformations to the source
* @param {array} visitors
* @param {string} source
* @param {?object} options
* @return {object}
*/
function transform(visitors, source, options) {
options = options || {};
var ast;
try {
var cachedAst = _astCache[source];
ast = cachedAst ||
(_astCache[source] = esprima.parse(source, {
comment: true,
loc: true,
range: true
}));
} catch (e) {
e.message = 'Parse Error: ' + e.message;
throw e;
}
var state = utils.createState(source, ast, options);
state.g.visitors = visitors;
if (options.sourceMap) {
var SourceMapGenerator = _dereq_('source-map').SourceMapGenerator;
state.g.sourceMap = new SourceMapGenerator({file: options.filename || 'transformed.js'});
}
traverse(ast, [], state);
utils.catchup(source.length, state);
var ret = {code: state.g.buffer, extra: state.g.extra};
if (options.sourceMap) {
ret.sourceMap = state.g.sourceMap;
ret.sourceMapFilename = options.filename || 'source.js';
}
return ret;
}
exports.transform = transform;
exports.Syntax = Syntax;
},{"./utils":22,"esprima-fb":8,"source-map":10}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node: true*/
var Syntax = _dereq_('esprima-fb').Syntax;
var leadingIndentRegexp = /(^|\n)( {2}|\t)/g;
var nonWhiteRegexp = /(\S)/g;
/**
* A `state` object represents the state of the parser. It has "local" and
* "global" parts. Global contains parser position, source, etc. Local contains
* scope based properties like current class name. State should contain all the
* info required for transformation. It's the only mandatory object that is
* being passed to every function in transform chain.
*
* @param {string} source
* @param {object} transformOptions
* @return {object}
*/
function createState(source, rootNode, transformOptions) {
return {
/**
* A tree representing the current local scope (and its lexical scope chain)
* Useful for tracking identifiers from parent scopes, etc.
* @type {Object}
*/
localScope: {
parentNode: rootNode,
parentScope: null,
identifiers: {},
tempVarIndex: 0
},
/**
* The name (and, if applicable, expression) of the super class
* @type {Object}
*/
superClass: null,
/**
* The namespace to use when munging identifiers
* @type {String}
*/
mungeNamespace: '',
/**
* Ref to the node for the current MethodDefinition
* @type {Object}
*/
methodNode: null,
/**
* Ref to the node for the FunctionExpression of the enclosing
* MethodDefinition
* @type {Object}
*/
methodFuncNode: null,
/**
* Name of the enclosing class
* @type {String}
*/
className: null,
/**
* Whether we're currently within a `strict` scope
* @type {Bool}
*/
scopeIsStrict: null,
/**
* Indentation offset
* @type {Number}
*/
indentBy: 0,
/**
* Global state (not affected by updateState)
* @type {Object}
*/
g: {
/**
* A set of general options that transformations can consider while doing
* a transformation:
*
* - minify
* Specifies that transformation steps should do their best to minify
* the output source when possible. This is useful for places where
* minification optimizations are possible with higher-level context
* info than what jsxmin can provide.
*
* For example, the ES6 class transform will minify munged private
* variables if this flag is set.
*/
opts: transformOptions,
/**
* Current position in the source code
* @type {Number}
*/
position: 0,
/**
* Auxiliary data to be returned by transforms
* @type {Object}
*/
extra: {},
/**
* Buffer containing the result
* @type {String}
*/
buffer: '',
/**
* Source that is being transformed
* @type {String}
*/
source: source,
/**
* Cached parsed docblock (see getDocblock)
* @type {object}
*/
docblock: null,
/**
* Whether the thing was used
* @type {Boolean}
*/
tagNamespaceUsed: false,
/**
* If using bolt xjs transformation
* @type {Boolean}
*/
isBolt: undefined,
/**
* Whether to record source map (expensive) or not
* @type {SourceMapGenerator|null}
*/
sourceMap: null,
/**
* Filename of the file being processed. Will be returned as a source
* attribute in the source map
*/
sourceMapFilename: 'source.js',
/**
* Only when source map is used: last line in the source for which
* source map was generated
* @type {Number}
*/
sourceLine: 1,
/**
* Only when source map is used: last line in the buffer for which
* source map was generated
* @type {Number}
*/
bufferLine: 1,
/**
* The top-level Program AST for the original file.
*/
originalProgramAST: null,
sourceColumn: 0,
bufferColumn: 0
}
};
}
/**
* Updates a copy of a given state with "update" and returns an updated state.
*
* @param {object} state
* @param {object} update
* @return {object}
*/
function updateState(state, update) {
var ret = Object.create(state);
Object.keys(update).forEach(function(updatedKey) {
ret[updatedKey] = update[updatedKey];
});
return ret;
}
/**
* Given a state fill the resulting buffer from the original source up to
* the end
*
* @param {number} end
* @param {object} state
* @param {?function} contentTransformer Optional callback to transform newly
* added content.
*/
function catchup(end, state, contentTransformer) {
if (end < state.g.position) {
// cannot move backwards
return;
}
var source = state.g.source.substring(state.g.position, end);
var transformed = updateIndent(source, state);
if (state.g.sourceMap && transformed) {
// record where we are
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
// record line breaks in transformed source
var sourceLines = source.split('\n');
var transformedLines = transformed.split('\n');
// Add line break mappings between last known mapping and the end of the
// added piece. So for the code piece
// (foo, bar);
// > var x = 2;
// > var b = 3;
// var c =
// only add lines marked with ">": 2, 3.
for (var i = 1; i < sourceLines.length - 1; i++) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: 0 },
original: { line: state.g.sourceLine, column: 0 },
source: state.g.sourceMapFilename
});
state.g.sourceLine++;
state.g.bufferLine++;
}
// offset for the last piece
if (sourceLines.length > 1) {
state.g.sourceLine++;
state.g.bufferLine++;
state.g.sourceColumn = 0;
state.g.bufferColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer +=
contentTransformer ? contentTransformer(transformed) : transformed;
state.g.position = end;
}
/**
* Returns original source for an AST node.
* @param {object} node
* @param {object} state
* @return {string}
*/
function getNodeSourceText(node, state) {
return state.g.source.substring(node.range[0], node.range[1]);
}
function replaceNonWhite(value) {
return value.replace(nonWhiteRegexp, ' ');
}
/**
* Removes all non-whitespace characters
*/
function stripNonWhite(value) {
return value.replace(nonWhiteRegexp, '');
}
/**
* Catches up as `catchup` but replaces non-whitespace chars with spaces.
*/
function catchupWhiteOut(end, state) {
catchup(end, state, replaceNonWhite);
}
/**
* Catches up as `catchup` but removes all non-whitespace characters.
*/
function catchupWhiteSpace(end, state) {
catchup(end, state, stripNonWhite);
}
/**
* Removes all non-newline characters
*/
var reNonNewline = /[^\n]/g;
function stripNonNewline(value) {
return value.replace(reNonNewline, function() {
return '';
});
}
/**
* Catches up as `catchup` but removes all non-newline characters.
*
* Equivalent to appending as many newlines as there are in the original source
* between the current position and `end`.
*/
function catchupNewlines(end, state) {
catchup(end, state, stripNonNewline);
}
/**
* Same as catchup but does not touch the buffer
*
* @param {number} end
* @param {object} state
*/
function move(end, state) {
// move the internal cursors
if (state.g.sourceMap) {
if (end < state.g.position) {
state.g.position = 0;
state.g.sourceLine = 1;
state.g.sourceColumn = 0;
}
var source = state.g.source.substring(state.g.position, end);
var sourceLines = source.split('\n');
if (sourceLines.length > 1) {
state.g.sourceLine += sourceLines.length - 1;
state.g.sourceColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
}
state.g.position = end;
}
/**
* Appends a string of text to the buffer
*
* @param {string} str
* @param {object} state
*/
function append(str, state) {
if (state.g.sourceMap && str) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
var transformedLines = str.split('\n');
if (transformedLines.length > 1) {
state.g.bufferLine += transformedLines.length - 1;
state.g.bufferColumn = 0;
}
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer += str;
}
/**
* Update indent using state.indentBy property. Indent is measured in
* double spaces. Updates a single line only.
*
* @param {string} str
* @param {object} state
* @return {string}
*/
function updateIndent(str, state) {
var indentBy = state.indentBy;
if (indentBy < 0) {
for (var i = 0; i < -indentBy; i++) {
str = str.replace(leadingIndentRegexp, '$1');
}
} else {
for (var i = 0; i < indentBy; i++) {
str = str.replace(leadingIndentRegexp, '$1$2$2');
}
}
return str;
}
/**
* Calculates indent from the beginning of the line until "start" or the first
* character before start.
* @example
* " foo.bar()"
* ^
* start
* indent will be " "
*
* @param {number} start
* @param {object} state
* @return {string}
*/
function indentBefore(start, state) {
var end = start;
start = start - 1;
while (start > 0 && state.g.source[start] != '\n') {
if (!state.g.source[start].match(/[ \t]/)) {
end = start;
}
start--;
}
return state.g.source.substring(start + 1, end);
}
function getDocblock(state) {
if (!state.g.docblock) {
var docblock = _dereq_('./docblock');
state.g.docblock =
docblock.parseAsObject(docblock.extract(state.g.source));
}
return state.g.docblock;
}
function identWithinLexicalScope(identName, state, stopBeforeNode) {
var currScope = state.localScope;
while (currScope) {
if (currScope.identifiers[identName] !== undefined) {
return true;
}
if (stopBeforeNode && currScope.parentNode === stopBeforeNode) {
break;
}
currScope = currScope.parentScope;
}
return false;
}
function identInLocalScope(identName, state) {
return state.localScope.identifiers[identName] !== undefined;
}
/**
* @param {object} boundaryNode
* @param {?array} path
* @return {?object} node
*/
function initScopeMetadata(boundaryNode, path, node) {
return {
boundaryNode: boundaryNode,
bindingPath: path,
bindingNode: node
};
}
function declareIdentInLocalScope(identName, metaData, state) {
state.localScope.identifiers[identName] = {
boundaryNode: metaData.boundaryNode,
path: metaData.path,
node: metaData.node,
state: Object.create(state)
};
}
function getLexicalBindingMetadata(identName, state) {
return state.localScope.identifiers[identName];
}
/**
* Apply the given analyzer function to the current node. If the analyzer
* doesn't return false, traverse each child of the current node using the given
* traverser function.
*
* @param {function} analyzer
* @param {function} traverser
* @param {object} node
* @param {function} visitor
* @param {array} path
* @param {object} state
*/
function analyzeAndTraverse(analyzer, traverser, node, path, state) {
if (node.type) {
if (analyzer(node, path, state) === false) {
return;
}
path.unshift(node);
}
getOrderedChildren(node).forEach(function(child) {
traverser(child, path, state);
});
node.type && path.shift();
}
/**
* It is crucial that we traverse in order, or else catchup() on a later
* node that is processed out of order can move the buffer past a node
* that we haven't handled yet, preventing us from modifying that node.
*
* This can happen when a node has multiple properties containing children.
* For example, XJSElement nodes have `openingElement`, `closingElement` and
* `children`. If we traverse `openingElement`, then `closingElement`, then
* when we get to `children`, the buffer has already caught up to the end of
* the closing element, after the children.
*
* This is basically a Schwartzian transform. Collects an array of children,
* each one represented as [child, startIndex]; sorts the array by start
* index; then traverses the children in that order.
*/
function getOrderedChildren(node) {
var queue = [];
for (var key in node) {
if (node.hasOwnProperty(key)) {
enqueueNodeWithStartIndex(queue, node[key]);
}
}
queue.sort(function(a, b) { return a[1] - b[1]; });
return queue.map(function(pair) { return pair[0]; });
}
/**
* Helper function for analyzeAndTraverse which queues up all of the children
* of the given node.
*
* Children can also be found in arrays, so we basically want to merge all of
* those arrays together so we can sort them and then traverse the children
* in order.
*
* One example is the Program node. It contains `body` and `comments`, both
* arrays. Lexographically, comments are interspersed throughout the body
* nodes, but esprima's AST groups them together.
*/
function enqueueNodeWithStartIndex(queue, node) {
if (typeof node !== 'object' || node === null) {
return;
}
if (node.range) {
queue.push([node, node.range[0]]);
} else if (Array.isArray(node)) {
for (var ii = 0; ii < node.length; ii++) {
enqueueNodeWithStartIndex(queue, node[ii]);
}
}
}
/**
* Checks whether a node or any of its sub-nodes contains
* a syntactic construct of the passed type.
* @param {object} node - AST node to test.
* @param {string} type - node type to lookup.
*/
function containsChildOfType(node, type) {
var foundMatchingChild = false;
function nodeTypeAnalyzer(node) {
if (node.type === type) {
foundMatchingChild = true;
return false;
}
}
function nodeTypeTraverser(child, path, state) {
if (!foundMatchingChild) {
foundMatchingChild = containsChildOfType(child, type);
}
}
analyzeAndTraverse(
nodeTypeAnalyzer,
nodeTypeTraverser,
node,
[]
);
return foundMatchingChild;
}
var scopeTypes = {};
scopeTypes[Syntax.FunctionExpression] = true;
scopeTypes[Syntax.FunctionDeclaration] = true;
scopeTypes[Syntax.Program] = true;
function getBoundaryNode(path) {
for (var ii = 0; ii < path.length; ++ii) {
if (scopeTypes[path[ii].type]) {
return path[ii];
}
}
throw new Error(
'Expected to find a node with one of the following types in path:\n' +
JSON.stringify(Object.keys(scopeTypes))
);
}
exports.append = append;
exports.catchup = catchup;
exports.catchupWhiteOut = catchupWhiteOut;
exports.catchupWhiteSpace = catchupWhiteSpace;
exports.catchupNewlines = catchupNewlines;
exports.containsChildOfType = containsChildOfType;
exports.createState = createState;
exports.declareIdentInLocalScope = declareIdentInLocalScope;
exports.getBoundaryNode = getBoundaryNode;
exports.getDocblock = getDocblock;
exports.getLexicalBindingMetadata = getLexicalBindingMetadata;
exports.initScopeMetadata = initScopeMetadata;
exports.identWithinLexicalScope = identWithinLexicalScope;
exports.identInLocalScope = identInLocalScope;
exports.indentBefore = indentBefore;
exports.move = move;
exports.scopeTypes = scopeTypes;
exports.updateIndent = updateIndent;
exports.updateState = updateState;
exports.analyzeAndTraverse = analyzeAndTraverse;
exports.getOrderedChildren = getOrderedChildren;
exports.getNodeSourceText = getNodeSourceText;
},{"./docblock":20,"esprima-fb":8}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*global exports:true*/
/**
* Desugars ES6 Arrow functions to ES3 function expressions.
* If the function contains `this` expression -- automatically
* binds the function to current value of `this`.
*
* Single parameter, simple expression:
*
* [1, 2, 3].map(x => x * x);
*
* [1, 2, 3].map(function(x) { return x * x; });
*
* Several parameters, complex block:
*
* this.users.forEach((user, idx) => {
* return this.isActive(idx) && this.send(user);
* });
*
* this.users.forEach(function(user, idx) {
* return this.isActive(idx) && this.send(user);
* }.bind(this));
*
*/
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
var destructuringVisitors = _dereq_('./es6-destructuring-visitors');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitArrowFunction(traverse, node, path, state) {
var notInExpression = (path[0].type === Syntax.ExpressionStatement);
// Wrap a function into a grouping operator, if it's not
// in the expression position.
if (notInExpression) {
utils.append('(', state);
}
utils.append('function', state);
renderParams(traverse, node, path, state);
// Skip arrow.
utils.catchupWhiteSpace(node.body.range[0], state);
var renderBody = node.body.type == Syntax.BlockStatement
? renderStatementBody
: renderExpressionBody;
path.unshift(node);
renderBody(traverse, node, path, state);
path.shift();
// Bind the function only if `this` value is used
// inside it or inside any sub-expression.
if (utils.containsChildOfType(node.body, Syntax.ThisExpression)) {
utils.append('.bind(this)', state);
}
utils.catchupWhiteSpace(node.range[1], state);
// Close wrapper if not in the expression.
if (notInExpression) {
utils.append(')', state);
}
return false;
}
function renderParams(traverse, node, path, state) {
// To preserve inline typechecking directives, we
// distinguish between parens-free and paranthesized single param.
if (isParensFreeSingleParam(node, state) || !node.params.length) {
utils.append('(', state);
}
if (node.params.length !== 0) {
path.unshift(node);
traverse(node.params, path, state);
path.unshift();
}
utils.append(')', state);
}
function isParensFreeSingleParam(node, state) {
return node.params.length === 1 &&
state.g.source[state.g.position] !== '(';
}
function renderExpressionBody(traverse, node, path, state) {
// Wrap simple expression bodies into a block
// with explicit return statement.
utils.append('{', state);
// Special handling of rest param.
if (node.rest) {
utils.append(
restParamVisitors.renderRestParamSetup(node),
state
);
}
// Special handling of destructured params.
destructuringVisitors.renderDestructuredComponents(
node,
utils.updateState(state, {
localScope: {
parentNode: state.parentNode,
parentScope: state.parentScope,
identifiers: state.identifiers,
tempVarIndex: 0
}
})
);
utils.append('return ', state);
renderStatementBody(traverse, node, path, state);
utils.append(';}', state);
}
function renderStatementBody(traverse, node, path, state) {
traverse(node.body, path, state);
utils.catchup(node.body.range[1], state);
}
visitArrowFunction.test = function(node, path, state) {
return node.type === Syntax.ArrowFunctionExpression;
};
exports.visitorList = [
visitArrowFunction
];
},{"../src/utils":22,"./es6-destructuring-visitors":25,"./es6-rest-param-visitors":28,"esprima-fb":8}],24:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var base62 = _dereq_('base62');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
var declareIdentInLocalScope = utils.declareIdentInLocalScope;
var initScopeMetadata = utils.initScopeMetadata;
var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf';
var _anonClassUUIDCounter = 0;
var _mungedSymbolMaps = {};
function resetSymbols() {
_anonClassUUIDCounter = 0;
_mungedSymbolMaps = {};
}
/**
* Used to generate a unique class for use with code-gens for anonymous class
* expressions.
*
* @param {object} state
* @return {string}
*/
function _generateAnonymousClassName(state) {
var mungeNamespace = state.mungeNamespace || '';
return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++);
}
/**
* Given an identifier name, munge it using the current state's mungeNamespace.
*
* @param {string} identName
* @param {object} state
* @return {string}
*/
function _getMungedName(identName, state) {
var mungeNamespace = state.mungeNamespace;
var shouldMinify = state.g.opts.minify;
if (shouldMinify) {
if (!_mungedSymbolMaps[mungeNamespace]) {
_mungedSymbolMaps[mungeNamespace] = {
symbolMap: {},
identUUIDCounter: 0
};
}
var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap;
if (!symbolMap[identName]) {
symbolMap[identName] =
base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++);
}
identName = symbolMap[identName];
}
return '$' + mungeNamespace + identName;
}
/**
* Extracts super class information from a class node.
*
* Information includes name of the super class and/or the expression string
* (if extending from an expression)
*
* @param {object} node
* @param {object} state
* @return {object}
*/
function _getSuperClassInfo(node, state) {
var ret = {
name: null,
expression: null
};
if (node.superClass) {
if (node.superClass.type === Syntax.Identifier) {
ret.name = node.superClass.name;
} else {
// Extension from an expression
ret.name = _generateAnonymousClassName(state);
ret.expression = state.g.source.substring(
node.superClass.range[0],
node.superClass.range[1]
);
}
}
return ret;
}
/**
* Used with .filter() to find the constructor method in a list of
* MethodDefinition nodes.
*
* @param {object} classElement
* @return {boolean}
*/
function _isConstructorMethod(classElement) {
return classElement.type === Syntax.MethodDefinition &&
classElement.key.type === Syntax.Identifier &&
classElement.key.name === 'constructor';
}
/**
* @param {object} node
* @param {object} state
* @return {boolean}
*/
function _shouldMungeIdentifier(node, state) {
return (
!!state.methodFuncNode &&
!utils.getDocblock(state).hasOwnProperty('preventMunge') &&
/^_(?!_)/.test(node.name)
);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassMethod(traverse, node, path, state) {
if (!state.g.opts.es5 && (node.kind === 'get' || node.kind === 'set')) {
throw new Error(
'This transform does not support ' + node.kind + 'ter methods for ES6 ' +
'classes. (line: ' + node.loc.start.line + ', col: ' +
node.loc.start.column + ')'
);
}
state = utils.updateState(state, {
methodNode: node
});
utils.catchup(node.range[0], state);
path.unshift(node);
traverse(node.value, path, state);
path.shift();
return false;
}
visitClassMethod.test = function(node, path, state) {
return node.type === Syntax.MethodDefinition;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassFunctionExpression(traverse, node, path, state) {
var methodNode = path[0];
var isGetter = methodNode.kind === 'get';
var isSetter = methodNode.kind === 'set';
state = utils.updateState(state, {
methodFuncNode: node
});
if (methodNode.key.name === 'constructor') {
utils.append('function ' + state.className, state);
} else {
var methodAccessor;
var prototypeOrStatic = methodNode["static"] ? '' : '.prototype';
var objectAccessor = state.className + prototypeOrStatic;
if (methodNode.key.type === Syntax.Identifier) {
// foo() {}
methodAccessor = methodNode.key.name;
if (_shouldMungeIdentifier(methodNode.key, state)) {
methodAccessor = _getMungedName(methodAccessor, state);
}
if (isGetter || isSetter) {
methodAccessor = JSON.stringify(methodAccessor);
} else if (reservedWordsHelper.isReservedWord(methodAccessor)) {
methodAccessor = '[' + JSON.stringify(methodAccessor) + ']';
} else {
methodAccessor = '.' + methodAccessor;
}
} else if (methodNode.key.type === Syntax.Literal) {
// 'foo bar'() {} | get 'foo bar'() {} | set 'foo bar'() {}
methodAccessor = JSON.stringify(methodNode.key.value);
if (!(isGetter || isSetter)) {
methodAccessor = '[' + methodAccessor + ']';
}
}
if (isSetter || isGetter) {
utils.append(
'Object.defineProperty(' +
objectAccessor + ',' +
methodAccessor + ',' +
'{enumerable:true,configurable:true,' +
methodNode.kind + ':function',
state
);
} else {
utils.append(
objectAccessor +
methodAccessor + '=function' + (node.generator ? '*' : ''),
state
);
}
}
utils.move(methodNode.key.range[1], state);
utils.append('(', state);
var params = node.params;
if (params.length > 0) {
utils.move(params[0].range[0], state);
for (var i = 0; i < params.length; i++) {
utils.catchup(node.params[i].range[0], state);
path.unshift(node);
traverse(params[i], path, state);
path.shift();
}
}
utils.append(')', state);
utils.catchupWhiteSpace(node.body.range[0], state);
utils.append('{', state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
state = utils.updateState(state, {
scopeIsStrict: true
});
}
utils.move(node.body.range[0] + '{'.length, state);
path.unshift(node);
traverse(node.body, path, state);
path.shift();
utils.catchup(node.body.range[1], state);
if (methodNode.key.name !== 'constructor') {
if (isGetter || isSetter) {
utils.append('})', state);
}
utils.append(';', state);
}
return false;
}
visitClassFunctionExpression.test = function(node, path, state) {
return node.type === Syntax.FunctionExpression
&& path[0].type === Syntax.MethodDefinition;
};
function visitClassMethodParam(traverse, node, path, state) {
var paramName = node.name;
if (_shouldMungeIdentifier(node, state)) {
paramName = _getMungedName(node.name, state);
}
utils.append(paramName, state);
utils.move(node.range[1], state);
}
visitClassMethodParam.test = function(node, path, state) {
if (!path[0] || !path[1]) {
return;
}
var parentFuncExpr = path[0];
var parentClassMethod = path[1];
return parentFuncExpr.type === Syntax.FunctionExpression
&& parentClassMethod.type === Syntax.MethodDefinition
&& node.type === Syntax.Identifier;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function _renderClassBody(traverse, node, path, state) {
var className = state.className;
var superClass = state.superClass;
// Set up prototype of constructor on same line as `extends` for line-number
// preservation. This relies on function-hoisting if a constructor function is
// defined in the class body.
if (superClass.name) {
// If the super class is an expression, we need to memoize the output of the
// expression into the generated class name variable and use that to refer
// to the super class going forward. Example:
//
// class Foo extends mixin(Bar, Baz) {}
// --transforms to--
// function Foo() {} var ____Class0Blah = mixin(Bar, Baz);
if (superClass.expression !== null) {
utils.append(
'var ' + superClass.name + '=' + superClass.expression + ';',
state
);
}
var keyName = superClass.name + '____Key';
var keyNameDeclarator = '';
if (!utils.identWithinLexicalScope(keyName, state)) {
keyNameDeclarator = 'var ';
declareIdentInLocalScope(keyName, initScopeMetadata(node), state);
}
utils.append(
'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' +
'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' +
className + '[' + keyName + ']=' +
superClass.name + '[' + keyName + '];' +
'}' +
'}',
state
);
var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name;
if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) {
utils.append(
'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' +
'null:' + superClass.name + '.prototype;',
state
);
declareIdentInLocalScope(superProtoIdentStr, initScopeMetadata(node), state);
}
utils.append(
className + '.prototype=Object.create(' + superProtoIdentStr + ');',
state
);
utils.append(
className + '.prototype.constructor=' + className + ';',
state
);
utils.append(
className + '.__superConstructor__=' + superClass.name + ';',
state
);
}
// If there's no constructor method specified in the class body, create an
// empty constructor function at the top (same line as the class keyword)
if (!node.body.body.filter(_isConstructorMethod).pop()) {
utils.append('function ' + className + '(){', state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
}
if (superClass.name) {
utils.append(
'if(' + superClass.name + '!==null){' +
superClass.name + '.apply(this,arguments);}',
state
);
}
utils.append('}', state);
}
utils.move(node.body.range[0] + '{'.length, state);
traverse(node.body, path, state);
utils.catchupWhiteSpace(node.range[1], state);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassDeclaration(traverse, node, path, state) {
var className = node.id.name;
var superClass = _getSuperClassInfo(node, state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
return false;
}
visitClassDeclaration.test = function(node, path, state) {
return node.type === Syntax.ClassDeclaration;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassExpression(traverse, node, path, state) {
var className = node.id && node.id.name || _generateAnonymousClassName(state);
var superClass = _getSuperClassInfo(node, state);
utils.append('(function(){', state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
utils.append('return ' + className + ';})()', state);
return false;
}
visitClassExpression.test = function(node, path, state) {
return node.type === Syntax.ClassExpression;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitPrivateIdentifier(traverse, node, path, state) {
utils.append(_getMungedName(node.name, state), state);
utils.move(node.range[1], state);
}
visitPrivateIdentifier.test = function(node, path, state) {
if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) {
// Always munge non-computed properties of MemberExpressions
// (a la preventing access of properties of unowned objects)
if (path[0].type === Syntax.MemberExpression && path[0].object !== node
&& path[0].computed === false) {
return true;
}
// Always munge identifiers that were declared within the method function
// scope
if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) {
return true;
}
// Always munge private keys on object literals defined within a method's
// scope.
if (path[0].type === Syntax.Property
&& path[1].type === Syntax.ObjectExpression) {
return true;
}
// Always munge function parameters
if (path[0].type === Syntax.FunctionExpression
|| path[0].type === Syntax.FunctionDeclaration
|| path[0].type === Syntax.ArrowFunctionExpression) {
for (var i = 0; i < path[0].params.length; i++) {
if (path[0].params[i] === node) {
return true;
}
}
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperCallExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
if (node.callee.type === Syntax.Identifier) {
if (_isConstructorMethod(state.methodNode)) {
utils.append(superClassName + '.call(', state);
} else {
var protoProp = SUPER_PROTO_IDENT_PREFIX + superClassName;
if (state.methodNode.key.type === Syntax.Identifier) {
protoProp += '.' + state.methodNode.key.name;
} else if (state.methodNode.key.type === Syntax.Literal) {
protoProp += '[' + JSON.stringify(state.methodNode.key.value) + ']';
}
utils.append(protoProp + ".call(", state);
}
utils.move(node.callee.range[1], state);
} else if (node.callee.type === Syntax.MemberExpression) {
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.callee.object.range[1], state);
if (node.callee.computed) {
// ["a" + "b"]
utils.catchup(node.callee.property.range[1] + ']'.length, state);
} else {
// .ab
utils.append('.' + node.callee.property.name, state);
}
utils.append('.call(', state);
utils.move(node.callee.range[1], state);
}
utils.append('this', state);
if (node.arguments.length > 0) {
utils.append(',', state);
utils.catchupWhiteSpace(node.arguments[0].range[0], state);
traverse(node.arguments, path, state);
}
utils.catchupWhiteSpace(node.range[1], state);
utils.append(')', state);
return false;
}
visitSuperCallExpression.test = function(node, path, state) {
if (state.superClass && node.type === Syntax.CallExpression) {
var callee = node.callee;
if (callee.type === Syntax.Identifier && callee.name === 'super'
|| callee.type == Syntax.MemberExpression
&& callee.object.name === 'super') {
return true;
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperMemberExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.object.range[1], state);
}
visitSuperMemberExpression.test = function(node, path, state) {
return state.superClass
&& node.type === Syntax.MemberExpression
&& node.object.type === Syntax.Identifier
&& node.object.name === 'super';
};
exports.resetSymbols = resetSymbols;
exports.visitorList = [
visitClassDeclaration,
visitClassExpression,
visitClassFunctionExpression,
visitClassMethod,
visitClassMethodParam,
visitPrivateIdentifier,
visitSuperCallExpression,
visitSuperMemberExpression
];
},{"../src/utils":22,"./reserved-words-helper":32,"base62":9,"esprima-fb":8}],25:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, 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.
*/
/*global exports:true*/
/**
* Implements ES6 destructuring assignment and pattern matchng.
*
* function init({port, ip, coords: [x, y]}) {
* return (x && y) ? {id, port} : {ip};
* };
*
* function init($__0) {
* var
* port = $__0.port,
* ip = $__0.ip,
* $__1 = $__0.coords,
* x = $__1[0],
* y = $__1[1];
* return (x && y) ? {id, port} : {ip};
* }
*
* var x, {ip, port} = init({ip, port});
*
* var x, $__0 = init({ip, port}), ip = $__0.ip, port = $__0.port;
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
var restPropertyHelpers = _dereq_('./es7-rest-property-helpers');
// -------------------------------------------------------
// 1. Structured variable declarations.
//
// var [a, b] = [b, a];
// var {x, y} = {y, x};
// -------------------------------------------------------
function visitStructuredVariable(traverse, node, path, state) {
// Allocate new temp for the pattern.
utils.append(getTmpVar(state.localScope.tempVarIndex) + '=', state);
// Skip the pattern and assign the init to the temp.
utils.catchupWhiteSpace(node.init.range[0], state);
traverse(node.init, path, state);
utils.catchup(node.init.range[1], state);
// Render the destructured data.
utils.append(',' + getDestructuredComponents(node.id, state), state);
state.localScope.tempVarIndex++;
return false;
}
visitStructuredVariable.test = function(node, path, state) {
return node.type === Syntax.VariableDeclarator &&
isStructuredPattern(node.id);
};
function isStructuredPattern(node) {
return node.type === Syntax.ObjectPattern ||
node.type === Syntax.ArrayPattern;
}
// Main function which does actual recursive destructuring
// of nested complex structures.
function getDestructuredComponents(node, state) {
var tmpIndex = state.localScope.tempVarIndex;
var components = [];
var patternItems = getPatternItems(node);
for (var idx = 0; idx < patternItems.length; idx++) {
var item = patternItems[idx];
if (!item) {
continue;
}
if (item.type === Syntax.SpreadElement) {
// Spread/rest of an array.
// TODO(dmitrys): support spread in the middle of a pattern
// and also for function param patterns: [x, ...xs, y]
components.push(item.argument.name +
'=Array.prototype.slice.call(' +
getTmpVar(tmpIndex) + ',' + idx + ')'
);
continue;
}
if (item.type === Syntax.SpreadProperty) {
var restExpression = restPropertyHelpers.renderRestExpression(
getTmpVar(tmpIndex),
patternItems
);
components.push(item.argument.name + '=' + restExpression);
continue;
}
// Depending on pattern type (Array or Object), we get
// corresponding pattern item parts.
var accessor = getPatternItemAccessor(node, item, tmpIndex, idx);
var value = getPatternItemValue(node, item);
// TODO(dmitrys): implement default values: {x, y=5}
if (value.type === Syntax.Identifier) {
// Simple pattern item.
components.push(value.name + '=' + accessor);
} else {
// Complex sub-structure.
components.push(
getInitialValue(++state.localScope.tempVarIndex, accessor) + ',' +
getDestructuredComponents(value, state)
);
}
}
return components.join(',');
}
function getPatternItems(node) {
return node.properties || node.elements;
}
function getPatternItemAccessor(node, patternItem, tmpIndex, idx) {
var tmpName = getTmpVar(tmpIndex);
if (node.type === Syntax.ObjectPattern) {
if (reservedWordsHelper.isReservedWord(patternItem.key.name)) {
return tmpName + '["' + patternItem.key.name + '"]';
} else {
return tmpName + '.' + patternItem.key.name;
}
} else {
return tmpName + '[' + idx + ']';
}
}
function getPatternItemValue(node, patternItem) {
return node.type === Syntax.ObjectPattern
? patternItem.value
: patternItem;
}
function getInitialValue(index, value) {
return getTmpVar(index) + '=' + value;
}
function getTmpVar(index) {
return '$__' + index;
}
// -------------------------------------------------------
// 2. Assignment expression.
//
// [a, b] = [b, a];
// ({x, y} = {y, x});
// -------------------------------------------------------
function visitStructuredAssignment(traverse, node, path, state) {
var exprNode = node.expression;
utils.append('var ' + getTmpVar(state.localScope.tempVarIndex) + '=', state);
utils.catchupWhiteSpace(exprNode.right.range[0], state);
traverse(exprNode.right, path, state);
utils.catchup(exprNode.right.range[1], state);
utils.append(
',' + getDestructuredComponents(exprNode.left, state) + ';',
state
);
utils.catchupWhiteSpace(node.range[1], state);
state.localScope.tempVarIndex++;
return false;
}
visitStructuredAssignment.test = function(node, path, state) {
// We consider the expression statement rather than just assignment
// expression to cover case with object patters which should be
// wrapped in grouping operator: ({x, y} = {y, x});
return node.type === Syntax.ExpressionStatement &&
node.expression.type === Syntax.AssignmentExpression &&
isStructuredPattern(node.expression.left);
};
// -------------------------------------------------------
// 3. Structured parameter.
//
// function foo({x, y}) { ... }
// -------------------------------------------------------
function visitStructuredParameter(traverse, node, path, state) {
utils.append(getTmpVar(getParamIndex(node, path)), state);
utils.catchupWhiteSpace(node.range[1], state);
return true;
}
function getParamIndex(paramNode, path) {
var funcNode = path[0];
var tmpIndex = 0;
for (var k = 0; k < funcNode.params.length; k++) {
var param = funcNode.params[k];
if (param === paramNode) {
break;
}
if (isStructuredPattern(param)) {
tmpIndex++;
}
}
return tmpIndex;
}
visitStructuredParameter.test = function(node, path, state) {
return isStructuredPattern(node) && isFunctionNode(path[0]);
};
function isFunctionNode(node) {
return (node.type == Syntax.FunctionDeclaration ||
node.type == Syntax.FunctionExpression ||
node.type == Syntax.MethodDefinition ||
node.type == Syntax.ArrowFunctionExpression);
}
// -------------------------------------------------------
// 4. Function body for structured parameters.
//
// function foo({x, y}) { x; y; }
// -------------------------------------------------------
function visitFunctionBodyForStructuredParameter(traverse, node, path, state) {
var funcNode = path[0];
utils.catchup(funcNode.body.range[0] + 1, state);
renderDestructuredComponents(funcNode, state);
if (funcNode.rest) {
utils.append(
restParamVisitors.renderRestParamSetup(funcNode),
state
);
}
return true;
}
function renderDestructuredComponents(funcNode, state) {
var destructuredComponents = [];
for (var k = 0; k < funcNode.params.length; k++) {
var param = funcNode.params[k];
if (isStructuredPattern(param)) {
destructuredComponents.push(
getDestructuredComponents(param, state)
);
state.localScope.tempVarIndex++;
}
}
if (destructuredComponents.length) {
utils.append('var ' + destructuredComponents.join(',') + ';', state);
}
}
visitFunctionBodyForStructuredParameter.test = function(node, path, state) {
return node.type === Syntax.BlockStatement && isFunctionNode(path[0]);
};
exports.visitorList = [
visitStructuredVariable,
visitStructuredAssignment,
visitStructuredParameter,
visitFunctionBodyForStructuredParameter
];
exports.renderDestructuredComponents = renderDestructuredComponents;
},{"../src/utils":22,"./es6-rest-param-visitors":28,"./es7-rest-property-helpers":30,"./reserved-words-helper":32,"esprima-fb":8}],26:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node:true*/
/**
* Desugars concise methods of objects to function expressions.
*
* var foo = {
* method(x, y) { ... }
* };
*
* var foo = {
* method: function(x, y) { ... }
* };
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
function visitObjectConciseMethod(traverse, node, path, state) {
var isGenerator = node.value.generator;
if (isGenerator) {
utils.catchupWhiteSpace(node.range[0] + 1, state);
}
if (node.computed) { // [<expr>]() { ...}
utils.catchup(node.key.range[1] + 1, state);
} else if (reservedWordsHelper.isReservedWord(node.key.name)) {
utils.catchup(node.key.range[0], state);
utils.append('"', state);
utils.catchup(node.key.range[1], state);
utils.append('"', state);
}
utils.catchup(node.key.range[1], state);
utils.append(
':function' + (isGenerator ? '*' : ''),
state
);
path.unshift(node);
traverse(node.value, path, state);
path.shift();
return false;
}
visitObjectConciseMethod.test = function(node, path, state) {
return node.type === Syntax.Property &&
node.value.type === Syntax.FunctionExpression &&
node.method === true;
};
exports.visitorList = [
visitObjectConciseMethod
];
},{"../src/utils":22,"./reserved-words-helper":32,"esprima-fb":8}],27:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node: true*/
/**
* Desugars ES6 Object Literal short notations into ES3 full notation.
*
* // Easier return values.
* function foo(x, y) {
* return {x, y}; // {x: x, y: y}
* };
*
* // Destrucruting.
* function init({port, ip, coords: {x, y}}) { ... }
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitObjectLiteralShortNotation(traverse, node, path, state) {
utils.catchup(node.key.range[1], state);
utils.append(':' + node.key.name, state);
return false;
}
visitObjectLiteralShortNotation.test = function(node, path, state) {
return node.type === Syntax.Property &&
node.kind === 'init' &&
node.shorthand === true &&
path[0].type !== Syntax.ObjectPattern;
};
exports.visitorList = [
visitObjectLiteralShortNotation
];
},{"../src/utils":22,"esprima-fb":8}],28:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node:true*/
/**
* Desugars ES6 rest parameters into ES3 arguments slicing.
*
* function printf(template, ...args) {
* args.forEach(...);
* };
*
* function printf(template) {
* var args = [].slice.call(arguments, 1);
* args.forEach(...);
* };
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function _nodeIsFunctionWithRestParam(node) {
return (node.type === Syntax.FunctionDeclaration
|| node.type === Syntax.FunctionExpression
|| node.type === Syntax.ArrowFunctionExpression)
&& node.rest;
}
function visitFunctionParamsWithRestParam(traverse, node, path, state) {
if (node.parametricType) {
utils.catchup(node.parametricType.range[0], state);
path.unshift(node);
traverse(node.parametricType, path, state);
path.shift();
}
// Render params.
if (node.params.length) {
path.unshift(node);
traverse(node.params, path, state);
path.shift();
} else {
// -3 is for ... of the rest.
utils.catchup(node.rest.range[0] - 3, state);
}
utils.catchupWhiteSpace(node.rest.range[1], state);
path.unshift(node);
traverse(node.body, path, state);
path.shift();
return false;
}
visitFunctionParamsWithRestParam.test = function(node, path, state) {
return _nodeIsFunctionWithRestParam(node);
};
function renderRestParamSetup(functionNode) {
return 'var ' + functionNode.rest.name + '=Array.prototype.slice.call(' +
'arguments,' +
functionNode.params.length +
');';
}
function visitFunctionBodyWithRestParam(traverse, node, path, state) {
utils.catchup(node.range[0] + 1, state);
var parentNode = path[0];
utils.append(renderRestParamSetup(parentNode), state);
return true;
}
visitFunctionBodyWithRestParam.test = function(node, path, state) {
return node.type === Syntax.BlockStatement
&& _nodeIsFunctionWithRestParam(path[0]);
};
exports.renderRestParamSetup = renderRestParamSetup;
exports.visitorList = [
visitFunctionParamsWithRestParam,
visitFunctionBodyWithRestParam
];
},{"../src/utils":22,"esprima-fb":8}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9
*/
function visitTemplateLiteral(traverse, node, path, state) {
var templateElements = node.quasis;
utils.append('(', state);
for (var ii = 0; ii < templateElements.length; ii++) {
var templateElement = templateElements[ii];
if (templateElement.value.raw !== '') {
utils.append(getCookedValue(templateElement), state);
if (!templateElement.tail) {
// + between element and substitution
utils.append(' + ', state);
}
// maintain line numbers
utils.move(templateElement.range[0], state);
utils.catchupNewlines(templateElement.range[1], state);
} else { // templateElement.value.raw === ''
// Concatenat adjacent substitutions, e.g. `${x}${y}`. Empty templates
// appear before the first and after the last element - nothing to add in
// those cases.
if (ii > 0 && !templateElement.tail) {
// + between substitution and substitution
utils.append(' + ', state);
}
}
utils.move(templateElement.range[1], state);
if (!templateElement.tail) {
var substitution = node.expressions[ii];
if (substitution.type === Syntax.Identifier ||
substitution.type === Syntax.MemberExpression ||
substitution.type === Syntax.CallExpression) {
utils.catchup(substitution.range[1], state);
} else {
utils.append('(', state);
traverse(substitution, path, state);
utils.catchup(substitution.range[1], state);
utils.append(')', state);
}
// if next templateElement isn't empty...
if (templateElements[ii + 1].value.cooked !== '') {
utils.append(' + ', state);
}
}
}
utils.move(node.range[1], state);
utils.append(')', state);
return false;
}
visitTemplateLiteral.test = function(node, path, state) {
return node.type === Syntax.TemplateLiteral;
};
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6
*/
function visitTaggedTemplateExpression(traverse, node, path, state) {
var template = node.quasi;
var numQuasis = template.quasis.length;
// print the tag
utils.move(node.tag.range[0], state);
traverse(node.tag, path, state);
utils.catchup(node.tag.range[1], state);
// print array of template elements
utils.append('(function() { var siteObj = [', state);
for (var ii = 0; ii < numQuasis; ii++) {
utils.append(getCookedValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(']; siteObj.raw = [', state);
for (ii = 0; ii < numQuasis; ii++) {
utils.append(getRawValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(
']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()',
state
);
// print substitutions
if (numQuasis > 1) {
for (ii = 0; ii < template.expressions.length; ii++) {
var expression = template.expressions[ii];
utils.append(', ', state);
// maintain line numbers by calling catchupWhiteSpace over the whole
// previous TemplateElement
utils.move(template.quasis[ii].range[0], state);
utils.catchupNewlines(template.quasis[ii].range[1], state);
utils.move(expression.range[0], state);
traverse(expression, path, state);
utils.catchup(expression.range[1], state);
}
}
// print blank lines to push the closing ) down to account for the final
// TemplateElement.
utils.catchupNewlines(node.range[1], state);
utils.append(')', state);
return false;
}
visitTaggedTemplateExpression.test = function(node, path, state) {
return node.type === Syntax.TaggedTemplateExpression;
};
function getCookedValue(templateElement) {
return JSON.stringify(templateElement.value.cooked);
}
function getRawValue(templateElement) {
return JSON.stringify(templateElement.value.raw);
}
exports.visitorList = [
visitTemplateLiteral,
visitTaggedTemplateExpression
];
},{"../src/utils":22,"esprima-fb":8}],30:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, 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.
*/
/*jslint node:true*/
/**
* Desugars ES7 rest properties into ES5 object iteration.
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
// TODO: This is a pretty massive helper, it should only be defined once, in the
// transform's runtime environment. We don't currently have a runtime though.
var restFunction =
'(function(source, exclusion) {' +
'var rest = {};' +
'var hasOwn = Object.prototype.hasOwnProperty;' +
'if (source == null) {' +
'throw new TypeError();' +
'}' +
'for (var key in source) {' +
'if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {' +
'rest[key] = source[key];' +
'}' +
'}' +
'return rest;' +
'})';
function getPropertyNames(properties) {
var names = [];
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
if (property.type === Syntax.SpreadProperty) {
continue;
}
if (property.type === Syntax.Identifier) {
names.push(property.name);
} else {
names.push(property.key.name);
}
}
return names;
}
function getRestFunctionCall(source, exclusion) {
return restFunction + '(' + source + ',' + exclusion + ')';
}
function getSimpleShallowCopy(accessorExpression) {
// This could be faster with 'Object.assign({}, ' + accessorExpression + ')'
// but to unify code paths and avoid a ES6 dependency we use the same
// helper as for the exclusion case.
return getRestFunctionCall(accessorExpression, '{}');
}
function renderRestExpression(accessorExpression, excludedProperties) {
var excludedNames = getPropertyNames(excludedProperties);
if (!excludedNames.length) {
return getSimpleShallowCopy(accessorExpression);
}
return getRestFunctionCall(
accessorExpression,
'{' + excludedNames.join(':1,') + ':1}'
);
}
exports.renderRestExpression = renderRestExpression;
},{"../src/utils":22,"esprima-fb":8}],31:[function(_dereq_,module,exports){
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
/*global exports:true*/
/**
* Implements ES7 object spread property.
* https://gist.github.com/sebmarkbage/aa849c7973cb4452c547
*
* { ...a, x: 1 }
*
* Object.assign({}, a, {x: 1 })
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function visitObjectLiteralSpread(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.append('Object.assign({', state);
// Skip the original {
utils.move(node.range[0] + 1, state);
var previousWasSpread = false;
for (var i = 0; i < node.properties.length; i++) {
var property = node.properties[i];
if (property.type === Syntax.SpreadProperty) {
// Close the previous object or initial object
if (!previousWasSpread) {
utils.append('}', state);
}
if (i === 0) {
// Normally there will be a comma when we catch up, but not before
// the first property.
utils.append(',', state);
}
utils.catchup(property.range[0], state);
// skip ...
utils.move(property.range[0] + 3, state);
traverse(property.argument, path, state);
utils.catchup(property.range[1], state);
previousWasSpread = true;
} else {
utils.catchup(property.range[0], state);
if (previousWasSpread) {
utils.append('{', state);
}
traverse(property, path, state);
utils.catchup(property.range[1], state);
previousWasSpread = false;
}
}
utils.catchup(node.range[1] - 1, state);
// Skip the trailing }
utils.move(node.range[1], state);
if (!previousWasSpread) {
utils.append('}', state);
}
utils.append(')', state);
return false;
}
visitObjectLiteralSpread.test = function(node, path, state) {
if (node.type !== Syntax.ObjectExpression) {
return false;
}
// Tight loop optimization
var hasAtLeastOneSpreadProperty = false;
for (var i = 0; i < node.properties.length; i++) {
var property = node.properties[i];
if (property.type === Syntax.SpreadProperty) {
hasAtLeastOneSpreadProperty = true;
} else if (property.kind !== 'init') {
return false;
}
}
return hasAtLeastOneSpreadProperty;
};
exports.visitorList = [
visitObjectLiteralSpread
];
},{"../src/utils":22,"esprima-fb":8}],32:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, 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.
*/
var KEYWORDS = [
'break', 'do', 'in', 'typeof', 'case', 'else', 'instanceof', 'var', 'catch',
'export', 'new', 'void', 'class', 'extends', 'return', 'while', 'const',
'finally', 'super', 'with', 'continue', 'for', 'switch', 'yield', 'debugger',
'function', 'this', 'default', 'if', 'throw', 'delete', 'import', 'try'
];
var FUTURE_RESERVED_WORDS = [
'enum', 'await', 'implements', 'package', 'protected', 'static', 'interface',
'private', 'public'
];
var LITERALS = [
'null',
'true',
'false'
];
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words
var RESERVED_WORDS = [].concat(
KEYWORDS,
FUTURE_RESERVED_WORDS,
LITERALS
);
var reservedWordsMap = {};
RESERVED_WORDS.forEach(function(k) {
reservedWordsMap[k] = true;
});
exports.isReservedWord = function(word) {
return !!reservedWordsMap[word];
};
},{}],33:[function(_dereq_,module,exports){
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('jstransform/src/utils');
var Syntax = esprima.Syntax;
function _isFunctionNode(node) {
return node.type === Syntax.FunctionDeclaration
|| node.type === Syntax.FunctionExpression
|| node.type === Syntax.ArrowFunctionExpression;
}
function visitClassProperty(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitClassProperty.test = function(node, path, state) {
return node.type === Syntax.ClassProperty;
};
function visitFunctionParametricAnnotation(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitFunctionParametricAnnotation.test = function(node, path, state) {
return node.type === Syntax.ParametricTypeAnnotation
&& path[0]
&& _isFunctionNode(path[0])
&& node === path[0].parametricType;
};
function visitFunctionReturnAnnotation(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitFunctionReturnAnnotation.test = function(node, path, state) {
return path[0] && _isFunctionNode(path[0]) && node === path[0].returnType;
};
function visitOptionalFunctionParameterAnnotation(traverse, node, path, state) {
path.unshift(node);
traverse(node.id, path, state);
path.shift();
utils.catchup(node.id.range[1], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitOptionalFunctionParameterAnnotation.test = function(node, path, state) {
return node.type === Syntax.OptionalParameter
&& path[0]
&& _isFunctionNode(path[0]);
};
function visitTypeAnnotatedIdentifier(traverse, node, path, state) {
traverse(node.id, path, state);
utils.catchup(node.id.range[1], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitTypeAnnotatedIdentifier.test = function(node, path, state) {
return node.type === Syntax.TypeAnnotatedIdentifier;
};
exports.visitorList = [
visitClassProperty,
visitFunctionParametricAnnotation,
visitFunctionReturnAnnotation,
visitOptionalFunctionParameterAnnotation,
visitTypeAnnotatedIdentifier
];
},{"esprima-fb":8,"jstransform/src/utils":22}],34:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*/
/*global exports:true*/
"use strict";
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('jstransform/src/utils');
var FALLBACK_TAGS = _dereq_('./xjs').knownTags;
var renderXJSExpressionContainer =
_dereq_('./xjs').renderXJSExpressionContainer;
var renderXJSLiteral = _dereq_('./xjs').renderXJSLiteral;
var quoteAttrName = _dereq_('./xjs').quoteAttrName;
var trimLeft = _dereq_('./xjs').trimLeft;
/**
* Customized desugar processor for React JSX. Currently:
*
* <X> </X> => React.createElement(X, null)
* <X prop="1" /> => React.createElement(X, {prop: '1'}, null)
* <X prop="2"><Y /></X> => React.createElement(X, {prop:'2'},
* React.createElement(Y, null)
* )
* <div /> => React.createElement("div", null)
*/
/**
* Removes all non-whitespace/parenthesis characters
*/
var reNonWhiteParen = /([^\s\(\)])/g;
function stripNonWhiteParen(value) {
return value.replace(reNonWhiteParen, '');
}
var tagConvention = /^[a-z]|\-/;
function isTagName(name) {
return tagConvention.test(name);
}
function visitReactTag(traverse, object, path, state) {
var openingElement = object.openingElement;
var nameObject = openingElement.name;
var attributesObject = openingElement.attributes;
utils.catchup(openingElement.range[0], state, trimLeft);
if (nameObject.type === Syntax.XJSNamespacedName && nameObject.namespace) {
throw new Error('Namespace tags are not supported. ReactJSX is not XML.');
}
// We assume that the React runtime is already in scope
utils.append('React.createElement(', state);
// Identifiers with lower case or hypthens are fallback tags (strings).
// XJSMemberExpressions are not.
if (nameObject.type === Syntax.XJSIdentifier && isTagName(nameObject.name)) {
// This is a temporary error message to assist upgrades
if (!FALLBACK_TAGS.hasOwnProperty(nameObject.name)) {
throw new Error(
'Lower case component names (' + nameObject.name + ') are no longer ' +
'supported in JSX: See http://fb.me/react-jsx-lower-case'
);
}
utils.append('"' + nameObject.name + '"', state);
utils.move(nameObject.range[1], state);
} else {
// Use utils.catchup in this case so we can easily handle
// XJSMemberExpressions which look like Foo.Bar.Baz. This also handles
// XJSIdentifiers that aren't fallback tags.
utils.move(nameObject.range[0], state);
utils.catchup(nameObject.range[1], state);
}
utils.append(', ', state);
var hasAttributes = attributesObject.length;
var hasAtLeastOneSpreadProperty = attributesObject.some(function(attr) {
return attr.type === Syntax.XJSSpreadAttribute;
});
// if we don't have any attributes, pass in null
if (hasAtLeastOneSpreadProperty) {
utils.append('React.__spread({', state);
} else if (hasAttributes) {
utils.append('{', state);
} else {
utils.append('null', state);
}
// keep track of if the previous attribute was a spread attribute
var previousWasSpread = false;
// write attributes
attributesObject.forEach(function(attr, index) {
var isLast = index === attributesObject.length - 1;
if (attr.type === Syntax.XJSSpreadAttribute) {
// Close the previous object or initial object
if (!previousWasSpread) {
utils.append('}, ', state);
}
// Move to the expression start, ignoring everything except parenthesis
// and whitespace.
utils.catchup(attr.range[0], state, stripNonWhiteParen);
// Plus 1 to skip `{`.
utils.move(attr.range[0] + 1, state);
utils.catchup(attr.argument.range[0], state, stripNonWhiteParen);
traverse(attr.argument, path, state);
utils.catchup(attr.argument.range[1], state);
// Move to the end, ignoring parenthesis and the closing `}`
utils.catchup(attr.range[1] - 1, state, stripNonWhiteParen);
if (!isLast) {
utils.append(', ', state);
}
utils.move(attr.range[1], state);
previousWasSpread = true;
return;
}
// If the next attribute is a spread, we're effective last in this object
if (!isLast) {
isLast = attributesObject[index + 1].type === Syntax.XJSSpreadAttribute;
}
if (attr.name.namespace) {
throw new Error(
'Namespace attributes are not supported. ReactJSX is not XML.');
}
var name = attr.name.name;
utils.catchup(attr.range[0], state, trimLeft);
if (previousWasSpread) {
utils.append('{', state);
}
utils.append(quoteAttrName(name), state);
utils.append(': ', state);
if (!attr.value) {
state.g.buffer += 'true';
state.g.position = attr.name.range[1];
if (!isLast) {
utils.append(', ', state);
}
} else {
utils.move(attr.name.range[1], state);
// Use catchupNewlines to skip over the '=' in the attribute
utils.catchupNewlines(attr.value.range[0], state);
if (attr.value.type === Syntax.Literal) {
renderXJSLiteral(attr.value, isLast, state);
} else {
renderXJSExpressionContainer(traverse, attr.value, isLast, path, state);
}
}
utils.catchup(attr.range[1], state, trimLeft);
previousWasSpread = false;
});
if (!openingElement.selfClosing) {
utils.catchup(openingElement.range[1] - 1, state, trimLeft);
utils.move(openingElement.range[1], state);
}
if (hasAttributes && !previousWasSpread) {
utils.append('}', state);
}
if (hasAtLeastOneSpreadProperty) {
utils.append(')', state);
}
// filter out whitespace
var childrenToRender = object.children.filter(function(child) {
return !(child.type === Syntax.Literal
&& typeof child.value === 'string'
&& child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/));
});
if (childrenToRender.length > 0) {
var lastRenderableIndex;
childrenToRender.forEach(function(child, index) {
if (child.type !== Syntax.XJSExpressionContainer ||
child.expression.type !== Syntax.XJSEmptyExpression) {
lastRenderableIndex = index;
}
});
if (lastRenderableIndex !== undefined) {
utils.append(', ', state);
}
childrenToRender.forEach(function(child, index) {
utils.catchup(child.range[0], state, trimLeft);
var isLast = index >= lastRenderableIndex;
if (child.type === Syntax.Literal) {
renderXJSLiteral(child, isLast, state);
} else if (child.type === Syntax.XJSExpressionContainer) {
renderXJSExpressionContainer(traverse, child, isLast, path, state);
} else {
traverse(child, path, state);
if (!isLast) {
utils.append(', ', state);
}
}
utils.catchup(child.range[1], state, trimLeft);
});
}
if (openingElement.selfClosing) {
// everything up to />
utils.catchup(openingElement.range[1] - 2, state, trimLeft);
utils.move(openingElement.range[1], state);
} else {
// everything up to </ sdflksjfd>
utils.catchup(object.closingElement.range[0], state, trimLeft);
utils.move(object.closingElement.range[1], state);
}
utils.append(')', state);
return false;
}
visitReactTag.test = function(object, path, state) {
return object.type === Syntax.XJSElement;
};
exports.visitorList = [
visitReactTag
];
},{"./xjs":36,"esprima-fb":8,"jstransform/src/utils":22}],35:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*/
/*global exports:true*/
"use strict";
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('jstransform/src/utils');
function addDisplayName(displayName, object, state) {
if (object &&
object.type === Syntax.CallExpression &&
object.callee.type === Syntax.MemberExpression &&
object.callee.object.type === Syntax.Identifier &&
object.callee.object.name === 'React' &&
object.callee.property.type === Syntax.Identifier &&
object.callee.property.name === 'createClass' &&
object['arguments'].length === 1 &&
object['arguments'][0].type === Syntax.ObjectExpression) {
// Verify that the displayName property isn't already set
var properties = object['arguments'][0].properties;
var safe = properties.every(function(property) {
var value = property.key.type === Syntax.Identifier ?
property.key.name :
property.key.value;
return value !== 'displayName';
});
if (safe) {
utils.catchup(object['arguments'][0].range[0] + 1, state);
utils.append("displayName: '" + displayName + "',", state);
}
}
}
/**
* Transforms the following:
*
* var MyComponent = React.createClass({
* render: ...
* });
*
* into:
*
* var MyComponent = React.createClass({
* displayName: 'MyComponent',
* render: ...
* });
*
* Also catches:
*
* MyComponent = React.createClass(...);
* exports.MyComponent = React.createClass(...);
* module.exports = {MyComponent: React.createClass(...)};
*/
function visitReactDisplayName(traverse, object, path, state) {
var left, right;
if (object.type === Syntax.AssignmentExpression) {
left = object.left;
right = object.right;
} else if (object.type === Syntax.Property) {
left = object.key;
right = object.value;
} else if (object.type === Syntax.VariableDeclarator) {
left = object.id;
right = object.init;
}
if (left && left.type === Syntax.MemberExpression) {
left = left.property;
}
if (left && left.type === Syntax.Identifier) {
addDisplayName(left.name, right, state);
}
}
visitReactDisplayName.test = function(object, path, state) {
return (
object.type === Syntax.AssignmentExpression ||
object.type === Syntax.Property ||
object.type === Syntax.VariableDeclarator
);
};
exports.visitorList = [
visitReactDisplayName
];
},{"esprima-fb":8,"jstransform/src/utils":22}],36:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*/
/*global exports:true*/
"use strict";
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('jstransform/src/utils');
var knownTags = {
a: true,
abbr: true,
address: true,
applet: true,
area: true,
article: true,
aside: true,
audio: true,
b: true,
base: true,
bdi: true,
bdo: true,
big: true,
blockquote: true,
body: true,
br: true,
button: true,
canvas: true,
caption: true,
circle: true,
cite: true,
code: true,
col: true,
colgroup: true,
command: true,
data: true,
datalist: true,
dd: true,
defs: true,
del: true,
details: true,
dfn: true,
dialog: true,
div: true,
dl: true,
dt: true,
ellipse: true,
em: true,
embed: true,
fieldset: true,
figcaption: true,
figure: true,
footer: true,
form: true,
g: true,
h1: true,
h2: true,
h3: true,
h4: true,
h5: true,
h6: true,
head: true,
header: true,
hgroup: true,
hr: true,
html: true,
i: true,
iframe: true,
img: true,
input: true,
ins: true,
kbd: true,
keygen: true,
label: true,
legend: true,
li: true,
line: true,
linearGradient: true,
link: true,
main: true,
map: true,
mark: true,
marquee: true,
mask: false,
menu: true,
menuitem: true,
meta: true,
meter: true,
nav: true,
noscript: true,
object: true,
ol: true,
optgroup: true,
option: true,
output: true,
p: true,
param: true,
path: true,
pattern: false,
picture: true,
polygon: true,
polyline: true,
pre: true,
progress: true,
q: true,
radialGradient: true,
rect: true,
rp: true,
rt: true,
ruby: true,
s: true,
samp: true,
script: true,
section: true,
select: true,
small: true,
source: true,
span: true,
stop: true,
strong: true,
style: true,
sub: true,
summary: true,
sup: true,
svg: true,
table: true,
tbody: true,
td: true,
text: true,
textarea: true,
tfoot: true,
th: true,
thead: true,
time: true,
title: true,
tr: true,
track: true,
tspan: true,
u: true,
ul: true,
'var': true,
video: true,
wbr: true
};
function renderXJSLiteral(object, isLast, state, start, end) {
var lines = object.value.split(/\r\n|\n|\r/);
if (start) {
utils.append(start, state);
}
var lastNonEmptyLine = 0;
lines.forEach(function (line, index) {
if (line.match(/[^ \t]/)) {
lastNonEmptyLine = index;
}
});
lines.forEach(function (line, index) {
var isFirstLine = index === 0;
var isLastLine = index === lines.length - 1;
var isLastNonEmptyLine = index === lastNonEmptyLine;
// replace rendered whitespace tabs with spaces
var trimmedLine = line.replace(/\t/g, ' ');
// trim whitespace touching a newline
if (!isFirstLine) {
trimmedLine = trimmedLine.replace(/^[ ]+/, '');
}
if (!isLastLine) {
trimmedLine = trimmedLine.replace(/[ ]+$/, '');
}
if (!isFirstLine) {
utils.append(line.match(/^[ \t]*/)[0], state);
}
if (trimmedLine || isLastNonEmptyLine) {
utils.append(
JSON.stringify(trimmedLine) +
(!isLastNonEmptyLine ? " + ' ' +" : ''),
state);
if (isLastNonEmptyLine) {
if (end) {
utils.append(end, state);
}
if (!isLast) {
utils.append(', ', state);
}
}
// only restore tail whitespace if line had literals
if (trimmedLine && !isLastLine) {
utils.append(line.match(/[ \t]*$/)[0], state);
}
}
if (!isLastLine) {
utils.append('\n', state);
}
});
utils.move(object.range[1], state);
}
function renderXJSExpressionContainer(traverse, object, isLast, path, state) {
// Plus 1 to skip `{`.
utils.move(object.range[0] + 1, state);
traverse(object.expression, path, state);
if (!isLast && object.expression.type !== Syntax.XJSEmptyExpression) {
// If we need to append a comma, make sure to do so after the expression.
utils.catchup(object.expression.range[1], state, trimLeft);
utils.append(', ', state);
}
// Minus 1 to skip `}`.
utils.catchup(object.range[1] - 1, state, trimLeft);
utils.move(object.range[1], state);
return false;
}
function quoteAttrName(attr) {
// Quote invalid JS identifiers.
if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) {
return "'" + attr + "'";
}
return attr;
}
function trimLeft(value) {
return value.replace(/^[ ]+/, '');
}
exports.knownTags = knownTags;
exports.renderXJSExpressionContainer = renderXJSExpressionContainer;
exports.renderXJSLiteral = renderXJSLiteral;
exports.quoteAttrName = quoteAttrName;
exports.trimLeft = trimLeft;
},{"esprima-fb":8,"jstransform/src/utils":22}],37:[function(_dereq_,module,exports){
/*global exports:true*/
var es6ArrowFunctions = _dereq_('jstransform/visitors/es6-arrow-function-visitors');
var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors');
var es6Destructuring = _dereq_('jstransform/visitors/es6-destructuring-visitors');
var es6ObjectConciseMethod = _dereq_('jstransform/visitors/es6-object-concise-method-visitors');
var es6ObjectShortNotation = _dereq_('jstransform/visitors/es6-object-short-notation-visitors');
var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors');
var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors');
var es7SpreadProperty = _dereq_('jstransform/visitors/es7-spread-property-visitors');
var react = _dereq_('./transforms/react');
var reactDisplayName = _dereq_('./transforms/reactDisplayName');
var typesSyntax = _dereq_('jstransform/visitors/type-syntax');
/**
* Map from transformName => orderedListOfVisitors.
*/
var transformVisitors = {
'es6-arrow-functions': es6ArrowFunctions.visitorList,
'es6-classes': es6Classes.visitorList,
'es6-destructuring': es6Destructuring.visitorList,
'es6-object-concise-method': es6ObjectConciseMethod.visitorList,
'es6-object-short-notation': es6ObjectShortNotation.visitorList,
'es6-rest-params': es6RestParameters.visitorList,
'es6-templates': es6Templates.visitorList,
'es7-spread-property': es7SpreadProperty.visitorList,
'react': react.visitorList.concat(reactDisplayName.visitorList),
'types': typesSyntax.visitorList
};
var transformSets = {
'harmony': [
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
'es7-spread-property'
],
'react': [
'react'
],
'type-annotations': [
'types'
]
};
/**
* Specifies the order in which each transform should run.
*/
var transformRunOrder = [
'types',
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
'es7-spread-property',
'react'
];
/**
* Given a list of transform names, return the ordered list of visitors to be
* passed to the transform() function.
*
* @param {array?} excludes
* @return {array}
*/
function getAllVisitors(excludes) {
var ret = [];
for (var i = 0, il = transformRunOrder.length; i < il; i++) {
if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) {
ret = ret.concat(transformVisitors[transformRunOrder[i]]);
}
}
return ret;
}
/**
* Given a list of visitor set names, return the ordered list of visitors to be
* passed to jstransform.
*
* @param {array}
* @return {array}
*/
function getVisitorsBySet(sets) {
var visitorsToInclude = sets.reduce(function(visitors, set) {
if (!transformSets.hasOwnProperty(set)) {
throw new Error('Unknown visitor set: ' + set);
}
transformSets[set].forEach(function(visitor) {
visitors[visitor] = true;
});
return visitors;
}, {});
var visitorList = [];
for (var i = 0; i < transformRunOrder.length; i++) {
if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) {
visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]);
}
}
return visitorList;
}
exports.getVisitorsBySet = getVisitorsBySet;
exports.getAllVisitors = getAllVisitors;
exports.transformVisitors = transformVisitors;
},{"./transforms/react":34,"./transforms/reactDisplayName":35,"jstransform/visitors/es6-arrow-function-visitors":23,"jstransform/visitors/es6-class-visitors":24,"jstransform/visitors/es6-destructuring-visitors":25,"jstransform/visitors/es6-object-concise-method-visitors":26,"jstransform/visitors/es6-object-short-notation-visitors":27,"jstransform/visitors/es6-rest-param-visitors":28,"jstransform/visitors/es6-template-visitors":29,"jstransform/visitors/es7-spread-property-visitors":31,"jstransform/visitors/type-syntax":33}]},{},[1])(1)
}); |
src/components/metadata/MetaSimple.js | jekyll/jekyll-admin | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TextareaAutosize from 'react-textarea-autosize';
import DateTimePicker from 'react-widgets/lib/DateTimePicker';
import DropdownList from 'react-widgets/lib/DropdownList';
import moment from 'moment';
import momentLocalizer from 'react-widgets-moment';
import FilePicker from '../FilePicker';
import MetaTags from './MetaTags';
import 'react-widgets/dist/css/react-widgets.css';
momentLocalizer(moment);
export class MetaSimple extends Component {
handleEditableChange = e => {
const { nameAttr, updateFieldValue } = this.props;
updateFieldValue(nameAttr, e.target.value);
};
handleDatepickerChange = (date, dateStr) => {
const { nameAttr, updateFieldValue } = this.props;
let formatted = moment(date).format('YYYY-MM-DD HH:mm:ss');
updateFieldValue(nameAttr, formatted);
};
handleEditableBlur = e => {
const { nameAttr, updateFieldValue } = this.props;
updateFieldValue(nameAttr, e.target.value.trim());
};
renderEditable() {
const { fieldValue } = this.props;
return (
<TextareaAutosize
onChange={this.handleEditableChange}
onBlur={this.handleEditableBlur}
className="field value-field"
value={`${fieldValue}`}
/>
);
}
renderDatepicker() {
const { fieldValue } = this.props;
let dateValue = new Date(fieldValue);
if (`${dateValue}` === 'Invalid Date') dateValue = null;
return (
<DateTimePicker
onChange={this.handleDatepickerChange}
className="date-field"
value={dateValue}
/>
);
}
onPickItem = path => {
const { nameAttr, updateFieldValue } = this.props;
this.refs.imagepicker.value = path;
updateFieldValue(nameAttr, path);
};
renderStaticFilePicker() {
const { fieldValue } = this.props;
return (
<div className="imagepicker">
<TextareaAutosize
onChange={this.handleEditableChange}
className="field value-field"
value={fieldValue}
ref="imagepicker"
/>
<FilePicker onPick={this.onPickItem} />
</div>
);
}
handleLayoutChange = value => {
const { nameAttr, updateFieldValue } = this.props;
updateFieldValue(nameAttr, value);
};
renderLayoutPicker() {
const { fieldValue, siteMeta } = this.props;
if (!siteMeta) return this.renderEditable();
const layouts = siteMeta.layouts || [];
return (
<DropdownList
className="layout-field"
data={['none', ...layouts]}
defaultValue={fieldValue}
onChange={this.handleLayoutChange}
/>
);
}
renderTagsInput(key) {
const { fieldValue, nameAttr, updateFieldValue, siteMeta } = this.props;
const suggestions = (siteMeta && siteMeta[key]) || [];
return (
<MetaTags
fieldValue={fieldValue}
nameAttr={nameAttr}
updateFieldValue={updateFieldValue}
suggestions={suggestions}
/>
);
}
render() {
const { fieldKey, nameAttr } = this.props;
let node;
switch (fieldKey) {
case 'date':
node = this.renderDatepicker();
break;
case 'image':
case 'file':
node = this.renderStaticFilePicker();
break;
case 'tags':
case 'categories':
node = this.renderTagsInput(fieldKey);
break;
default:
node = this.renderEditable();
}
if (nameAttr === "metadata['layout']") {
node = this.renderLayoutPicker();
}
return <div className="meta-value">{node}</div>;
}
}
MetaSimple.propTypes = {
parentType: PropTypes.string.isRequired,
fieldKey: PropTypes.string.isRequired,
fieldValue: PropTypes.any,
updateFieldValue: PropTypes.func.isRequired,
nameAttr: PropTypes.any.isRequired,
siteMeta: PropTypes.object,
};
export default MetaSimple;
|
docs/app/Examples/modules/Progress/States/index.js | aabustamante/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
import { Message } from 'semantic-ui-react'
const ProgressStatesExamples = () => (
<ExampleSection title='States'>
<Message info>
Semantic UI states <code>success</code>, <code>warning</code>, and <code>error</code>
{' '}are only retained at 100% completion.
</Message>
<ComponentExample
title='Active'
description='A progress bar can show activity.'
examplePath='modules/Progress/States/ProgressExampleActive'
/>
<ComponentExample
title='Success'
description='A progress bar can show a success state.'
examplePath='modules/Progress/States/ProgressExampleSuccess'
/>
<ComponentExample
title='Warning'
description='A progress bar can show a warning state.'
examplePath='modules/Progress/States/ProgressExampleWarning'
/>
<ComponentExample
title='Error'
description='A progress bar can show an error state.'
examplePath='modules/Progress/States/ProgressExampleError'
/>
<ComponentExample
title='Disabled'
description='A progress bar can be disabled.'
examplePath='modules/Progress/States/ProgressExampleDisabled'
/>
</ExampleSection>
)
export default ProgressStatesExamples
|
src/svg-icons/av/play-circle-outline.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvPlayCircleOutline = (props) => (
<SvgIcon {...props}>
<path d="M10 16.5l6-4.5-6-4.5v9zM12 2C6.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 8z"/>
</SvgIcon>
);
AvPlayCircleOutline = pure(AvPlayCircleOutline);
AvPlayCircleOutline.displayName = 'AvPlayCircleOutline';
AvPlayCircleOutline.muiName = 'SvgIcon';
export default AvPlayCircleOutline;
|